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

feature #4186: Merge branch 'feature-4217' into feature-4186

Marketplace branch into vcenter storage
This commit is contained in:
Tino Vazquez 2016-02-10 12:25:28 +01:00
commit 006ba41c62
385 changed files with 22218 additions and 7046 deletions

View File

@ -84,6 +84,8 @@ main_env.Append(LIBPATH=[
cwd+'/src/client',
cwd+'/src/secgroup',
cwd+'/src/vdc',
cwd+'/src/vrouter',
cwd+'/src/market'
])
# Compile flags
@ -244,6 +246,8 @@ build_scripts=[
'src/zone/SConstruct',
'src/secgroup/SConstruct',
'src/vdc/SConstruct',
'src/vrouter/SConstruct',
'src/market/SConstruct',
'share/man/SConstruct',
'src/sunstone/public/locale/languages/SConstruct',
'src/sunstone/public/SConstruct',

View File

@ -121,9 +121,11 @@ public:
* A vector containing just -1 means all VMs.
* @param vnet_ids list of VNET the user can access reservation info from.
* A vector containing just -1 means all VNETs.
* @param vrs list of VRouter the user can access VNET usage info from.
* A vector containing just -1 means all VRouters.
*/
void to_xml(ostringstream &oss, const vector<int>& vms,
const vector<int>& vnets) const;
const vector<int>& vnets, const vector<int>& vrs) const;
// *************************************************************************
// Address allocation functions
@ -344,7 +346,7 @@ public:
*/
friend int AddressRangePool::add_ar(AddressRange * ar);
static void set_restricted_attributes(vector<const Attribute *>& rattrs);
static void set_restricted_attributes(vector<const SingleAttribute *>& rattrs);
private:
/* ---------------------------------------------------------------------- */

View File

@ -82,7 +82,7 @@ public:
* the reason.
* @return 0 on success
*/
int update_ar(vector<Attribute *> ars, bool keep_restricted, string& error_msg);
int update_ar(vector<VectorAttribute *> ars, bool keep_restricted, string& error_msg);
/**
* Allocates a new *empty* address range. It is not added to the pool as it
@ -341,10 +341,12 @@ public:
* A vector containing just -1 means all VMs.
* @param vnet_ids list of VNET the user can access reservation info from.
* A vector containing just -1 means all VNETs.
* @param vrs list of VRouter the user can access VNET usage info from.
* A vector containing just -1 means all VRouters.
* @return the string with the XML
*/
string& to_xml(string& sstream, bool extended, const vector<int>& vms,
const vector<int>& vnets) const;
const vector<int>& vnets, const vector<int>& vrs) const;
private:
/**

View File

@ -247,84 +247,81 @@ public:
string vector_value(const char *name) const;
/**
* Returns the string value
* @param name of the attribute
* @param value of the value
* Returns the value of the given element of the VectorAttribute
*
* @return 0 if the attribute was found, -1 otherwise
* @param name of the attribute
* @param value, not set if the element is not found of has invalid type
*
* @return 0 on success, -1 otherwise
*/
template<typename T>
int vector_value(const char *name, T& value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
return -1;
}
if ( it->second.empty() )
{
return -1;
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
return -1;
}
return 0;
}
int vector_value(const char *name, string& value) const;
/**
* Returns the boolean value
* @param name of the attribute
* @param value Bool value ("YES" is true)
*
* @return 0 on success, -1 otherwise
*/
int vector_value(const char *name, bool& value) const;
/**
* Returns the integer value
*
* @param name Name of the attribute
* @param value Integer value
*
* @return 0 on success, -1 otherwise
*/
int vector_value(const char *name, int& value) const;
/**
* Returns the unsigned integer value
*
* @param name Name of the attribute
* @param value Integer value
*
* @return 0 on success, -1 otherwise
*/
int vector_value(const char *name, unsigned int& value) const;
/**
* Returns the long long value
*
* @param name Name of the attribute
* @param value Long long value
*
* @return 0 on success, -1 otherwise
*/
int vector_value(const char *name, long long& value) const;
/**
* Returns the float value
*
* @param name Name of the attribute
* @param value Float value
*
* @return 0 on success, -1 otherwise
*/
int vector_value(const char *name, float& value) const;
/**
* Returns the integer value
*
* @param name Name of the attribute
* @param value Integer value, if an error occurred the string returned is
* empty and value set to -1;
* empty and value is not set
*
* @return the value in string form on success, "" otherwise
*/
string vector_value_str(const char *name, int& value) const;
template<typename T>
string vector_value_str(const char *name, T& value) const
{
map<string,string>::const_iterator it;
/**
* Returns the float value
*
* @param name Name of the attribute
* @param value Float value, if an error occurred the string returned is
* empty and value set to -1;
*
* @return the value in string form on success, "" otherwise
*/
string vector_value_str(const char *name, float& value) const;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
return "";
}
if ( it->second.empty() )
{
return "";
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
return "";
}
return it->second;
}
/**
* Marshall the attribute in a single string. The string MUST be freed
@ -375,12 +372,8 @@ public:
/**
* Replace the value of the given vector attribute
*/
void replace(const string& name, const string& value);
/**
* Replace the value of the given vector attribute
*/
void replace(const string& name, int value)
template<typename T>
void replace(const string& name, T value)
{
ostringstream oss;
@ -389,59 +382,20 @@ public:
replace(name, oss.str());
}
/**
* Replace the value of the given vector attribute
*/
void replace(const string& name, unsigned int value)
{
ostringstream oss;
oss << value;
replace(name, oss.str());
}
/**
* Replace the value of the given vector attribute
*/
void replace(const string& name, long long value)
{
ostringstream oss;
oss << value;
replace(name, oss.str());
}
/**
* Replace the value of the given vector attribute
*/
void replace(const string& name, const char* value)
{
string svalue(value);
replace(name, svalue);
}
/**
* Replace the value of the given vector attribute
*/
void replace(const string& name, bool value)
{
string b_value;
if (value == true)
{
b_value = "YES";
replace(name, "YES");
}
else
{
b_value = "NO";
replace(name, "NO");
}
replace(name, b_value);
}
void replace(const string& name, const string& value);
/**
* Removes given the vector attribute
* @param name of the vector attribute

View File

@ -41,7 +41,7 @@ public:
AuthManager(
time_t timer,
vector<const Attribute*>& _mads):
vector<const VectorAttribute*>& _mads):
MadManager(_mads), timer_period(timer)
{
am.addListener(this);

View File

@ -100,15 +100,6 @@ public:
return name;
};
/** Update a particular Cluster
* @param user pointer to Cluster
* @return 0 on success
*/
int update(Cluster * cluster)
{
return cluster->update(db);
};
/**
* Drops the Cluster from the data base. The object mutex SHOULD be
* locked.

View File

@ -26,7 +26,7 @@ using namespace std;
class DatastorePool : public PoolSQL
{
public:
DatastorePool(SqlDB * db, const vector<const Attribute *>& _inherit_attrs);
DatastorePool(SqlDB * db, const vector<const SingleAttribute *>& _inherit_attrs);
~DatastorePool(){};
@ -135,15 +135,6 @@ public:
return name;
};
/** Update a particular Datastore
* @param user pointer to Datastore
* @return 0 on success
*/
int update(Datastore * datastore)
{
return datastore->update(db);
};
/**
* Drops the Datastore data in the data base. The object mutex SHOULD be
* locked.

View File

@ -76,18 +76,6 @@ public:
return static_cast<Document *>(PoolSQL::get(oid,lock));
};
/**
* Updates the object's data in the data base. The object mutex SHOULD be
* locked.
* @param objsql a pointer to the object
*
* @return 0 on success.
*/
int update(Document * document)
{
return document->update(db);
};
/**
* Dumps the pool in XML format. A filter can be also added to the
* query

View File

@ -26,10 +26,8 @@ using namespace std;
class GroupPool : public PoolSQL
{
public:
GroupPool(SqlDB * db,
vector<const Attribute *> hook_mads,
const string& remotes_location,
bool is_federation_slave);
GroupPool(SqlDB * db, vector<const VectorAttribute *> hook_mads,
const string& remotes_location, bool is_federation_slave);
~GroupPool(){};
@ -118,7 +116,7 @@ public:
* @param user pointer to Group
* @return 0 on success
*/
int update(Group * group);
int update(PoolObjectSQL * objsql);
/**
* Update a particular Group's Quotas

View File

@ -30,7 +30,7 @@ class HookManager : public MadManager, public ActionListener
{
public:
HookManager(vector<const Attribute*>& _mads, VirtualMachinePool * _vmpool)
HookManager(vector<const VectorAttribute*>& _mads, VirtualMachinePool * _vmpool)
:MadManager(_mads),vmpool(_vmpool)
{
am.addListener(this);

View File

@ -383,7 +383,7 @@ public:
* @return 0 on success
*/
void add_capacity(int vm_id, long long cpu, long long mem, long long disk,
vector<Attribute *> pci)
vector<VectorAttribute *> pci)
{
if ( vm_collection.add_collection_id(vm_id) == 0 )
{
@ -410,7 +410,7 @@ public:
* @return 0 on success
*/
void del_capacity(int vm_id, long long cpu, long long mem, long long disk,
vector<Attribute *> pci)
vector<VectorAttribute *> pci)
{
if ( vm_collection.del_collection_id(vm_id) == 0 )
{
@ -449,7 +449,7 @@ public:
* @return true if the share can host the VM
*/
bool test_capacity(long long cpu, long long mem, long long disk,
vector<Attribute *> &pci, string& error) const
vector<VectorAttribute *> &pci, string& error) const
{
return host_share.test(cpu, mem, disk, pci, error);
}
@ -461,7 +461,7 @@ public:
* @param error Returns the error reason, if any
* @return true if the share can host the VM
*/
bool test_capacity(vector<Attribute *> &pci, string& error) const
bool test_capacity(vector<VectorAttribute *> &pci, string& error) const
{
return host_share.test(pci, error);
}

View File

@ -35,11 +35,9 @@ using namespace std;
class HostPool : public PoolSQL
{
public:
HostPool(SqlDB * db,
vector<const Attribute *> hook_mads,
const string& hook_location,
const string& remotes_location,
time_t expire_time);
HostPool(SqlDB * db, vector<const VectorAttribute *> hook_mads,
const string& hook_location, const string& remotes_location,
time_t expire_time);
~HostPool(){};
@ -128,7 +126,7 @@ public:
* @return 0 on success -1 in case of failure
*/
int add_capacity(int oid, int vm_id, int cpu, int mem, int disk,
vector<Attribute *> pci)
vector<VectorAttribute *> pci)
{
int rc = 0;
Host * host = get(oid, true);
@ -159,7 +157,7 @@ public:
* @param pci devices requested by the VM
*/
void del_capacity(int oid, int vm_id, int cpu, int mem, int disk,
vector<Attribute *> pci)
vector<VectorAttribute *> pci)
{
Host * host = get(oid, true);

View File

@ -79,7 +79,7 @@ public:
* @param devs list of requested devices by the VM.
* @return true if all the devices are available.
*/
bool test(const vector<Attribute *> &devs) const;
bool test(const vector<VectorAttribute *> &devs) const;
/**
* Assign the requested devices to the given VM. The assigned devices will
@ -89,18 +89,18 @@ public:
* assigned devices.
* @param vmid of the VM
*/
void add(vector<Attribute *> &devs, int vmid);
void add(vector<VectorAttribute *> &devs, int vmid);
/**
* Remove the VM assignment from the PCI device list
*/
void del(const vector<Attribute *> &devs);
void del(const vector<VectorAttribute *> &devs);
/**
* Updates the PCI list with monitor data, it will create or
* remove PCIDevices as needed.
*/
void set_monitorization(vector<Attribute*> &pci_att);
void set_monitorization(vector<VectorAttribute*> &pci_att);
/**
* Prints the PCI device list to an output stream. This function is used
@ -122,7 +122,7 @@ private:
/**
* Sets the internal class structures from the template
*/
int init();
void init();
/**
* Internal structure to represent PCI devices for fast look up and
@ -171,7 +171,7 @@ public:
* @param pci_devs requested by the VM
*/
void add(int vmid, long long cpu, long long mem, long long disk,
vector<Attribute *> pci_devs)
vector<VectorAttribute *> pci_devs)
{
cpu_usage += cpu;
mem_usage += mem;
@ -202,7 +202,8 @@ public:
* @param disk requested by the VM
* @param pci_devs requested by the VM
*/
void del(long long cpu, long long mem, long long disk, vector<Attribute *> pci_devs)
void del(long long cpu, long long mem, long long disk,
vector<VectorAttribute *> pci_devs)
{
cpu_usage -= cpu;
mem_usage -= mem;
@ -225,7 +226,7 @@ public:
* configured
*/
bool test(long long cpu, long long mem, long long disk,
vector<Attribute *>& pci_devs, string& error) const
vector<VectorAttribute *>& pci_devs, string& error) const
{
bool pci_fits = pci.test(pci_devs);
@ -257,7 +258,7 @@ public:
* @return true if the share can host the VM or it is the only one
* configured
*/
bool test(vector<Attribute *>& pci_devs, string& error) const
bool test(vector<VectorAttribute *>& pci_devs, string& error) const
{
bool fits = pci.test(pci_devs);
@ -282,9 +283,9 @@ public:
*/
string& to_xml(string& xml) const;
void set_ds_monitorization(const vector<Attribute*> &ds_att);
void set_ds_monitorization(const vector<VectorAttribute*> &ds_att);
void set_pci_monitorization(vector<Attribute*> &pci_att)
void set_pci_monitorization(vector<VectorAttribute*> &pci_att)
{
pci.set_monitorization(pci_att);
}

View File

@ -37,7 +37,7 @@ public:
time_t _monitor_period,
ImagePool * _ipool,
DatastorePool * _dspool,
vector<const Attribute*>& _mads):
vector<const VectorAttribute*>& _mads):
MadManager(_mads),
timer_period(_timer_period),
monitor_period(_monitor_period),
@ -115,8 +115,8 @@ public:
/**
* Closes any cloning operation on the image, updating the state if needed
* @param iid image id of the image to be released
* @param clone_img_id image id of the image that was being cloned
* @param iid image id of the image to that was being cloned
* @param clone_img_id the cloned image (id > 0) or market app (id =< 0)
*/
void release_cloning_image(int iid, int clone_img_id);
@ -133,11 +133,15 @@ public:
* Adds a new image to the repository copying or creating it as needed
* @param img pointer to the image
* @param ds_data data of the associated datastore in XML format
* @param extra_data data to be sent to the driver
* @param error Error reason
*
* @return 0 on success
*/
int register_image(int iid, const string& ds_data, string& error);
int register_image(int iid,
const string& ds_data,
const string& extra_data,
string& error);
/**
* Checks if an image is ready to be cloned
@ -147,22 +151,31 @@ public:
*
* @return 0 if the image can be cloned, -1 otherwise
*/
int can_clone_image(int cloning_id,
ostringstream& oss_error);
int can_clone_image(int cloning_id, ostringstream& oss_error);
/**
* Sets the state to CLONE for the given image
* @param new_id for the target image (new_id>0) or market app (new_id =<0)
* @param clonning_id the ID of the image to be cloned
* @param error if any
* @return 0 if siccess
*/
int set_clone_state(int new_id, int cloning_id, std::string& error);
/**
* Clone an existing image to the repository
* @param new_id of the new image
* @param cloning_id of the image to be cloned
* @param ds_data data of the associated datastore in XML format
* @param extra_data data to be sent to the driver
* @param error describing the error
* @return 0 on success
*/
int clone_image(int new_id,
int cloning_id,
const string& ds_data,
const string& extra_data,
string& error);
/**
* Deletes an image from the repository and the DB. The Datastore image list
* is also updated

View File

@ -41,14 +41,14 @@ class ImagePool : public PoolSQL
public:
ImagePool(
SqlDB * db,
const string& __default_type,
const string& __default_dev_prefix,
const string& __default_cdrom_dev_prefix,
vector<const Attribute *>& restricted_attrs,
vector<const Attribute *> hook_mads,
const string& remotes_location,
const vector<const Attribute *>& _inherit_image_attrs);
SqlDB * db,
const string& __default_type,
const string& __default_dev_prefix,
const string& __default_cdrom_dev_prefix,
vector<const SingleAttribute *>& restricted_attrs,
vector<const VectorAttribute *>& hook_mads,
const string& remotes_location,
const vector<const SingleAttribute *>& _inherit_image_attrs);
~ImagePool(){};
@ -65,6 +65,7 @@ public:
* @param ds_type disk type for the image
* @param ds_data the datastore data
* @param ds_type the datastore type
* @param extra_data extra data that will be sent to the driver
* @param source_img_id If the new Image is a clone, this must be the
* source Image ID. Otherwise, it must be set to -1
* @param oid the id assigned to the Image
@ -85,6 +86,7 @@ public:
Image::DiskType disk_type,
const string& ds_data,
Datastore::DatastoreType ds_type,
const string& extra_data,
int source_img_id,
int * oid,
string& error_str);
@ -115,16 +117,6 @@ public:
return static_cast<Image *>(PoolSQL::get(name,uid,lock));
};
/**
* Update a particular Image
* @param image pointer to Image
* @return 0 on success
*/
int update(Image * image)
{
return image->update(db);
};
/**
* Bootstraps the database table(s) associated to the Image pool
* @return 0 on success

View File

@ -88,7 +88,7 @@ private:
* ImageTemplate::check
* @param rattrs Attributes to restrict
*/
static void set_restricted_attributes(vector<const Attribute *>& rattrs)
static void set_restricted_attributes(vector<const SingleAttribute *>& rattrs)
{
Template::set_restricted_attributes(rattrs, restricted_attributes);
};

View File

@ -41,7 +41,7 @@ public:
int _host_limit,
int _monitor_threads,
const string& _remotes_location,
vector<const Attribute*>& _mads)
vector<const VectorAttribute*>& _mads)
:MadManager(_mads),
hpool(_hpool),
clpool(_clpool),

View File

@ -64,7 +64,7 @@ public:
protected:
MadManager(vector<const Attribute *>& _mads);
MadManager(vector<const VectorAttribute *>& _mads);
virtual ~MadManager();
@ -72,7 +72,7 @@ protected:
* Vector containing Mad configuration for this Manager, as described in
* the nebula location
*/
vector<const Attribute *> mad_conf;
vector<const VectorAttribute *> mad_conf;
/**
* This function initialize the communication pipes to register new MADs

202
include/MarketPlace.h Normal file
View File

@ -0,0 +1,202 @@
/* ------------------------------------------------------------------------ */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACE_H_
#define MARKETPLACE_H_
#include "PoolSQL.h"
#include "ObjectCollection.h"
#include "MarketPlaceTemplate.h"
/**
* The MarketPlace class. It represents an abstract container for OpenNebula
* objects (Image, VM Templates or Flows)
*/
class MarketPlace : public PoolObjectSQL, ObjectCollection
{
public:
/**
* Function to print the MarketPlace object into a string in XML format
* @param xml the resulting XML string
* @return a reference to the generated string
*/
string& to_xml(string& xml) const;
/**
* Rebuilds the object from an xml formatted string
* @param xml_str The xml-formatted string
*
* @return 0 on success, -1 otherwise
*/
int from_xml(const string &xml_str);
/**
* Adds this marketplace app's ID to the set.
* @param id of the app to be added to the MarketPlace
* @return 0 on success
*/
int add_marketapp(int id)
{
return add_collection_id(id);
};
/**
* Deletes this image's ID from the set.
* @param id of the image to be deleted from the MarketPlace
* @return 0 on success
*/
int del_marketapp(int id)
{
return del_collection_id(id);
};
/**
* Returns a copy of the Image IDs set
*/
set<int> get_marketapp_ids()
{
return get_collection_copy();
}
/**
* Retrieves marketplace mad name
* @return string mp mad name
*/
const string& get_market_mad() const
{
return market_mad;
};
/**
* Set monitor information for the MarketPlace
* @param data template with monitor information
*/
void update_monitor(const Template& data);
private:
friend class MarketPlacePool;
// *************************************************************************
// MarketPlace Attributes
// *************************************************************************
/**
* Name of the marketplace driver used to import apps
*/
string market_mad;
/**
* Total capacity in MB
*/
long long total_mb;
/**
* Available capacity in MB
*/
long long free_mb;
/**
* Used capacity in MB
*/
long long used_mb;
// *************************************************************************
// Constructor
// *************************************************************************
MarketPlace(
int uid,
int gid,
const string& uname,
const string& gname,
int umask,
MarketPlaceTemplate* mp_template);
virtual ~MarketPlace();
// *************************************************************************
// DataBase implementation (Private)
// *************************************************************************
static const char * db_names;
static const char * db_bootstrap;
static const char * table;
/**
* Execute an INSERT or REPLACE Sql query.
* @param db The SQL DB
* @param replace Execute an INSERT or a REPLACE
* @param error_str Returns the error reason, if any
* @return 0 one success
*/
int insert_replace(SqlDB *db, bool replace, string& error_str);
/**
* Bootstraps the database table(s) associated to the MarketPlace
* @return 0 on success
*/
static int bootstrap(SqlDB * db)
{
ostringstream oss(db_bootstrap);
return db->exec(oss);
};
/**
* Writes the MarketPlace in the database.
* @param db pointer to the db
* @return 0 on success
*/
int insert(SqlDB *db, string& error_str);
/**
* Writes/updates the MarketPlace's data fields in the database.
* @param db pointer to the db
* @return 0 on success
*/
int update(SqlDB *db)
{
string error_str;
return insert_replace(db, true, error_str);
}
/**
* Factory method for marketplace templates
*/
Template * get_new_template() const
{
return new MarketPlaceTemplate;
}
/**
* Verify the proper definition of the Market by checking the
* attributes of the MARKET_MAD_CONF parameter
*/
int set_market_mad(string &tm_mad, string &error_str);
/**
* Child classes can process the new template set with replace_template or
* append_template with this method
* @param error string describing the error if any
* @return 0 on success
*/
int post_update_template(string& error);
};
#endif /*MARKETPLACE_H*/

388
include/MarketPlaceApp.h Normal file
View File

@ -0,0 +1,388 @@
/* ------------------------------------------------------------------------ */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACEAPP_H_
#define MARKETPLACEAPP_H_
#include "PoolSQL.h"
#include "ObjectCollection.h"
#include "MarketPlaceAppTemplate.h"
/**
* The MarketPlaceApp class. It represents an abstract application for
* OpenNebula objects (Image, VM Templates or Flows)
*/
class MarketPlaceApp : public PoolObjectSQL
{
public:
/**
* MarketPlaceApp states
*/
enum MarketPlaceAppState
{
INIT = 0, /** < Initialization state */
READY = 1, /** < Ready to use */
LOCKED = 2, /** < Operation in process */
ERROR = 3, /** < Error state the operation failed*/
DISABLED = 4
};
/**
* Returns the string representation of an MarketplaceApp State
* @param state The state
* @return the string representation
*/
static string state_to_str(MarketPlaceAppState state)
{
switch(state)
{
case INIT: return "INIT"; break;
case READY: return "READY"; break;
case LOCKED: return "LOCKED"; break;
case ERROR: return "ERROR"; break;
case DISABLED: return "DISABLED"; break;
default: return "";
}
};
/**
* MarketPlaceApp container types
*/
enum MarketPlaceAppType
{
UNKNOWN = 0, /** < Unknown types */
IMAGE = 1, /** < Image MarketPlace App*/
VMTEMPLATE = 2, /** < VM Template MarketPlace App*/
SERVICE_TEMPLATE = 3 /** < Service Template MarketPlace App*/
};
/**
* Return the string representation of a MarketPlaceType
* @param ob the type
* @return the string
*/
static string type_to_str(MarketPlaceAppType ob)
{
switch (ob)
{
case IMAGE: return "IMAGE"; break;
case VMTEMPLATE: return "VMTEMPLATE"; break;
case SERVICE_TEMPLATE: return "SERVICE_TEMPLATE"; break;
default: return "";
}
};
/**
* Return the string representation of a MarketPlaceType, By default it will
* return IMAGE_MP.
* @param str_type string representing the type
* @return the MarketPlaceType
*/
static MarketPlaceAppType str_to_type(string& str_type);
/**
* Function to print the MarketPlaceApp object into a string in XML format
* @param xml the resulting XML string
* @return a reference to the generated string
*/
string& to_xml(std::string& xml) const;
/**
* Rebuilds the object from an xml formatted string
* @param xml_str The xml-formatted string
*
* @return 0 on success, -1 otherwise
*/
int from_xml(const std::string &xml_str);
/**
* Rebuilds the object from base64 encoded template representation
* @param str The template string, base64 encoded
* @param error_str Returns the error reason, if any
*
* @return 0 on success, -1 otherwise
*/
int from_template64(const std::string &xml_str, std::string& error_str);
/**
* Copies the special attributes of the App to the template
* @param tmp The template object
* @param error_str Returns the error reason, if any
*/
void to_template(Template * tmpl) const;
/**
* Enable or disable the app. A disabled app cannot be exported
* @param enable true to enable
* @param error_str Returns the error reason, if any
*
* @return 0 on success
*/
int enable(bool enable, std::string& error_str);
/**
* Returns the marketplace ID
*/
int get_market_id() const
{
return market_id;
};
/**
* Returns the marketplace name
*/
const std::string& get_market_name() const
{
return market_name;
};
/**
* Updates the marketplace name
*/
void set_market_name(const std::string& name)
{
market_name = name;
};
/**
* Returns the marketplace app type
* @return marketplace app type
*/
MarketPlaceAppType get_type() const
{
return type;
};
/**
* Returns the ID of the object originating this app
* @return the image, vmtemplate or flow id
*/
int get_origin_id() const
{
return origin_id;
};
const string& get_source() const
{
return source;
}
const string& get_md5() const
{
return md5;
}
long long get_size() const
{
return size_mb;
}
const string& get_format() const
{
return format;
}
MarketPlaceAppState get_state() const
{
return state;
}
//--------------------------------------------------------------------------
// Set Marketplace app attributes
//--------------------------------------------------------------------------
void set_state(MarketPlaceAppState _state)
{
state = _state;
};
void set_source(const std::string& _source)
{
source = _source;
};
void set_md5(const std::string& _md5)
{
md5 = _md5;
};
void set_size(long long _size_mb)
{
size_mb = _size_mb;
};
void set_format(const std::string& _format)
{
format = _format;
};
private:
friend class MarketPlaceAppPool;
// *************************************************************************
// MarketPlaceApp Attributes
// *************************************************************************
/**
* Publishing date
*/
time_t date;
/**
* Source URL for the marketplace app
*/
std::string source;
/**
* Source URL for the marketplace app
*/
std::string md5;
/**
* Size of this app
*/
long long size_mb;
/**
* Description of the App
*/
std::string description;
/**
* User sharing the app
*/
std::string publisher;
/**
* Version of the app
*/
std::string version;
/**
* format of the disk images
*/
std::string format;
/**
* App template to import it
*/
std::string apptemplate64;
/**
* Marketplace ID that holds this app
*/
int market_id;
/**
* Marketplace name
*/
std::string market_name;
/**
* Marketplace App state
*/
MarketPlaceAppState state;
/**
* The marketplace type
*/
MarketPlaceAppType type;
/**
* Origin of this App
*/
int origin_id;
// *************************************************************************
// Constructor
// *************************************************************************
MarketPlaceApp(
int uid,
int gid,
const std::string& uname,
const std::string& gname,
int umask,
MarketPlaceAppTemplate* app_template);
virtual ~MarketPlaceApp();
// *************************************************************************
// DataBase implementation (Private)
// *************************************************************************
static const char * db_names;
static const char * db_bootstrap;
static const char * table;
/**
* Execute an INSERT or REPLACE Sql query.
* @param db The SQL DB
* @param replace Execute an INSERT or a REPLACE
* @param error_str Returns the error reason, if any
* @return 0 one success
*/
int insert_replace(SqlDB *db, bool replace, std::string& error_str);
/**
* Bootstraps the database table(s) associated to the MarketPlace
* @return 0 on success
*/
static int bootstrap(SqlDB * db)
{
ostringstream oss(db_bootstrap);
return db->exec(oss);
};
/**
* Writes the MarketPlace in the database.
* @param db pointer to the db
* @return 0 on success
*/
int insert(SqlDB *db, std::string& error_str);
/**
* Writes/updates the MarketPlace's data fields in the database.
* @param db pointer to the db
* @return 0 on success
*/
int update(SqlDB *db)
{
std::string error_str;
return insert_replace(db, true, error_str);
}
/**
* Child classes can process the new template set with replace_template or
* append_template with this method
* @param error string describing the error if any
* @return 0 on success
*/
int post_update_template(std::string& error);
/**
* Factory method for marketplace app templates
*/
Template * get_new_template() const
{
return new MarketPlaceAppTemplate;
}
};
#endif /*MARKETPLACEAPP_H*/

View File

@ -0,0 +1,143 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACEAPP_POOL_H_
#define MARKETPLACEAPP_POOL_H_
#include "MarketPlaceApp.h"
class SqlDB;
class MarketPlaceAppPool : public PoolSQL
{
public:
MarketPlaceAppPool(SqlDB * db):PoolSQL(db,MarketPlaceApp::table,true,true){};
~MarketPlaceAppPool(){};
/* ---------------------------------------------------------------------- */
/* Methods for DB management */
/* ---------------------------------------------------------------------- */
/**
* Allocates a new MarketPlaceApp, writing it in the pool database.
* @param uid the user id of the MarketPlace owner
* @param gid the id of the group this object is assigned to
* @param uname name of the user
* @param gname name of the group
* @param umask permissions umask
* @param apptemplate MarketPlaceApp definition template
* @param mp_id of the MarketPlace to store de App
* @param mp_name of the MarketPlace
* @param mp_data XML representation of the target MarketPlace
* @param oid the id assigned to the MarketPlace
* @param error_str Returns the error reason, if any
*
* @return the oid assigned to the object, -1 in case of failure
*/
int allocate(
int uid,
int gid,
const std::string& uname,
const std::string& gname,
int umask,
MarketPlaceAppTemplate * apptemplate,
int mp_id,
const std::string& mp_name,
const std::string& mp_data,
int * oid,
std::string& error_str);
/**
* Imports an app into the marketplace, as reported by the monitor driver
* @param template to generate app with the from_template64 function
* @param mp_id of the MarketPlace to store de App
* @param mp_name of the MarketPlace
* @param error_str Returns the error reason, if any
*
* @return 0 on success
*/
int import(const std::string& t64, int mp_id, const std::string& mp_name,
std::string& error_str);
/**
* Function to get a MarketPlaceApp from the pool
* @param oid MarketPlaceApp unique id
* @param lock locks the MarketPlaceApp mutex
* @return a pointer to the MarketPlaceApp, 0 if not loaded
*/
MarketPlaceApp * get(int oid, bool lock)
{
return static_cast<MarketPlaceApp *>(PoolSQL::get(oid,lock));
};
/**
* Gets an object from the pool (if needed the object is loaded from the
* database).
* @param name of the object
* @param uid id of owner
* @param lock locks the object if true
*
* @return a pointer to the object, 0 in case of failure
*/
MarketPlaceApp * get(const std::string& name, int uid, bool lock)
{
return static_cast<MarketPlaceApp *>(PoolSQL::get(name, uid, lock));
};
/**
* Bootstraps the database table(s) associated to the MarketPlace pool
* @return 0 on success
*/
static int bootstrap(SqlDB * _db)
{
return MarketPlaceApp::bootstrap(_db);
};
/**
* Dumps the MarketPlace pool in XML format. A filter can be also added to
* the query
* @param oss the output stream to dump the pool contents
* @param where filter for the objects, defaults to all
* @param limit parameters used for pagination
*
* @return 0 on success
*/
int dump(std::ostringstream& oss, const std::string& where,
const std::string& limit)
{
return PoolSQL::dump(oss, "MARKETPLACEAPP_POOL", MarketPlaceApp::table,
where, limit);
};
/** Update a particular MarketPlaceApp
* @param zone pointer to Zone
* @return 0 on success
*/
int update(PoolObjectSQL * objsql);
private:
/**
* Factory method to produce objects
* @return a pointer to the new object
*/
PoolObjectSQL * create()
{
return new MarketPlaceApp(-1,-1,"","", 0, 0);
};
};
#endif /*MARKETPLACE_POOL_H_*/

View File

@ -0,0 +1,37 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACEAPP_TEMPLATE_H_
#define MARKETPLACEAPP_TEMPLATE_H_
#include "Template.h"
/**
* Datastore Template class
*/
class MarketPlaceAppTemplate : public Template
{
public:
MarketPlaceAppTemplate():
Template(false,'=',"TEMPLATE"){};
~MarketPlaceAppTemplate(){};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
#endif /*MARKETPLACEAPP_TEMPLATE_H_*/

View File

@ -0,0 +1,227 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACE_MANAGER_H_
#define MARKETPLACE_MANAGER_H_
#include "MadManager.h"
#include "ActionManager.h"
#include "MarketPlaceManagerDriver.h"
extern "C" void * marketplace_action_loop(void *arg);
class MarketPlacePool;
class MarketPlaceAppPool;
class ImagePool;
class DatastorePool;
class ImageManager;
class MarketPlaceManager : public MadManager, public ActionListener
{
public:
/**
* Inititalizes the Marketplace manager:
* @param t, timer_period to wake up the manger to perform actions
* @param m, monitor_period to monitor marketplaces
* @param mad, list of drivers for the manager
*/
MarketPlaceManager(time_t t, time_t m, std::vector<const VectorAttribute*>& mad);
~MarketPlaceManager(){};
/**
* Initializes internal pointers to other managers. Must be called when
* all the other managers exist in Nebula::instance
*/
void init_managers();
/**
* This functions starts the associated listener thread, and creates a
* new thread for the MarketPlace Manager. This thread will wait in
* an action loop till it receives ACTION_FINALIZE.
* @return 0 on success.
*/
int start();
/**
* Loads the MarketPlace Driver 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.
*/
int load_mads(int uid=0);
/**
* Gets the thread identification.
* @return pthread_t for the manager thread (that in the action loop).
*/
pthread_t get_thread_id() const
{
return marketm_thread;
};
/**
* Finalizes the Image Manager
*/
void finalize()
{
am.trigger(ACTION_FINALIZE,0);
};
/**
* Imports a new app into the marketplace. The marketplace app needs to
* include the ORIGIN_ID attribute so the driver can locate the app. An
* optional template maybe provided to export the app to a cloud.
* @param appid of the app
* @param market_data of the associated marketplace in XML format
* @param error descrition
*
* @return 0 on success
*/
int import_app(int appid, const std::string& market_data, std::string& err);
/**
* Exports the app to this cloud. If an APPTEMPLATE64 is provided associated
* objects can also be created.
* @param appid of the app
* @param market_data of the associated marketplace in XML format
* @param error descrition
*
* @return 0 on success
*/
int export_app(int appid, const std::string& market_data, std::string& err);
/**
* Deletes an app from the marketplace.
* @param appid of the app
* @param market_data of the associated marketplace in XML format
* @param error descrition
*
* @return 0 on success
*/
int delete_app(int appid, const std::string& market_data, std::string& err);
/**
* Trigger a monitor action for the marketplace .
* @param ds_id id of the datastore to monitor
*/
void monitor_market(int ds_id);
/**
* Relsease resources locked by this app during the import phase
* @param appid of the app
*/
void release_app_resources(int appid);
private:
/**
* Generic name for the marketplace driver
*/
static const char * market_driver_name;
/**
* Thread id for the MarketPlace Manager
*/
pthread_t marketm_thread;
/**
* Timer period for the Image Manager.
*/
time_t timer_period;
/**
* Marketplace monitor interval
*/
time_t monitor_period;
/**
* Pointer to the marketplace pool
*/
MarketPlacePool * mppool;
/**
* Pointer to the app pool
*/
MarketPlaceAppPool * apppool;
/**
* Pointer to the image pool
*/
ImagePool * ipool;
/**
* Pointer to the image pool
*/
DatastorePool * dspool;
/**
* Pointer to the Image Manger
*/
ImageManager * imagem;
/**
* Action engine for the Manager
*/
ActionManager am;
/**
* Returns a pointer to the marketplace driver.
* @return the marketplace manager driver or 0 in not found
*/
const MarketPlaceManagerDriver * get()
{
std::string name("NAME");
return static_cast<const MarketPlaceManagerDriver *>
(MadManager::get(0, name, market_driver_name));
};
/**
* Function to execute the Manager action loop method within a new pthread
* (requires C linkage)
*/
friend void * marketplace_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 std::string& action, void * arg);
/**
* Formats an XML message for the MAD
*
* @param app_data marketplace app XML representation
* @param market_data marketplace XML representation
* @param extra_data additional XML formatted data for the driver
*
* @return the XML message
*/
static std::string * format_message(
const std::string& app_data,
const std::string& market_data,
const std::string& extra_data);
/**
* This function is executed periodically to monitor marketplaces..
*/
void timer_action();
};
#endif /*MARKETPLACE_MANAGER_H*/

View File

@ -0,0 +1,98 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACE_MANAGER_DRIVER_H_
#define MARKETPLACE_MANAGER_DRIVER_H_
#include <map>
#include <string>
#include <sstream>
#include "Mad.h"
class MarketPlacePool;
class MarketPlaceAppPool;
class MarketPlaceManager;
/**
* ImageManagerDriver represents the basic abstraction for Image Repository
* drivers. It implements the protocol and recover functions from the Mad
* interface.
*/
class MarketPlaceManagerDriver : public Mad
{
public:
MarketPlaceManagerDriver(int userid,
const std::map<string,string>& attrs,
bool sudo,
MarketPlacePool * _marketpool,
MarketPlaceAppPool * _apppool,
MarketPlaceManager * _marketm
):Mad(userid,attrs,sudo), marketpool(_marketpool), apppool(_apppool),
marketm(_marketm){};
virtual ~MarketPlaceManagerDriver(){};
/**
* Implements the Image Manager driver protocol.
* @param message the string read from the driver
*/
void protocol(const std::string& message) const;
/**
* TODO: What do we need here? Check on-going xfr?
*/
void recover();
private:
friend class MarketPlaceManager;
/**
* Reference to Marketplace related pools
*/
MarketPlacePool * marketpool;
MarketPlaceAppPool * apppool;
MarketPlaceManager * marketm;
/**
* Imports a new object into the marketplace
* @param oid of the app
* @param drv_msg xml data for the mad operation.
*/
void importapp(int oid, const std::string& drv_msg) const;
/**
* Deletes an app from the marketplace
* @param oid of the app
* @param drv_msg xml data for the mad operation.
*/
void deleteapp(int oid, const std::string& drv_msg) const;
/**
* Monitors the marketplace
* @param oid of the operation
* @param drv_msg xml data for the mad operation.
*/
void monitor(int oid, const std::string& drv_msg) const;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
#endif /*MARKETPLACE_MANAGER_DRIVER_H_*/

162
include/MarketPlacePool.h Normal file
View File

@ -0,0 +1,162 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 MARKETPLACE_POOL_H_
#define MARKETPLACE_POOL_H_
#include "MarketPlace.h"
#include "NebulaLog.h"
#include "SqlDB.h"
class SqlDB;
class MarketPlaceApp;
class MarketPlacePool : public PoolSQL
{
public:
MarketPlacePool(SqlDB * db);
~MarketPlacePool(){};
/* ---------------------------------------------------------------------- */
/* Methods for DB management */
/* ---------------------------------------------------------------------- */
/**
* Allocates a new MarketPlace, writing it in the pool database. No memory is
* allocated for the object.
* @param uid the user id of the MarketPlace owner
* @param gid the id of the group this object is assigned to
* @param uname name of the user
* @param gname name of the group
* @param umask permissions umask
* @param mp_template MarketPlace definition template
* @param oid the id assigned to the MarketPlace
* @param error_str Returns the error reason, if any
*
* @return the oid assigned to the object, -1 in case of failure
*/
int allocate(
int uid,
int gid,
const std::string& uname,
const std::string& gname,
int umask,
MarketPlaceTemplate * mp_template,
int * oid,
std::string& error_str);
/**
* Function to get a MarketPlace from the pool, the object is loaded if not
* in memory
* @param oid MarketPlace unique id
* @param lock locks the MarketPlace mutex
* @return a pointer to the MarketPlace, 0 if not loaded
*/
MarketPlace * get(int oid, bool lock)
{
return static_cast<MarketPlace *>(PoolSQL::get(oid,lock));
};
/**
* Gets an object from the pool (if needed the object is loaded from the
* database).
* @param name of the object
* @param lock locks the object if true
*
* @return a pointer to the object, 0 in case of failure
*/
MarketPlace * get(const std::string& name, bool lock)
{
return static_cast<MarketPlace *>(PoolSQL::get(name,-1,lock));
};
/**
* Generate an index key for the object
* @param name of the object
* @param uid owner of the object, only used if needed
*
* @return the key, a string
*/
string key(const std::string& name, int uid)
{
return name;
};
/** Update a particular MarketPlace
* @param objsql points to the market
* @return 0 on success
*/
int update(PoolObjectSQL * objsql);
/**
* Drops the MarketPlace data in the data base. The object mutex SHOULD be
* locked.
* @param objsql a pointer to the MarketPlace object
* @param error_msg Error reason, if any
* @return 0 on success, -1 DB error -3 MarketPlace's App ID set not empty
*/
int drop(PoolObjectSQL * objsql, std::string& error_msg);
/**
* Bootstraps the database table(s) associated to the MarketPlace pool
* @return 0 on success
*/
static int bootstrap(SqlDB * _db)
{
return MarketPlace::bootstrap(_db);
};
/**
* Dumps the MarketPlace pool in XML format. A filter can be also added to
* the query
* @param oss the output stream to dump the pool contents
* @param where filter for the objects, defaults to all
* @param limit parameters used for pagination
*
* @return 0 on success
*/
int dump(std::ostringstream& oss, const std::string& where,
const std::string& limit)
{
return PoolSQL::dump(oss, "MARKETPLACE_POOL", MarketPlace::table, where,
limit);
};
/**
* Lists the Datastore ids
* @param oids a vector with the oids of the objects.
*
* @return 0 on success
*/
int list(std::vector<int>& oids)
{
return PoolSQL::list(oids, MarketPlace::table);
}
private:
/**
* Factory method to produce objects
* @return a pointer to the new object
*/
PoolObjectSQL * create()
{
return new MarketPlace(-1,-1,"","", 0, 0);
};
};
#endif /*MARKETPLACE_POOL_H_*/

View File

@ -14,30 +14,24 @@
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
define(function(require) {
#ifndef MARKETPLACE_TEMPLATE_H_
#define MARKETPLACE_TEMPLATE_H_
/*
CONSTANTS
*/
#include "Template.h"
var TAB_ID = require('../tabId');
/**
* Datastore Template class
*/
class MarketPlaceTemplate : public Template
{
public:
MarketPlaceTemplate():
Template(false,'=',"TEMPLATE"){};
/*
FUNCTION DEFINITIONS
*/
~MarketPlaceTemplate(){};
};
function _pre(info, contextTabId) {
var element = info;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
$('.resource-id', '#' + TAB_ID).hide();
$('.resource-info-header', '#' + TAB_ID).text(element.name);
}
function _post(info, contextTabId) {
}
return {
'pre': _pre,
'post': _post
};
});
#endif /*MARKETPLACE_TEMPLATE_H_*/

View File

@ -34,6 +34,9 @@
#include "ZonePool.h"
#include "SecurityGroupPool.h"
#include "VdcPool.h"
#include "VirtualRouterPool.h"
#include "MarketPlacePool.h"
#include "MarketPlaceAppPool.h"
#include "VirtualMachineManager.h"
#include "LifeCycleManager.h"
@ -45,6 +48,7 @@
#include "AuthManager.h"
#include "AclManager.h"
#include "ImageManager.h"
#include "MarketPlaceManager.h"
#include "DefaultQuotas.h"
@ -136,6 +140,21 @@ public:
return vdcpool;
};
VirtualRouterPool * get_vrouterpool()
{
return vrouterpool;
};
MarketPlacePool * get_marketpool()
{
return marketpool;
};
MarketPlaceAppPool * get_apppool()
{
return apppool;
};
// --------------------------------------------------------------
// Manager Accessors
// --------------------------------------------------------------
@ -185,6 +204,11 @@ public:
return aclm;
};
MarketPlaceManager * get_marketm()
{
return marketm;
};
// --------------------------------------------------------------
// Environment & Configuration
// --------------------------------------------------------------
@ -378,33 +402,8 @@ public:
* @param name of the attribute
* @param value of the attribute
*/
void get_configuration_attribute(
const char * name,
string& value) const
{
string _name(name);
nebula_configuration->Template::get(_name, value);
};
/**
* Gets a configuration attribute for oned (long long version)
*/
void get_configuration_attribute(
const char * name,
long long& value) const
{
string _name(name);
nebula_configuration->Template::get(_name, value);
};
/**
* Gets a configuration attribute for oned (time_t version)
*/
void get_configuration_attribute(
const char * name,
time_t& value) const
template<typename T>
void get_configuration_attribute(const string& name, T& value) const
{
nebula_configuration->get(name, value);
};
@ -435,6 +434,13 @@ public:
const string& tm_name,
const VectorAttribute* &value) const;
/**
* Gets a Market configuration attribute
*/
int get_market_conf_attribute(
const string& tm_name,
const VectorAttribute* &value) const;
/**
* Gets an XML document with all of the configuration attributes
* @return the XML
@ -564,9 +570,10 @@ private:
"/DEFAULT_GROUP_QUOTAS/VM_QUOTA"),
system_db(0), db(0),
vmpool(0), hpool(0), vnpool(0), upool(0), ipool(0), gpool(0), tpool(0),
dspool(0), clpool(0), docpool(0), zonepool(0), secgrouppool(0), vdcpool(0),
dspool(0), clpool(0), docpool(0), zonepool(0),
secgrouppool(0), vdcpool(0), vrouterpool(0), marketpool(0), apppool(0),
lcm(0), vmm(0), im(0), tm(0), dm(0), rm(0), hm(0), authm(0),
aclm(0), imagem(0)
aclm(0), imagem(0), marketm(0)
{
const char * nl = getenv("ONE_LOCATION");
@ -614,6 +621,9 @@ private:
delete zonepool;
delete secgrouppool;
delete vdcpool;
delete vrouterpool;
delete marketpool;
delete apppool;
delete vmm;
delete lcm;
delete im;
@ -624,6 +634,7 @@ private:
delete authm;
delete aclm;
delete imagem;
delete marketm;
delete nebula_configuration;
delete db;
delete system_db;
@ -693,6 +704,9 @@ private:
ZonePool * zonepool;
SecurityGroupPool * secgrouppool;
VdcPool * vdcpool;
VirtualRouterPool * vrouterpool;
MarketPlacePool * marketpool;
MarketPlaceAppPool * apppool;
// ---------------------------------------------------------------
// Nebula Managers
@ -708,12 +722,31 @@ private:
AuthManager * authm;
AclManager * aclm;
ImageManager * imagem;
MarketPlaceManager * marketm;
// ---------------------------------------------------------------
// Implementation functions
// ---------------------------------------------------------------
friend void nebula_signal_handler (int sig);
// ---------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------
/**
* Gets a Generic configuration attribute
* @param key String that identifies the configuration parameter group name
* @param name Name of the specific configuration parameter
* @param value Value of the specific configuration parameter
* @return a reference to the generated string
*/
int get_conf_attribute(
const std::string& key,
const std::string& name,
const VectorAttribute* &value) const;
};
#endif /*NEBULA_H_*/

View File

@ -26,9 +26,6 @@
class NebulaTemplate : public Template
{
public:
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
NebulaTemplate(const string& etc_location, const char * _conf_name)
{
conf_file = etc_location + _conf_name;
@ -36,89 +33,6 @@ public:
virtual ~NebulaTemplate(){};
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
int get(const char * name, vector<const Attribute*>& values) const
{
string _name(name);
return Template::get(_name,values);
};
void get(const char * name, string& values) const
{
string _name(name);
Template::get(_name,values);
};
void get(const char * name, int& values) const
{
string _name(name);
Template::get(_name,values);
};
void get(const char *name, unsigned int& values) const
{
int ival;
NebulaTemplate::get(name, ival);
values = static_cast<unsigned int>(ival);
};
void get(const char * name, time_t& values) const
{
const SingleAttribute * sattr;
vector<const Attribute *> attr;
string _name(name);
if ( Template::get(_name,attr) == 0 )
{
values = 0;
return;
}
sattr = dynamic_cast<const SingleAttribute *>(attr[0]);
if ( sattr != 0 )
{
istringstream is;
is.str(sattr->value());
is >> values;
}
else
values = 0;
};
void get(const char *name, float& value) const
{
string _name(name);
Template::get(_name,value);
};
void get(const char *name, bool& value) const
{
string _name(name);
Template::get(_name,value);
};
void get(const char *name, long long& value) const
{
string _name(name);
Template::get(_name,value);
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/**
* Parse and loads the configuration in the template
*/
@ -214,6 +128,11 @@ private:
const std::string& shared,
const std::string& ds_migrate);
/**
* Sets a the defaults for a Market
*/
void set_conf_market(const std::string& name,
const std::string& required_attrs);
};

View File

@ -159,6 +159,33 @@ namespace one_util
*/
std::string float_to_str(const float &num);
/**
* Returns a scaped version of a value in the from "<op><val><cl>"
* @param v the value to be escaped
* @param op the opening escape string
* @param cl the closing escape string
*/
template <typename ValueType> inline
std::string escape(const ValueType& v, const char * op, const char * cl)
{
std::ostringstream oss;
oss << op << v << cl;
return oss.str();
}
template <typename ValueType> inline
std::string escape_xml(const ValueType &v)
{
return escape(v, "<![CDATA[", "]]>");
}
template <typename ValueType> inline
std::string escape_xml_attr(const ValueType &v)
{
return escape(v, "'", "'");
}
/**
* Checks if a strings matches a regular expression
*
@ -174,6 +201,17 @@ namespace one_util
* @return trimed string
*/
std::string trim(const std::string& str);
/**
* Returns a copy of st with the all occurrences of "find" substituted
* for "replacement"
* @param st string input
* @param sfind string to search for
* @param replacement string to replace occurrences with
* @return a string copy
*/
std::string gsub(const std::string& st, const std::string& sfind,
const std::string& replacement);
};
#endif /* _NEBULA_UTIL_H_ */

View File

@ -80,11 +80,19 @@ public:
/**
* Returns a copy of the IDs set
*/
set<int> get_collection_copy()
set<int> get_collection_copy() const
{
return set<int> (collection_set);
};
/**
* Returns a reference to the IDs set
*/
const set<int>& get_collection() const
{
return collection_set;
};
/**
* Returns true if the collection contains the given id
* @param id ID to search

View File

@ -53,71 +53,107 @@ public:
virtual ~ObjectXML();
/**
* Gets elements using Xpath expression.
* @param xpath_expr the Xpath of the element
* @return a vector with the elements
* Gets elements by xpath.
* @param values vector with the element values.
* @param expr of the xml element
*/
template<typename T>
void xpaths(std::vector<T>& values, const char * expr)
{
xmlXPathObjectPtr obj;
xmlNodePtr cur;
xmlChar * str_ptr;
obj=xmlXPathEvalExpression(reinterpret_cast<const xmlChar *>(expr),ctx);
if (obj == 0)
{
return;
}
switch (obj->type)
{
case XPATH_NUMBER:
values.push_back(static_cast<T>(obj->floatval));
break;
case XPATH_NODESET:
for(int i = 0; i < obj->nodesetval->nodeNr ; ++i)
{
cur = obj->nodesetval->nodeTab[i];
if ( cur == 0 || cur->type != XML_ELEMENT_NODE )
{
continue;
}
str_ptr = xmlNodeGetContent(cur);
if (str_ptr != 0)
{
std::istringstream iss(reinterpret_cast<char *>(str_ptr));
T val;
iss >> std::dec >> val;
if (!iss.fail())
{
values.push_back(val);
}
xmlFree(str_ptr);
}
}
break;
default:
break;
}
xmlXPathFreeObject(obj);
};
void xpaths(std::vector<std::string>& values, const char * xpath_expr);
/* ---------------------------------------------------------------------- */
/* Gets elements, type wrappers. See __xpaths definition for full */
/* description of these methods. */
/* ---------------------------------------------------------------------- */
inline void xpaths(std::vector<int>& values, const char * xpath_expr)
{
__xpaths<int>(values, xpath_expr);
};
inline void xpaths(std::vector<float>& values, const char * xpath_expr)
{
__xpaths<float>(values, xpath_expr);
};
/**
* Gets and sets a xpath attribute, if the attribute is not found a default
* is used
* @param value to set
* Gets a xpath attribute, if the attribute is not found a default is used.
* This function only returns the first element
* @param value of the element
* @param xpath_expr of the xml element
* @param def default value if the element is not found
*
* @return -1 if default was set
*/
template<typename T>
int xpath(T& value, const char * xpath_expr, const T& def)
{
std::vector<std::string> values;
xpaths(values, xpath_expr);
if (values.empty() == true)
{
value = def;
return -1;
}
std::istringstream iss(values[0]);
iss >> std::dec >> value;
if (iss.fail() == true)
{
value = def;
return -1;
}
return 0;
}
int xpath(std::string& value, const char * xpath_expr, const char * def);
/* ---------------------------------------------------------------------- */
/* Gets xpath attribute, type wrappers. See __xpath definition for full */
/* description of these methods. */
/* ---------------------------------------------------------------------- */
inline int xpath(int& v, const char * x, const int& d)
{
return __xpath<int>(v, x, d);
}
inline int xpath(float& v, const char * x, const float& d)
{
return __xpath<float>(v, x, d);
}
inline int xpath(unsigned int& v, const char * x, const unsigned int& d)
{
return __xpath<unsigned int>(v, x, d);
}
inline int xpath(long long& v, const char * x, const long long& d)
{
return __xpath<long long>(v, x, d);
}
inline int xpath(unsigned long long& v, const char * x, const unsigned long long& d)
{
return __xpath<unsigned long long>(v, x, d);
}
inline int xpath(time_t& v, const char * x, const time_t& d)
{
return __xpath<time_t>(v, x, d);
}
/**
* Gets the value of an element from an xml string
* @param value the value of the element
@ -293,103 +329,7 @@ private:
*/
void search(const char* name, std::vector<std::string>& results);
/**
* Gets a xpath attribute, if the attribute is not found a default is used.
* This function only returns the first element
* @param value of the element
* @param xpath_expr of the xml element
* @param def default value if the element is not found
*
* @return -1 if default was set
*/
template<typename T>
int __xpath(T& value, const char * xpath_expr, const T& def)
{
std::vector<std::string> values;
xpaths(values, xpath_expr);
if (values.empty() == true)
{
value = def;
return -1;
}
std::istringstream iss(values[0]);
iss >> std::dec >> value;
if (iss.fail() == true)
{
value = def;
return -1;
}
return 0;
}
/**
* Gets elements by xpath.
* @param values vector with the element values.
* @param expr of the xml element
*/
template<typename T>
void __xpaths(std::vector<T>& values, const char * expr)
{
xmlXPathObjectPtr obj;
xmlNodePtr cur;
xmlChar * str_ptr;
obj=xmlXPathEvalExpression(reinterpret_cast<const xmlChar *>(expr),ctx);
if (obj == 0)
{
return;
}
switch (obj->type)
{
case XPATH_NUMBER:
values.push_back(static_cast<T>(obj->floatval));
break;
case XPATH_NODESET:
for(int i = 0; i < obj->nodesetval->nodeNr ; ++i)
{
cur = obj->nodesetval->nodeTab[i];
if ( cur == 0 || cur->type != XML_ELEMENT_NODE )
{
continue;
}
str_ptr = xmlNodeGetContent(cur);
if (str_ptr != 0)
{
std::istringstream iss(reinterpret_cast<char *>(str_ptr));
T val;
iss >> std::dec >> val;
if (!iss.fail())
{
values.push_back(val);
}
xmlFree(str_ptr);
}
}
break;
default:
break;
}
xmlXPathFreeObject(obj);
};
};
#endif /*OBJECT_XML_H_*/

View File

@ -49,41 +49,48 @@ public:
*/
enum ObjectType
{
VM = 0x0000001000000000LL,
HOST = 0x0000002000000000LL,
NET = 0x0000004000000000LL,
IMAGE = 0x0000008000000000LL,
USER = 0x0000010000000000LL,
TEMPLATE = 0x0000020000000000LL,
GROUP = 0x0000040000000000LL,
ACL = 0x0000080000000000LL,
DATASTORE = 0x0000100000000000LL,
CLUSTER = 0x0000200000000000LL,
DOCUMENT = 0x0000400000000000LL,
ZONE = 0x0000800000000000LL,
SECGROUP = 0x0001000000000000LL,
VDC = 0x0002000000000000LL
NONE = 0x0000000000000000LL,
VM = 0x0000001000000000LL,
HOST = 0x0000002000000000LL,
NET = 0x0000004000000000LL,
IMAGE = 0x0000008000000000LL,
USER = 0x0000010000000000LL,
TEMPLATE = 0x0000020000000000LL,
GROUP = 0x0000040000000000LL,
ACL = 0x0000080000000000LL,
DATASTORE = 0x0000100000000000LL,
CLUSTER = 0x0000200000000000LL,
DOCUMENT = 0x0000400000000000LL,
ZONE = 0x0000800000000000LL,
SECGROUP = 0x0001000000000000LL,
VDC = 0x0002000000000000LL,
VROUTER = 0x0004000000000000LL,
MARKETPLACE = 0x0008000000000000LL,
MARKETPLACEAPP = 0x0010000000000000LL
};
static string type_to_str(ObjectType ob)
{
switch (ob)
{
case VM: return "VM" ; break;
case HOST: return "HOST" ; break;
case NET: return "NET" ; break;
case IMAGE: return "IMAGE" ; break;
case USER: return "USER" ; break;
case TEMPLATE: return "TEMPLATE" ; break;
case GROUP: return "GROUP" ; break;
case ACL: return "ACL" ; break;
case DATASTORE: return "DATASTORE" ; break;
case CLUSTER: return "CLUSTER" ; break;
case DOCUMENT: return "DOCUMENT" ; break;
case ZONE: return "ZONE" ; break;
case SECGROUP: return "SECGROUP" ; break;
case VDC: return "VDC" ; break;
default: return "";
case VM: return "VM" ; break;
case HOST: return "HOST" ; break;
case NET: return "NET" ; break;
case IMAGE: return "IMAGE" ; break;
case USER: return "USER" ; break;
case TEMPLATE: return "TEMPLATE" ; break;
case GROUP: return "GROUP" ; break;
case ACL: return "ACL" ; break;
case DATASTORE: return "DATASTORE" ; break;
case CLUSTER: return "CLUSTER" ; break;
case DOCUMENT: return "DOCUMENT" ; break;
case ZONE: return "ZONE" ; break;
case SECGROUP: return "SECGROUP" ; break;
case VDC: return "VDC" ; break;
case VROUTER: return "VROUTER" ; break;
case MARKETPLACE: return "MARKETPLACE" ; break;
case MARKETPLACEAPP: return "MARKETPLACEAPP" ; break;
default: return "";
}
};
@ -320,152 +327,61 @@ public:
// Template
// ------------------------------------------------------------------------
/**
* Gets the values of a template attribute
* Gets the first VectorAttribute of the specified type with the given name.
* Const and non-const versions of this method is provided
* @param name the attribute name.
* @return true first attribute or 0 if not found or wrong type
*/
const VectorAttribute * get_template_attribute(const string& s) const
{
return obj_template->get(s);
}
VectorAttribute * get_template_attribute(const string& s)
{
return obj_template->get(s);
}
/**
* Gets the values of a template attribute, as a list of VectorAttributes
* @param name of the attribute
* @param values of the attribute
* @return the number of values
*/
int get_template_attribute(
const char * name,
vector<const Attribute*>& values) const
template<typename T>
int get_template_attribute(const char * name, vector<const T*>& values) const
{
return obj_template->get(name,values);
};
/**
* Gets a string based attribute (single)
* These methods gets the value of a SingleAttribute and converts it to the
* target type
* @param name of the attribute
* @param value of the attribute (a string), will be "" if not defined or
* @param value of the attribute, will be ""/0/false if not defined or
* not a single attribute
*
* @return true if the attribute was found and is a valid type for the
* target value
*/
void get_template_attribute(
const char * name,
string& value) const
{
obj_template->get(name,value);
}
/**
* Gets and removes a string based attribute (single)
* @param name of the attribute
* @param value of the attribute (a string), will be "" if not defined or
* not a single attribute
* @return the number of attributes erased
*/
int erase_template_attribute(
const char * name,
string& value)
{
obj_template->get(name,value);
return obj_template->erase(name);
}
/**
* Gets and removes a float based attribute (single)
* @param name of the attribute
* @param value of the attribute (a float), will be 0 if not defined or
* not a single attribute
* @return the number of attributes erased
*/
int erase_template_attribute(
const char * name,
float& value)
{
obj_template->get(name,value);
return obj_template->erase(name);
}
/**
* Gets and removes a long long based attribute (single)
* @param name of the attribute
* @param value of the attribute (a long long), will be 0 if not defined or
* not a single attribute
* @return the number of attributes erased
*/
int erase_template_attribute(
const char * name,
long long& value)
{
obj_template->get(name,value);
return obj_template->erase(name);
}
/**
* Gets and removes a boolean based attribute (single)
* @param name of the attribute
* @param value of the attribute (a boolean), will be false if not defined or
* not a single attribute
* @return the number of attributes erased
*/
int erase_template_attribute(
const char * name,
bool& value)
{
obj_template->get(name,value);
return obj_template->erase(name);
}
/**
* Gets an int based attribute (single)
* @param name of the attribute
* @param value of the attribute (an int), will be 0 if not defined or
* not a single attribute
*
* @return True if the Single attribute was found and is a valid integer
* value
*/
bool get_template_attribute(
const char * name,
int& value) const
template<typename T>
bool get_template_attribute(const char * name, T& value) const
{
return obj_template->get(name,value);
}
/**
* Gets a long long based attribute (single)
* These methods get and remove a string based attribute (single)
* @param name of the attribute
* @param value of the attribute (long long), will be 0 if not defined or
* not a single attribute
*
* @return True if the Single attribute was found and is a valid integer
* value
* @param value of the attribute (a string), will be ""/0/false if not
* defined or not a single attribute, depending on the target value type
* @return the number of attributes erased
*/
bool get_template_attribute(
const char * name,
long long& value) const
template<typename T>
int erase_template_attribute(const char * name, T& value)
{
return obj_template->get(name,value);
}
/**
* Gets a float based attribute (single)
* @param name of the attribute
* @param value of the attribute (a float), will be 0 if not defined or
* not a single attribute
*
* @return True if the Single attribute was found and is a valid float
* value
*/
bool get_template_attribute(
const char * name,
float& value) const
{
return obj_template->get(name,value);
}
/**
* Gets a boolean attribute (single) (YES = true)
* @param name of the attribute
* @param value of the attribute (True if "YES", false otherwise)
*
* @return True if the Single attribute was found and is a valid boolean
* value
*/
bool get_template_attribute(
const char * name,
bool& value) const
{
return obj_template->get(name,value);
obj_template->get(name,value);
return obj_template->erase(name);
}
/**
@ -475,9 +391,8 @@ public:
* @param value of the new attribute
* @return 0 on success
*/
int replace_template_attribute(
const string& name,
const string& value)
template<typename T>
int replace_template_attribute(const string& name, const T& value)
{
return obj_template->replace(name, value);
}
@ -489,18 +404,17 @@ public:
* @param values a vector containing a pointer to the attributes
* @return the number of attributes removed
*/
int remove_template_attribute(
const string& name,
vector<Attribute *>& values)
template<typename T>
int remove_template_attribute(const string& n, vector<T *>& v)
{
return obj_template->remove(name, values);
return obj_template->remove(n, v);
}
/**
* Generates a XML string for the template of the Object
* @param xml the string to store the XML description.
*/
string& template_to_xml(string &xml) const
string& template_to_xml(string &xml) const
{
return obj_template->to_xml(xml);
}
@ -530,27 +444,8 @@ public:
* @param att_name Name for the attribute
* @param att_val Message string
*/
void add_template_attribute(const string& name, const string& value)
{
obj_template->add(name, value);
}
/**
* Adds an int attribute
* @param att_name Name for the attribute
* @param att_val integer
*/
void add_template_attribute(const string& name, int value)
{
obj_template->add(name, value);
}
/**
* Adds a float attribute
* @param att_name Name for the attribute
* @param att_val integer
*/
void add_template_attribute(const string& name, float value)
template<typename T>
void add_template_attribute(const string& name, const T& value)
{
obj_template->add(name, value);
}

View File

@ -248,8 +248,8 @@ protected:
* @param remotes_location, path to remotes in the front-end where the
* hooks are installed
*/
void register_hooks(vector<const Attribute *> hook_mads,
const string& remotes_location);
void register_hooks(vector<const VectorAttribute *> hook_mads,
const string& remotes_location);
/**
* Gets an object from the pool (if needed the object is loaded from the

View File

@ -23,24 +23,11 @@
class Quotas;
/**
* Base class for resource quotas, it provides basic storage and management of
* the quotas. Each resource MUST inherit from it to implement check and
* update methods. Quotas are stored in a template form, each class store the
* limits and usage in a resource specific format.
* This class defines the public interface (pure abstract) for Quota.
*/
class Quota: public Template
class QuotaInterface
{
public:
/**
* Set the quotas. If the quota previously exists its limit is updated.
* @param quota_str the quota template in ASCII or XML formats
* @param error describe the error in case of error
*
* @return 0 on success -1 otherwise
*/
int set(vector<Attribute*> * quotas, string& error);
/**
* Check if the resource allocation will exceed the quota limits. If not
* the usage counters are updated
@ -51,6 +38,112 @@ public:
*/
virtual bool check(Template* tmpl, Quotas& default_quotas, string& error) = 0;
/**
* Decrement usage counters when deallocating image
* @param tmpl template for the resource
*/
virtual void del(Template* tmpl) = 0;
/**
* Set the quotas. If the quota previously exists its limit is updated.
* @param quota_str the quota template in ASCII or XML formats
* @param error describe the error in case of error
*
* @return 0 on success -1 otherwise
*/
virtual int set(vector<VectorAttribute*> * quotas, string& error) = 0;
/**
* Check if a resource update in usage counters will exceed the
* quota limits. If not the usage counters are updated for that resource
* @param tmpl with increments in MEMORY and CPU
* @param default_quotas Quotas that contain the default limits
* @param error string
* @return true if the operation can be performed
*/
virtual bool update(Template * tmpl, Quotas& default_quotas, string& error) = 0;
/**
* Returns the name that identifies the quota in a template
*/
virtual const char * get_quota_name() = 0;
/**
* Gets a quota identified by its ID.
* @param id of the quota
* @param va The quota, if it is found
* @return 0 on success, -1 if not found
*/
virtual int get_quota(const string& id, VectorAttribute **va) = 0;
protected:
QuotaInterface(){};
virtual ~QuotaInterface(){};
};
/**
* The QuotaDecorator class decorates the quota interface with specific
* behavior over the same quota object and counters. Decorators must be derived
* from this class and pass in its constructor the decorated object.
*/
class QuotaDecorator : public QuotaInterface
{
virtual bool check(Template* tmpl, Quotas& default_quotas, string& error)
{
return quota->check(tmpl, default_quotas, error);
}
virtual void del(Template* tmpl)
{
return quota->del(tmpl);
}
virtual int set(vector<VectorAttribute*> * quotas, string& error)
{
return quota->set(quotas, error);
}
virtual bool update(Template * tmpl, Quotas& default_quotas, string& error)
{
return quota->update(tmpl, default_quotas, error);
}
virtual const char * get_quota_name()
{
return quota->get_quota_name();
}
virtual int get_quota(const string& id, VectorAttribute **va)
{
return quota->get_quota(id, va);
}
protected:
QuotaDecorator(QuotaInterface * _quota):quota(_quota){};
virtual ~QuotaDecorator(){};
QuotaInterface * quota;
};
/**
* Base class for resource quotas, it provides basic storage and management of
* the quotas. Each resource MUST inherit from it to implement check and
* update methods. Quotas are stored in a template form, each class store the
* limits and usage in a resource specific format.
*/
class Quota: public Template, public QuotaInterface
{
public:
/**
* Set the quotas. If the quota previously exists its limit is updated.
* @param quota_str the quota template in ASCII or XML formats
* @param error describe the error in case of error
*
* @return 0 on success -1 otherwise
*/
int set(vector<VectorAttribute*> * quotas, string& error);
/**
* Check if a resource update in usage counters will exceed the
* quota limits. If not the usage counters are updated for that resource
@ -65,12 +158,6 @@ public:
return false;
};
/**
* Decrement usage counters when deallocating image
* @param tmpl template for the resource
*/
virtual void del(Template* tmpl) = 0;
/**
* Returns the name that identifies the quota in a template
*/
@ -102,7 +189,6 @@ public:
*/
static const int UNLIMITED;
protected:
Quota(const char * quota_name,

View File

@ -18,6 +18,7 @@
#define QUOTA_NETWORK_H_
#include "Quota.h"
#include "PoolObjectSQL.h"
/**
* DataStore Quotas, defined as:
@ -29,39 +30,38 @@
*
* 0 = unlimited, default if missing
*/
class QuotaNetwork : public Quota
{
public:
QuotaNetwork(bool is_default): Quota("NETWORK_QUOTA", "NETWORK", NET_METRICS,
NUM_NET_METRICS, is_default) {};
QuotaNetwork(bool is_default):
Quota("NETWORK_QUOTA",
"NETWORK",
NET_METRICS,
NUM_NET_METRICS,
is_default)
{};
~QuotaNetwork(){};
virtual ~QuotaNetwork(){};
/**
* Check if the resource allocation will exceed the quota limits. If not
* the usage counters are updated
* the usage counters are updated. Assumes calling object is a VM
* @param tmpl template for the resource
* @param default_quotas Quotas that contain the default limits
* @param error string
* @return true if the operation can be performed
*/
bool check(Template* tmpl, Quotas& default_quotas, string& error);
bool check(Template* tmpl, Quotas& default_quotas, string& err)
{
return check(PoolObjectSQL::VM, tmpl, default_quotas, err);
}
/**
* Decrement usage counters when deallocating image
* Decrement usage counters when freeing a lease. This method considers
* the object type to accounto for FLOATING IP addresses or not
* @param tmpl template for the resource
*/
void del(Template* tmpl);
void del(Template* tmpl)
{
del(PoolObjectSQL::VM, tmpl);
}
protected:
/**
* Gets the default quota identified by its ID.
*
@ -78,6 +78,61 @@ protected:
static const char * NET_METRICS[];
static const int NUM_NET_METRICS;
private:
/**
* Friends are decorators for the QuotaNetwork. They can access specialized
* methods to operate over the same quota counters (base Template class)
*/
friend class QuotaNetworkVirtualRouter;
/**
* Check if the resource allocation will exceed the quota limits. If not
* the usage counters are updated. This method considers the object type to
* accounto for FLOATING IP addresses or not
* @param otype object type, VM or VRouter
* @param tmpl template for the resource
* @param default_quotas Quotas that contain the default limits
* @param error string
* @return true if the operation can be performed
*/
bool check(PoolObjectSQL::ObjectType otype, Template* tmpl,
Quotas& default_quotas, string& error);
/**
* Decrement usage counters when freeing a lease. This method considers
* the object type to accounto for FLOATING IP addresses or not
* @param otype object type, VM or VRouter
* @param tmpl template for the resource
*/
void del(PoolObjectSQL::ObjectType otype, Template* tmpl);
};
/**
* Decorates the QuotaNetwork object to consider the FLOATING_IP attribute
* of the NIC attributes. It must be instantiated using an exisiting QuotaNetwork
* object
*/
class QuotaNetworkVirtualRouter: public QuotaDecorator
{
public:
QuotaNetworkVirtualRouter(QuotaNetwork *qn):QuotaDecorator(qn){};
virtual ~QuotaNetworkVirtualRouter(){};
bool check(Template* tmpl, Quotas& default_quotas, string& err)
{
QuotaNetwork * qn = static_cast<QuotaNetwork *>(quota);
return qn->check(PoolObjectSQL::VROUTER, tmpl, default_quotas, err);
}
void del(Template* tmpl)
{
QuotaNetwork * qn = static_cast<QuotaNetwork *>(quota);
qn->del(PoolObjectSQL::VROUTER, tmpl);
}
};
#endif /*QUOTA_NETWORK_H_*/

View File

@ -35,7 +35,8 @@ public:
VM, /**< Checks VM usage (MEMORY, CPU and VMS) */
NETWORK, /**< Checks Network usage (leases) */
IMAGE, /**< Checks Image usage (RVMs using it) */
VIRTUALMACHINE /**< Checks all VM associated resources VM, NETWORK, IMAGE */
VIRTUALMACHINE, /**< Checks all VM associated resources VM, NETWORK, IMAGE */
VIRTUALROUTER /**< Checks the Virtual Router NETWORK usage (leases) */
};
/**
@ -69,17 +70,6 @@ public:
return datastore_quota.get_quota(id, va);
}
/**
* Delete VM related usage (network, image and compute) from quota counters.
* @param tmpl template for the image, with usage
*/
void vm_del(Template * tmpl)
{
network_quota.del(tmpl);
vm_quota.del(tmpl);
image_quota.del(tmpl);
}
/**
* Gets a VM quota identified by its ID.
*

View File

@ -27,6 +27,77 @@
using namespace std;
/**
* This class represents the dynamic attributes: specific for a request of the
* same method.
*/
struct RequestAttributes
{
public:
int uid; /**< id of the user */
int gid; /**< id of the user's group */
string uname; /**< name of the user */
string gname; /**< name of the user's group */
string password; /**< password of the user */
set<int> group_ids; /**< set of user's group ids */
string session; /**< Session from ONE XML-RPC API */
int req_id; /**< Request ID for log messages */
int umask; /**< User umask for new objects */
xmlrpc_c::value * retval; /**< Return value from libxmlrpc-c */
PoolObjectSQL::ObjectType resp_obj; /**< object type */
int resp_id; /**< Id of the object */
string resp_msg; /**< Additional response message */
RequestAttributes(){};
RequestAttributes(const RequestAttributes& ra)
{
uid = ra.uid;
gid = ra.gid;
uname = ra.uname;
gname = ra.gname;
password = ra.password;
session = ra.session;
retval = ra.retval;
umask = ra.umask;
resp_obj = ra.resp_obj;
resp_id = ra.resp_id;
resp_msg = ra.resp_msg;
};
RequestAttributes(int _uid, int _gid, const RequestAttributes& ra)
{
uid = _uid;
gid = _gid;
password = "";
uname = "";
gname = "";
umask = 0;
session = ra.session;
retval = ra.retval;
resp_obj = PoolObjectSQL::NONE;
resp_id = -1;
resp_msg = "";
};
};
/**
* The Request Class represents the basic abstraction for the OpenNebula
* XML-RPC API. This interface must be implemented by any XML-RPC API call
@ -34,16 +105,6 @@ using namespace std;
class Request: public xmlrpc_c::method
{
public:
/**
* Wraps the actual execution function by authorizing the user
* and calling the request_execute virtual function
* @param _paramlist list of XML parameters
* @param _retval value to be returned to the client
*/
virtual void execute(
xmlrpc_c::paramList const& _paramList,
xmlrpc_c::value * const _retval);
/**
* Error codes for the XML-RPC API
*/
@ -55,8 +116,17 @@ public:
ACTION = 0x0800,
XML_RPC_API = 0x1000,
INTERNAL = 0x2000,
ALLOCATE = 0x4000
};
/**
* Gets a string representation for the Auth object in the
* request.
* @param ob object for the auth operation
* @return string equivalent of the object
*/
static string object_name(PoolObjectSQL::ObjectType ob);
/**
* Sets the format string to log xml-rpc method calls. The format string
* interprets the following sequences:
@ -77,69 +147,9 @@ public:
}
protected:
/* ---------------------------------------------------------------------*/
/* Attributes of the Request */
/* ---------------------------------------------------------------------*/
/* -------- Dynamic (specific for a request of the same method) -------- */
struct RequestAttributes
{
int uid; /**< id of the user */
int gid; /**< id of the user's group */
string uname; /**< name of the user */
string gname; /**< name of the user's group */
string password; /**< password of the user */
set<int> group_ids; /**< set of user's group ids */
string session; /**< Session from ONE XML-RPC API */
int req_id; /**< Request ID for log messages */
int umask; /**< User umask for new objects */
xmlrpc_c::value * retval; /**< Return value from libxmlrpc-c */
RequestAttributes(){};
RequestAttributes(const RequestAttributes& ra)
{
uid = ra.uid;
gid = ra.gid;
uname = ra.uname;
gname = ra.gname;
password = ra.password;
session = ra.session;
retval = ra.retval;
umask = ra.umask;
};
RequestAttributes(int _uid, int _gid, const RequestAttributes& ra)
{
uid = _uid;
gid = _gid;
password = "";
uname = "";
gname = "";
umask = 0;
session = ra.session;
retval = ra.retval;
};
};
/* -------- Static (shared among request of the same method) -------- */
/* ---------------------------------------------------------------------- */
/* Static Request Attributes: shared among request of the same method */
/* ---------------------------------------------------------------------- */
PoolSQL * pool; /**< Pool of objects */
string method_name; /**< The name of the XML-RPC method */
@ -150,11 +160,11 @@ protected:
static string format_str;
/* -------------------- Constructors ---------------------------------- */
Request(const string& mn,
const string& signature,
const string& help): pool(0),method_name(mn)
/* ---------------------------------------------------------------------- */
/* Class Constructors */
/* ---------------------------------------------------------------------- */
Request(const string& mn, const string& signature, const string& help):
pool(0),method_name(mn)
{
_signature = signature;
_help = help;
@ -164,9 +174,88 @@ protected:
virtual ~Request(){};
/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- */
/* Methods to execute the request when received at the server */
/* ---------------------------------------------------------------------- */
/**
* Wraps the actual execution function by authorizing the user
* and calling the request_execute virtual function
* @param _paramlist list of XML parameters
* @param _retval value to be returned to the client
*/
virtual void execute(xmlrpc_c::paramList const& _paramList,
xmlrpc_c::value * const _retval);
/**
* Actual Execution method for the request. Must be implemented by the
* XML-RPC requests
* @param _paramlist of the XML-RPC call (complete list)
* @param att the specific request attributes
*/
virtual void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att) = 0;
/**
* Locks the requested object, gets information, and unlocks it
*
* @param pool object pool
* @param id of the object
* @param type of the object
* @param att the specific request attributes
*
* @param perms returns the object's permissions
* @param name returns the object's name
* @param throw_error send error response to client if object not found
*
* @return 0 on success, -1 otherwise
*/
int get_info(PoolSQL * pool,
int id,
PoolObjectSQL::ObjectType type,
RequestAttributes& att,
PoolObjectAuth& perms,
string& name,
bool throw_error);
/* ---------------------------------------------------------------------- */
/* Methods to send response to xml-rpc client */
/* ---------------------------------------------------------------------- */
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc excute method should return
* @param val to be returned to the client
* @param att the specific request attributes
*/
void success_response(int val, RequestAttributes& att);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc excute method should return
* @param val string to be returned to the client
* @param att the specific request attributes
*/
void success_response(const string& val, RequestAttributes& att);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc execute method should return
* @param val to be returned to the client
* @param att the specific request attributes
*/
void success_response(bool val, RequestAttributes& att);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc excute method should return. A descriptive error message
* is constructed using att.resp_obj, att.resp_id and/or att.resp_msg and
* the ErrorCode
* @param ec error code for this call
* @param ra the specific request attributes
*/
void failure_response(ErrorCode ec, RequestAttributes& ra);
/* ---------------------------------------------------------------------- */
/* Authorization methods for requests */
/* ---------------------------------------------------------------------- */
/**
* Performs a basic authorization for this request using the uid/gid
* from the request. The function gets the object from the pool to get
@ -196,7 +285,7 @@ protected:
* @return true if the user is authorized.
*/
bool basic_authorization(int oid, AuthRequest::Operation op,
RequestAttributes& att);
RequestAttributes& att);
/**
* Performs a basic quota check for this request using the uid/gid
@ -209,10 +298,8 @@ protected:
*
* @return true if the user is authorized.
*/
bool quota_authorization(
Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att);
bool quota_authorization(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att);
/**
* Performs a basic quota check for this request using the uid/gid
@ -227,11 +314,8 @@ protected:
* @param error_str Error reason, if any
* @return true if the user is authorized.
*/
bool quota_authorization(
Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att,
string& error_str);
static bool quota_authorization(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att, string& error_str);
/**
* Performs rollback on usage counters for a previous quota check operation
@ -239,136 +323,53 @@ protected:
* @param tmpl describing the object
* @param att the specific request attributes
*/
void quota_rollback(Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att);
static void quota_rollback(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att);
/**
* Actual Execution method for the request. Must be implemented by the
* XML-RPC requests
* @param _paramlist of the XML-RPC call (complete list)
* @param att the specific request attributes
*/
virtual void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att) = 0;
private:
/* ---------------------------------------------------------------------- */
/* Functions to manage user and group quotas */
/* ---------------------------------------------------------------------- */
static bool user_quota_authorization(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att, string& error_str);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc excute method should return
* @param val to be returned to the client
* @param att the specific request attributes
*/
void success_response(int val, RequestAttributes& att);
static bool group_quota_authorization(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att, string& error_str);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc excute method should return
* @param val string to be returned to the client
* @param att the specific request attributes
*/
void success_response(const string& val, RequestAttributes& att);
static void user_quota_rollback(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc execute method should return
* @param val to be returned to the client
* @param att the specific request attributes
*/
void success_response(bool val, RequestAttributes& att);
static void group_quota_rollback(Template * tmpl, Quotas::QuotaType qtype,
RequestAttributes& att);
/**
* Builds an XML-RPC response updating retval. After calling this function
* the xml-rpc excute method should return
* @param ec error code for this call
* @param val string representation of the error
* @param att the specific request attributes
* @param va string representation of the error
* @param ra the specific request attributes
*/
void failure_response(ErrorCode ec,
const string& val,
RequestAttributes& att);
void failure_response(ErrorCode ec, const string& va, RequestAttributes& ra);
/**
* Gets a string representation for the Auth object in the
* request.
* @param ob object for the auth operation
* @return string equivalent of the object
*/
static string object_name(PoolObjectSQL::ObjectType ob);
/**
* Logs authorization errors
* @param message with the authorization error details
* @return string for logging
* @param att the specific request attributes
*/
string authorization_error (const string &message, RequestAttributes& att);
/**
* Logs authenticate errors
* @return string for logging
*/
string authenticate_error ();
/**
* Logs get object errors
* @param object over which the get failed
* @param id of the object over which the get failed
* @return string for logging
*/
string get_error (const string &object, int id);
/**
* Logs action errors
* @param err_desc brief description of the error
* @param err_detail additional error details from Managers & Pools
* @return string for logging
*/
string request_error (const string &err_desc, const string &err_detail);
/**
* Logs allocate errors
* @param message with the allocate error details
* @return string for logging
*/
string allocate_error (const string& error);
/**
* Logs allocate errors for a given resource
* @param obj the resource
* @param message with the allocate error details
* @return string for logging
*/
string allocate_error (PoolObjectSQL::ObjectType obj, const string& error);
/**
* Locks the requested object, gets information, and unlocks it
*
* @param pool object pool
* @param id of the object
* @param type of the object
* Logs the method invocation, including the arguments
* @param att the specific request attributes
*
* @param perms returns the object's permissions
* @param name returns the object's name
* @param throw_error send error response to client if object not found
*
* @return 0 on success, -1 otherwise
* @param paramList list of XML parameters
* @param format_str for the log
* @param hidden_params params not to be shown
*/
int get_info (PoolSQL * pool,
int id,
PoolObjectSQL::ObjectType type,
RequestAttributes& att,
PoolObjectAuth& perms,
string& name,
bool throw_error);
static void log_method_invoked(const RequestAttributes& att,
const xmlrpc_c::paramList& paramList, const string& format_str,
const std::string& method_name, const std::set<int>& hidden_params);
/**
* Logs the method result, including the output data or error message
*
* @param att the specific request attributes
* @param method_name that produced the error
*/
virtual void log_result(
const RequestAttributes& att);
static void log_result(const RequestAttributes& att,
const std::string& method_name);
/**
* Formats and adds a xmlrpc_c::value to oss.
@ -376,41 +377,7 @@ protected:
* @param v value to format
* @param oss stream to write v
*/
virtual void log_xmlrpc_value(
const xmlrpc_c::value& v,
ostringstream& oss);
private:
/**
* Logs the method invocation, including the arguments
*
* @param att the specific request attributes
* @param paramList list of XML parameters
*/
void log_method_invoked(
const RequestAttributes& att,
const xmlrpc_c::paramList& paramList);
/* ------------- Functions to manage user and group quotas -------------- */
bool user_quota_authorization(Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att,
string& error_str);
bool group_quota_authorization(Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att,
string& error_str);
void user_quota_rollback(Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att);
void group_quota_rollback(Template * tmpl,
Quotas::QuotaType qtype,
RequestAttributes& att);
static void log_xmlrpc_value(const xmlrpc_c::value& v, std::ostringstream& oss);
};
/* -------------------------------------------------------------------------- */

View File

@ -64,7 +64,6 @@ protected:
virtual int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att)
{
return -1;
@ -73,12 +72,11 @@ protected:
virtual int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name)
{
return pool_allocate(_paramList, tmpl, id, error_str, att);
return pool_allocate(_paramList, tmpl, id, att);
};
virtual int get_cluster_id(xmlrpc_c::paramList const& paramList)
@ -138,7 +136,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
bool allocate_authorization(Template * obj_template,
@ -175,7 +172,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name);
@ -249,7 +245,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
bool allocate_authorization(Template * obj_template,
@ -281,7 +276,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name);
@ -325,7 +319,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
};
@ -353,7 +346,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
private:
@ -389,7 +381,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name);
@ -445,7 +436,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
};
@ -478,7 +468,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
};
@ -514,7 +503,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
};
@ -547,7 +535,6 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
};
@ -580,10 +567,113 @@ public:
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterAllocate : public RequestManagerAllocate
{
public:
VirtualRouterAllocate():
RequestManagerAllocate("VirtualRouterAllocate",
"Allocates a new virtual router",
"A:ss",
true)
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterAllocate(){};
/* --------------------------------------------------------------------- */
Template * get_object_template()
{
return new Template;
};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
RequestAttributes& att);
bool allocate_authorization(Template * obj_template,
RequestAttributes& att,
PoolObjectAuth * cluster_perms);
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAllocate : public RequestManagerAllocate
{
public:
MarketPlaceAllocate():
RequestManagerAllocate("MarketPlaceAllocate",
"Allocates a new marketplace",
"A:ss",
true)
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceAllocate(){};
/* --------------------------------------------------------------------- */
Template * get_object_template()
{
return new MarketPlaceTemplate;
};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppAllocate : public RequestManagerAllocate
{
public:
MarketPlaceAppAllocate():
RequestManagerAllocate("MarketPlaceAppAllocate",
"Allocates a new marketplace app",
"A:ssi",
true)
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
mppool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppAllocate(){};
/* --------------------------------------------------------------------- */
Template * get_object_template()
{
return new MarketPlaceAppTemplate;
};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
RequestAttributes& att);
private:
MarketPlacePool * mppool;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -171,7 +171,62 @@ public:
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterChmod: public RequestManagerChmod
{
public:
VirtualRouterChmod():
RequestManagerChmod("VirtualRouterChmod",
"Changes permission bits of a virtual router")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterChmod(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceChmod: public RequestManagerChmod
{
public:
MarketPlaceChmod():
RequestManagerChmod("MarketPlaceChmod",
"Changes permission bits of a marketplace")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceChmod(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppChmod: public RequestManagerChmod
{
public:
MarketPlaceAppChmod():
RequestManagerChmod("MarketPlaceAppChmod",
"Changes permission bits of a marketplace app")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppChmod(){};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -268,7 +268,76 @@ public:
return static_cast<SecurityGroupPool*>(pool)->get(name, uid, lock);
};
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterChown: public RequestManagerChown
{
public:
VirtualRouterChown():
RequestManagerChown("VirtualRouterChown",
"Changes ownership of a virtual router")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterChown(){};
PoolObjectSQL * get(const string& name, int uid, bool lock)
{
return static_cast<VirtualRouterPool*>(pool)->get(name, uid, lock);
};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceChown: public RequestManagerChown
{
public:
MarketPlaceChown():
RequestManagerChown("MarketPlaceChown",
"Changes ownership of a marketplace")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceChown(){};
PoolObjectSQL * get(const string& name, int uid, bool lock)
{
return 0;
};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppChown: public RequestManagerChown
{
public:
MarketPlaceAppChown():
RequestManagerChown("MarketPlaceAppChown",
"Changes ownership of a marketplace app")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppChown(){};
PoolObjectSQL * get(const string& name, int uid, bool lock)
{
return static_cast<MarketPlaceAppPool *>(pool)->get(name, uid, lock);
};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -48,7 +48,6 @@ protected:
int source_id,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att) = 0;
};
@ -82,7 +81,6 @@ public:
int source_id,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att)
{
VMTemplatePool * tpool = static_cast<VMTemplatePool *>(pool);
@ -91,7 +89,7 @@ public:
static_cast<VirtualMachineTemplate *>(tmpl);
return tpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
ttmpl, &id, error_str);
ttmpl, &id, att.resp_msg);
};
};
@ -126,14 +124,15 @@ public:
int source_id,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att)
{
DocumentPool * docpool = static_cast<DocumentPool *>(pool);
Document * doc = docpool->get(source_id, true);
Document * doc = docpool->get(source_id, true);
doc->unlock();
return docpool->allocate(att.uid, att.gid, att.uname, att.gname,
att.umask, doc->get_document_type(), tmpl, &id, error_str);
att.umask, doc->get_document_type(), tmpl, &id, att.resp_msg);
};
};
@ -167,13 +166,12 @@ public:
int source_id,
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att)
{
SecurityGroupPool * secgrouppool = static_cast<SecurityGroupPool *>(pool);
return secgrouppool->allocate(att.uid, att.gid, att.uname, att.gname,
att.umask, tmpl, &id, error_str);
att.umask, tmpl, &id, att.resp_msg);
};
};
/* -------------------------------------------------------------------------- */

View File

@ -137,9 +137,6 @@ public:
~ImageDelete(){};
/* -------------------------------------------------------------------- */
int drop(int oid, PoolObjectSQL * object, string& error_msg);
};
@ -354,7 +351,61 @@ public:
~VdcDelete(){};
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterDelete : public RequestManagerDelete
{
public:
VirtualRouterDelete():
RequestManagerDelete("VirtualRouterDelete",
"Deletes a virtual router")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterDelete(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceDelete : public RequestManagerDelete
{
public:
MarketPlaceDelete():
RequestManagerDelete("MarketPlaceDelete",
"Deletes a marketplace")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceDelete(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppDelete : public RequestManagerDelete
{
public:
MarketPlaceAppDelete():
RequestManagerDelete("MarketPlaceAppDelete",
"Deletes a marketplace app")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppDelete(){};
int drop(int oid, PoolObjectSQL * object, string& error_msg);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -318,7 +318,59 @@ public:
~VdcInfo(){};
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterInfo : public RequestManagerInfo
{
public:
VirtualRouterInfo():
RequestManagerInfo("VirtualRouterInfo",
"Returns virtual router information")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterInfo(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceInfo : public RequestManagerInfo
{
public:
MarketPlaceInfo():
RequestManagerInfo("MarketPlaceInfo",
"Returns marketplace information")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceInfo(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppInfo : public RequestManagerInfo
{
public:
MarketPlaceAppInfo():
RequestManagerInfo("MarketPlaceAppInfo",
"Returns marketplace app information")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppInfo(){};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,66 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#ifndef REQUEST_MANAGER_MARKETPLACEAPP_H
#define REQUEST_MANAGER_MARKETPLACEAPP_H
#include "Request.h"
#include "Nebula.h"
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class RequestManagerMarketPlaceApp: public Request
{
protected:
RequestManagerMarketPlaceApp(const std::string& method_name,
const std::string& help, const std::string& params) :
Request(method_name, params, help)
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
auth_op = AuthRequest::MANAGE;
};
~RequestManagerMarketPlaceApp(){};
/* --------------------------------------------------------------------- */
virtual void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att) = 0;
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppEnable : public RequestManagerMarketPlaceApp
{
public:
MarketPlaceAppEnable(): RequestManagerMarketPlaceApp("MarketPlaceAppEnable",
"Enables or disables a marketplace app", "A:sib"){};
~MarketPlaceAppEnable(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
#endif

View File

@ -488,14 +488,66 @@ public:
~VdcPoolInfo(){};
/* -------------------------------------------------------------------- */
void request_execute(xmlrpc_c::paramList const& pl, RequestAttributes& att);
};
void request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att);
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterPoolInfo : public RequestManagerPoolInfoFilter
{
public:
VirtualRouterPoolInfo():
RequestManagerPoolInfoFilter("VirtualRouterPoolInfo",
"Returns the virtual router pool",
"A:siii")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterPoolInfo(){};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class MarketPlacePoolInfo : public RequestManagerPoolInfoFilter
{
public:
MarketPlacePoolInfo():
RequestManagerPoolInfoFilter("MarketPlacePoolInfo",
"Returns the marketplace pool",
"A:s")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlacePoolInfo(){};
void request_execute(xmlrpc_c::paramList const& pl, RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
class MarketPlaceAppPoolInfo : public RequestManagerPoolInfoFilter
{
public:
MarketPlaceAppPoolInfo():
RequestManagerPoolInfoFilter("MarketPlacePoolInfo",
"Returns the market place pool",
"A:siii")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppPoolInfo(){};
};
#endif

View File

@ -334,7 +334,74 @@ public:
~VdcRename(){};
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterRename: public RequestManagerRename
{
public:
VirtualRouterRename():
RequestManagerRename("VirtualRouterRename", "Renames a virtual router")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterRename(){};
PoolObjectSQL * get(const string& name, int uid, bool lock)
{
return static_cast<VirtualRouterPool*>(pool)->get(name, uid, lock);
};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceRename: public RequestManagerRename
{
public:
MarketPlaceRename():
RequestManagerRename("MarketPlaceRename", "Renames a marketplace")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceRename(){};
PoolObjectSQL * get(const string& name, int uid, bool lock)
{
return static_cast<MarketPlacePool*>(pool)->get(name, lock);
};
void batch_rename(int oid);
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppRename: public RequestManagerRename
{
public:
MarketPlaceAppRename():
RequestManagerRename("MarketPlaceRename", "Renames a marketplace app")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppRename(){};
PoolObjectSQL * get(const string& name, int uid, bool lock)
{
return static_cast<MarketPlaceAppPool*>(pool)->get(name, uid, lock);
};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -286,7 +286,60 @@ public:
~VdcUpdateTemplate(){};
};
/* -------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterUpdateTemplate : public RequestManagerUpdateTemplate
{
public:
VirtualRouterUpdateTemplate():
RequestManagerUpdateTemplate("VirtualRouterUpdateTemplate",
"Updates a virtual router template")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~VirtualRouterUpdateTemplate(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceUpdateTemplate : public RequestManagerUpdateTemplate
{
public:
MarketPlaceUpdateTemplate():
RequestManagerUpdateTemplate("MarketPlaceUpdateTemplate",
"Updates a marketplace template")
{
Nebula& nd = Nebula::instance();
pool = nd.get_marketpool();
auth_object = PoolObjectSQL::MARKETPLACE;
};
~MarketPlaceUpdateTemplate(){};
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class MarketPlaceAppUpdateTemplate : public RequestManagerUpdateTemplate
{
public:
MarketPlaceAppUpdateTemplate():
RequestManagerUpdateTemplate("MarketPlaceUpdateTemplate",
"Updates a marketplace app template")
{
Nebula& nd = Nebula::instance();
pool = nd.get_apppool();
auth_object = PoolObjectSQL::MARKETPLACEAPP;
};
~MarketPlaceAppUpdateTemplate(){};
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -66,6 +66,24 @@ public:
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
/**
* Instantiates the VM Template, checking permissions, quotas, etc
* @param id VM Template ID
* @param name Name for the new VM. Can be empty
* @param on_hold True to start the VM on HOLD state
* @param str_uattrs Template supplied by user to merge with the original
* contents. Can be empty
* @param extra_attrs Template to be merged. It should contain internal
* configuration, and it won't be authenticated or checked for restricted
* attributes. Can be 0
* @param vmid on success of the new VM
* @param att the specific request attributes
*
* @return ErroCode for the request.
*/
static ErrorCode instantiate(int id, string name, bool on_hold,
string str_uattrs, Template* extra_attrs, int& vid, RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */

View File

@ -253,8 +253,16 @@ public:
~VirtualMachineAttachNic(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
void request_execute(xmlrpc_c::paramList const& pl, RequestAttributes& ra);
/**
* Process a NIC attahment request to a Virtual Machine
* @param id of the VirtualMachine
* @param tmpl with the new NIC description
* @param att attributes of this request
* @return ErroCode as defined in Request
*/
static ErrorCode attach(int id, VirtualMachineTemplate& tmpl, RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
@ -272,6 +280,15 @@ public:
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
/**
* Process a NIC detach request to a Virtual Machine
* @param id of the VirtualMachine
* @param nic_id id of the NIC
* @param att attributes of this request
* @return ErroCode as defined in Request
*/
static ErrorCode detach(int id, int nic_id, RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,118 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#ifndef REQUEST_MANAGER_VIRTUAL_ROUTER_H
#define REQUEST_MANAGER_VIRTUAL_ROUTER_H
#include "Request.h"
#include "Nebula.h"
using namespace std;
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class RequestManagerVirtualRouter: public Request
{
protected:
RequestManagerVirtualRouter(const string& method_name,
const string& help,
const string& params)
:Request(method_name,params,help)
{
Nebula& nd = Nebula::instance();
pool = nd.get_vrouterpool();
auth_object = PoolObjectSQL::VROUTER;
};
~RequestManagerVirtualRouter(){};
/* -------------------------------------------------------------------- */
virtual void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att) = 0;
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterInstantiate : public RequestManagerVirtualRouter
{
public:
VirtualRouterInstantiate():
RequestManagerVirtualRouter("VirtualRouterInstantiate",
"Instantiates a new virtual machine associated to a virtual router",
"A:siiisbs")
{
auth_op = AuthRequest::MANAGE;
};
~VirtualRouterInstantiate(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterAttachNic : public RequestManagerVirtualRouter
{
public:
VirtualRouterAttachNic():
RequestManagerVirtualRouter("VirtualRouterAttachNic",
"Attaches a new NIC to the virtual router, and its virtual machines",
"A:sis")
{
auth_op = AuthRequest::MANAGE;
};
~VirtualRouterAttachNic(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualRouterDetachNic : public RequestManagerVirtualRouter
{
public:
VirtualRouterDetachNic():
RequestManagerVirtualRouter("VirtualRouterDetachNic",
"Detaches a NIC from a virtual router, and its virtual machines",
"A:sii")
{
auth_op = AuthRequest::MANAGE;
};
~VirtualRouterDetachNic(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
#endif

View File

@ -86,12 +86,6 @@ public:
return static_cast<SecurityGroup *>(PoolSQL::get(name,uid,lock));
};
/** Update a particular SecurityGroup
* @param securitygroup pointer to SecurityGroup
* @return 0 on success
*/
int update(SecurityGroup * securitygroup);
/**
* Bootstraps the database table(s) associated to the SecurityGroup pool
* @return 0 on success

View File

@ -45,7 +45,7 @@ class SqliteDB : public SqlDB
{
public:
SqliteDB(string& db_name);
SqliteDB(const string& db_name);
~SqliteDB();

View File

@ -89,6 +89,9 @@ public:
*/
virtual ~Template();
/* ---------------------------------------------------------------------- */
/* Functions to create a Template parsing a file, stream in txt or XML */
/* ---------------------------------------------------------------------- */
/**
* Parse a string representing the template, each attribute is inserted
* in the template class.
@ -119,6 +122,30 @@ public:
*/
int parse_str_or_xml(const string &parse_str, string& error_msg);
/**
* Rebuilds the template from a xml formatted string
* @param xml_str The xml-formatted string
*
* @return 0 on success, -1 otherwise
*/
int from_xml(const string &xml_str);
/**
* Rebuilds the object from an xml node
* @param node The xml node pointer
*
* @return 0 on success, -1 otherwise
*/
int from_xml_node(const xmlNodePtr node);
/**
* Writes the Template into a output stream in txt format
*/
friend ostream& operator<<(ostream& os, const Template& t);
/* ---------------------------------------------------------------------- */
/* Functions to render a Template in a str, or xml */
/* ---------------------------------------------------------------------- */
/**
* Marshall a template. This function generates a single string with the
* template attributes ("VAR=VAL<delim>...").
@ -150,6 +177,9 @@ public:
*/
string& to_str(string& str) const;
/* ---------------------------------------------------------------------- */
/* Functions to add, remove and change attributes from a Template */
/* ---------------------------------------------------------------------- */
/**
* Clears all the attributes from the template
*/
@ -163,98 +193,43 @@ public:
virtual void set(Attribute * attr);
/**
* Adds a new attribute to the template (replacing it if
* already defined)
* Adds a new attribute to the template (replacing it if already defined)
* @param name of the new attribute
* @param value of the new attribute
* @return 0 on success
*/
template<typename T>
int replace(const string& name, const T& value)
{
std::ostringstream oss;
oss << value;
return replace(name, oss.str());
}
int replace(const string& name, const string& value);
/**
* Adds a new attribute to the template (replacing it if
* already defined)
* @param name of the new attribute
* @param value of the new attribute
* @return 0 on success
*/
int replace(const string& name, int value)
{
ostringstream oss;
oss << value;
return replace(name, oss.str());
}
/**
* Adds a new attribute to the template (replacing it if
* already defined)
* @param name of the new attribute
* @param value of the new attribute
* @return 0 on success
*/
int replace(const string& name, long long value)
{
ostringstream oss;
oss << value;
return replace(name, oss.str());
}
/*
* Adds a new single attribute to the template. It will replace an existing
* one if replace_mode was set to true
* @param name of the attribute
* @param value of the attribute
*/
void add(const string& name, const string& value)
{
set(new SingleAttribute(name, value));
}
/**
* Adds a new single attribute to the template.
* @param name of the attribute
* @param value of the attribute
*/
void add(const string& name, int value)
{
ostringstream oss;
template<typename T>
void add(const string& name, const T& value)
{
std::ostringstream oss;
oss << value;
set(new SingleAttribute(name, oss.str()));
}
}
/**
* Adds a new single attribute to the template.
* @param name of the attribute
* @param value of the attribute
*/
void add(const string& name, long long value)
{
ostringstream oss;
oss << value;
set(new SingleAttribute(name, oss.str()));
}
/**
* Adds a new single attribute to the template.
* @param name of the attribute
* @param value of the attribute
*/
void add(const string& name, float value)
{
ostringstream oss;
oss << value;
set(new SingleAttribute(name, oss.str()));
}
void add(const string& name, const string& value)
{
set(new SingleAttribute(name, value));
}
/**
* Removes an attribute from the template. The attributes are returned. The
@ -263,9 +238,27 @@ public:
* @param values a vector containing a pointer to the attributes
* @return the number of attributes removed
*/
virtual int remove(
const string& name,
vector<Attribute *>& values);
template<typename T>
int remove(const string& name, vector<T *>& values)
{
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
multimap<string, Attribute *>::iterator i;
int j;
index = attributes.equal_range(name);
for ( i = index.first,j=0 ; i != index.second ; i++,j++ )
{
values.push_back(static_cast<T *>(i->second));
}
attributes.erase(index.first, index.second);
return j;
}
/**
* Removes an attribute from the template, but it DOES NOT free the
@ -283,94 +276,90 @@ public:
*/
virtual int erase(const string& name);
/* ---------------------------------------------------------------------- */
/* Functions get attributes from a template */
/* ---------------------------------------------------------------------- */
/**
* Gets all the attributes with the given name.
* Gets the all the attributes of the given name and stores a reference
* to them in a vector. If the selected attribute does not match the
* requested type it will not be included
* @param name the attribute name.
* @param values vector with the values
*
* @return the number of elements in the vector
*/
virtual int get(
const string& name,
vector<const Attribute*>& values) const;
/**
* Gets all the attributes with the given name, non-const version
* @param name the attribute name.
* @return the number of elements in the vector
*/
virtual int get(
const string& name,
vector<Attribute*>& values);
/**
* Gets the value of a Single attributes (string) with the given name.
* @param name the attribute name.
* @param value the attribute value, a string, "" if the attribute is not
* defined or not Single
*/
virtual void get(
const string& name,
string& value) const;
/**
* Gets the value of a Single attributes (int) with the given name.
* @param name the attribute name.
* @param value the attribute value, an int, 0 if the attribute is not
* defined or not Single
*
* @return True if the Single attribute was found and is a valid integer
* value
*/
virtual bool get(
const string& name,
int& value) const;
/**
* Gets the value of a Single attributes (long long) with the given name.
* @param name the attribute name.
* @param value the attribute value, a long long, 0 if the attribute is not
* defined or not Single
*
* @return True if the Single attribute was found and is a valid integer
* value
*/
virtual bool get(
const string& name,
long long& value) const;
/**
* Gets the value of a Single attributes (float) with the given name.
* @param name the attribute name.
* @param value the attribute value, an int, 0 if the attribute is not
* defined or not Single
*
* @return True if the Single attribute was found and is a valid float
* value
*/
virtual bool get(
const string& name,
float& value) const;
/**
* Gets the value of a Single attributes (bool) with the given name.
* @param name the attribute name.
* @param value the attribute value, a bool, false if the attribute is not
* defined or not Single
*
* @return True if the Single attribute was found and is a valid bool
* value
*/
virtual bool get(
const string& name,
bool& value) const;
/**
* Trims the trailing spaces in the NAME attribute
* @return True if the attribute was found and trimmed
*/
virtual bool trim_name()
inline virtual int get(const string& n, vector<const VectorAttribute*>& v) const
{
return trim("NAME");
};
return __get<VectorAttribute>(n, v);
}
inline virtual int get( const string& n, vector<VectorAttribute*>& v)
{
return __get<VectorAttribute>(n, v);
}
inline virtual int get(const string& n, vector<const SingleAttribute*>& s) const
{
return __get<SingleAttribute>(n, s);
}
inline virtual int get( const string& n, vector<SingleAttribute*>& s)
{
return __get<SingleAttribute>(n, s);
}
/**
* Gets the first Attribute of the specified type with the given name.
* Const and non-const versions of this method is provided
* @param name the attribute name.
* @return true first attribute or 0 if not found or wrong type
*/
inline const VectorAttribute * get(const string& name) const
{
return __get<VectorAttribute>(name);
}
inline VectorAttribute * get(const string& name)
{
return __get<VectorAttribute>(name);
}
/**
* Gets the value of a SingleAttribute with the given name and converts
* it to the target value format
* @param name the attribute name.
* @param value the attribute value
*
* @return true if a SingleAttribute was found and it stores a valid
* value, false otherwise.
*/
template<typename T>
bool get(const string& name, T& value) const
{
const SingleAttribute * s = __get<SingleAttribute>(name);
value = 0;
if ( s == 0 )
{
return false;
}
istringstream iss(s->value());
iss >> value;
if (iss.fail() || !iss.eof())
{
return false;
}
return true;
}
virtual bool get(const string& name, bool& value) const;
virtual bool get(const string& name, string& value) const;
/**
* Trims the trailing spaces in the attribute
@ -379,23 +368,14 @@ public:
*/
virtual bool trim(const string& name);
friend ostream& operator<<(ostream& os, const Template& t);
/**
* Rebuilds the template from a xml formatted string
* @param xml_str The xml-formatted string
*
* @return 0 on success, -1 otherwise
* Trims the trailing spaces in the NAME attribute
* @return True if the attribute was found and trimmed
*/
int from_xml(const string &xml_str);
/**
* Rebuilds the object from an xml node
* @param node The xml node pointer
*
* @return 0 on success, -1 otherwise
*/
int from_xml_node(const xmlNodePtr node);
inline virtual bool trim_name()
{
return trim("NAME");
};
/**
* Merges another Template, adding the new attributes and
@ -452,7 +432,7 @@ protected:
* @param restricted_attributes The attributes will be stored here
*/
static void set_restricted_attributes(
vector<const Attribute *>& rattrs,
vector<const SingleAttribute *>& rattrs,
vector<string>& restricted_attributes);
/**
@ -505,6 +485,96 @@ private:
* @param root_element The xml element to build the template from.
*/
void rebuild_attributes(const xmlNode * root_element);
/**
* Gets the all the attributes of the given name and stores a reference
* to them in a vector. If the selected attribute does not match the
* requested type it will not be included
* @param name the attribute name.
* @param values vector with the values
*
* @return the number of elements in the vector
*/
template<typename T>
int __get(const string& name, vector<const T *>& values) const
{
pair<multimap<string, Attribute *>::const_iterator,
multimap<string, Attribute *>::const_iterator> index;
multimap<string, Attribute *>::const_iterator i;
int j;
index = attributes.equal_range(name);
for (i = index.first, j = 0 ; i != index.second ; i++, j++)
{
const T * vatt = dynamic_cast<const T *>(i->second);
if ( vatt == 0 )
{
continue;
}
values.push_back(vatt);
}
return j;
}
/* Non-const version of get for all attributes */
template<typename T>
int __get(const string& name, vector<T *>& values)
{
pair<multimap<string, Attribute *>::iterator,
multimap<string, Attribute *>::iterator> index;
multimap<string, Attribute *>::iterator i;
int j;
index = attributes.equal_range(name);
for (i = index.first, j = 0 ; i != index.second ; i++, j++)
{
T * vatt = dynamic_cast<T *>(i->second);
if ( vatt == 0 )
{
continue;
}
values.push_back(vatt);
}
return j;
}
/**
* Gets the first Attribute of the specified type with the given name.
* Const and non-const versions of this method is provided
* @param name the attribute name.
* @return true first attribute or 0 if not found or wrong type
*/
template<typename T>
const T * __get(const string& s) const
{
vector<const T*> atts;
if (__get<T>(s, atts) < 1)
{
return 0;
}
return atts[0];
}
template<typename T>
T * __get(const string& s)
{
return const_cast<T *>(
static_cast<const Template&>(*this).__get<T>(s));
}
};
/* -------------------------------------------------------------------------- */

View File

@ -32,9 +32,9 @@ class TransferManager : public MadManager, public ActionListener
public:
TransferManager(
VirtualMachinePool * _vmpool,
HostPool * _hpool,
vector<const Attribute*>& _mads):
VirtualMachinePool * _vmpool,
HostPool * _hpool,
vector<const VectorAttribute*>& _mads):
MadManager(_mads),
vmpool(_vmpool),
hpool(_hpool)
@ -123,6 +123,22 @@ public:
ostream& xfr,
ostringstream& error);
/**
* Inserts a context command in the xfs stream
*
* @param vm The VM
* @param token_password Owner user's token password
* @param system_tm_mad The Transfer Manager for the system datastore
* @param xfr Stream where the transfer command will be written
*
* @return 0 on success
*/
int prolog_context_command(
VirtualMachine * vm,
const string& token_password,
string& system_tm_mad,
ostream& xfr);
/**
* Inserts a transfer command in the xfs stream
*

View File

@ -41,7 +41,7 @@ public:
UserPool(SqlDB * db,
time_t __session_expiration_time,
vector<const Attribute *> hook_mads,
vector<const VectorAttribute *> hook_mads,
const string& remotes_location,
bool is_federation_slave);
@ -114,7 +114,7 @@ public:
* @param user pointer to User
* @return 0 on success
*/
int update(User * user);
int update(PoolObjectSQL * objsql);
/**
* Update a particular User's Quotas

View File

@ -70,6 +70,16 @@ public:
*(static_cast<VirtualMachineTemplate *>(obj_template)));
};
// ------------------------------------------------------------------------
// Virtual Router
// ------------------------------------------------------------------------
/**
* Returns true if this Template is a Virtual Router Template
* @return true if this Template is a Virtual Router Template
*/
bool is_vrouter();
private:
// -------------------------------------------------------------------------
// Friends

View File

@ -81,18 +81,6 @@ public:
return static_cast<VMTemplate *>(PoolSQL::get(name,uid,lock));
};
/**
* Updates the object's data in the data base. The object mutex SHOULD be
* locked.
* @param objsql a pointer to the object
*
* @return 0 on success.
*/
int update(VMTemplate * vm_template)
{
return vm_template->update(db);
};
/**
* Dumps the pool in XML format. A filter can be also added to the
* query

View File

@ -90,7 +90,7 @@ public:
* @param vdc pointer to Vdc
* @return 0 on success
*/
int update(Vdc * vdc);
int update(PoolObjectSQL * objsql);
/**
* Drops the Vdc from the data base. The object mutex SHOULD be

View File

@ -463,18 +463,13 @@ public:
*/
void set_kernel(const string& kernel)
{
vector<Attribute *> os_attr;
VectorAttribute * os;
VectorAttribute * os = obj_template->get("OS");
int num = obj_template->get("OS", os_attr);
if ( num == 0 )
if ( os == 0 )
{
return;
}
os = dynamic_cast<VectorAttribute *>(os_attr[0]);
os->replace("KERNEL", kernel);
};
@ -485,18 +480,13 @@ public:
*/
void set_initrd(const string& initrd)
{
vector<Attribute *> os_attr;
VectorAttribute * os;
VectorAttribute * os = obj_template->get("OS");
int num = obj_template->get("OS", os_attr);
if ( num == 0 )
if ( os == 0 )
{
return;
}
os = dynamic_cast<VectorAttribute *>(os_attr[0]);
os->replace("INITRD", initrd);
};
@ -1225,7 +1215,7 @@ public:
* @param pci_dev
*/
void get_requirements (int& cpu, int& memory, int& disk,
vector<Attribute *>& pci_dev);
vector<VectorAttribute *>& pci_dev);
/**
* Checks if the resize parameters are valid
@ -1265,7 +1255,8 @@ public:
*
* @return 0 on success, -1 otherwise
*/
static int release_network_leases(VectorAttribute const * nic, int vmid);
static int release_network_leases(
VectorAttribute const * nic, int vmid);
/**
* Releases all disk images taken by this Virtual Machine
@ -1322,6 +1313,31 @@ public:
*/
const VectorAttribute* get_disk(int disk_id) const;
const VectorAttribute* get_nic(int nic_id) const;
// ------------------------------------------------------------------------
// Virtual Router related functions
// ------------------------------------------------------------------------
/**
* Returns the Virtual Router ID if this VM is a VR, or -1
* @return VR ID or -1
*/
int get_vrouter_id();
/**
* Returns true if this VM is a Virtual Router
* @return true if this VM is a Virtual Router
*/
bool is_vrouter();
/**
* Checks if the given action is supported for Virtual Router VMs
* @param action VM action to check
* @return true if the action is supported for Virtual Router VMs
*/
static bool is_vrouter_action_supported(History::VMAction action);
// ------------------------------------------------------------------------
// Context related functions
// ------------------------------------------------------------------------
@ -1333,7 +1349,18 @@ public:
* @param token_password Password to encrypt the token, if it is set
* @return -1 in case of error, 0 if the VM has no context, 1 on success
*/
int generate_context(string &files, int &disk_id, string& token_password);
int generate_context(string &files, int &disk_id, const string& token_password);
const VectorAttribute* get_context() const
{
return obj_template->get("CONTEXT");
}
/**
* Returns the CREATED_BY template attribute, or the uid if it does not exist
* @return uid
*/
int get_created_by_uid() const;
// -------------------------------------------------------------------------
// "Save as" Disk related functions (save_as hot)
@ -1555,18 +1582,6 @@ public:
int uid,
string& error_str);
/**
* Cleans the ATTACH = YES attribute from the NICs
*/
void clear_attach_nic();
/**
* Deletes the NIC that was in the process of being attached
*
* @return the deleted NIC or 0 if none was deleted
*/
VectorAttribute * delete_attach_nic();
/**
* Adds a new NIC to the virtual machine template. The NIC should be
* generated by the build_attach_nic
@ -1575,12 +1590,37 @@ public:
*/
void set_attach_nic(VectorAttribute * new_nic, vector<VectorAttribute*> &rules);
/**
* Cleans the ATTACH = YES attribute from the NICs
*/
void attach_nic_success();
/**
* Deletes the NIC that was in the process of being attached
*
* @return the deleted NIC or 0 if none was deleted
*/
VectorAttribute * attach_nic_failure();
/**
* Sets the attach attribute to the given NIC
* @param nic_id of the NIC
* @return 0 if the nic_id was found, -1 otherwise
*/
int set_attach_nic(int nic_id);
int set_detach_nic(int nic_id);
/**
* Deletes the NIC that was in the process of being detached
*
* @return the deleted NIC or 0 if none was deleted
*/
VectorAttribute * detach_nic_success();
/**
* Cleans the ATTACH = YES attribute from the NIC, restores the NIC context
* variables
*/
void detach_nic_failure();
// ------------------------------------------------------------------------
// Snapshot related functions
@ -1699,7 +1739,6 @@ public:
*/
void delete_snapshots();
private:
// -------------------------------------------------------------------------
@ -1959,6 +1998,20 @@ private:
*/
int parse_defaults(string& error_str);
/**
* Parse virtual router related attributes
* @param error_str Returns the error reason, if any
* @return 0 on success
*/
int parse_vrouter(string& error_str);
/**
* Known Virtual Router attributes, to be moved from the user template
* to the template
*/
static const char* VROUTER_ATTRIBUTES[];
static const int NUM_VROUTER_ATTRIBUTES;
/**
* Known attributes for network contextualization rendered as:
* ETH_<nicid>_<context[0]> = $NETWORK[context[1], vnet_name]
@ -2002,6 +2055,17 @@ private:
*/
int parse_context(string& error_str);
/**
* Parses the current contents of the context vector attribute, without
* adding any attributes. Substitutes $VARIABLE, $VARIABLE[ATTR] and
* $VARIABLE[ATTR, ATTR = VALUE]
* @param pointer to the context attribute. It will be updated to point
* to the new parsed CONTEXT
* @param error_str description in case of error
* @return 0 on success
*/
int parse_context_variables(VectorAttribute ** context, string& error_str);
/**
* Parse the "SCHED_REQUIREMENTS" attribute of the template by substituting
* $VARIABLE, $VARIABLE[ATTR] and $VARIABLE[ATTR, ATTR = VALUE]
@ -2104,6 +2168,13 @@ private:
static_cast<const VirtualMachine&>(*this).get_disk(disk_id));
};
/**
* Returns the NIC that is waiting for an attachment action
*
* @return the NIC waiting for an attachment action, or 0
*/
VectorAttribute* get_attach_nic();
// ------------------------------------------------------------------------
// Public cloud templates related functions
// ------------------------------------------------------------------------

View File

@ -38,7 +38,7 @@ public:
time_t _poll_period,
bool _do_vm_poll,
int _vm_limit,
vector<const Attribute*>& _mads);
vector<const VectorAttribute*>& _mads);
~VirtualMachineManager(){};

View File

@ -33,10 +33,10 @@ class VirtualMachinePool : public PoolSQL
public:
VirtualMachinePool(SqlDB * db,
vector<const Attribute *> hook_mads,
vector<const VectorAttribute *> hook_mads,
const string& hook_location,
const string& remotes_location,
vector<const Attribute *>& restricted_attrs,
vector<const SingleAttribute *>& restricted_attrs,
time_t expire_time,
bool on_hold,
float default_cpu_cost,
@ -112,14 +112,20 @@ public:
*
* @return 0 on success.
*/
virtual int update(
VirtualMachine * objsql)
virtual int update(PoolObjectSQL * objsql)
{
VirtualMachine * vm = dynamic_cast<VirtualMachine *>(objsql);
if ( vm == 0 )
{
return -1;
}
do_hooks(objsql, Hook::UPDATE);
objsql->set_prev_state();
vm->set_prev_state();
return objsql->update(db);
return vm->update(db);
};
/**
@ -353,7 +359,20 @@ public:
*
* @param vid VM id
*/
void delete_attach_nic(int vid);
void attach_nic_failure(int vid)
{
delete_hotplug_nic(vid, true);
}
/**
* Deletes the NIC that was in the process of being detached
*
* @param vid VM id
*/
void detach_nic_success(int vid)
{
delete_hotplug_nic(vid, false);
}
/**
* Deletes an entry in the HV-2-vmid mapping table for imported VMs
@ -411,6 +430,15 @@ private:
* @return 0 on success
*/
int insert_index(const string& deploy_id, int vm_id, bool replace);
// -------------------------------------------------------------------------
/**
* Helper method for delete attach/detach
* @param vid VM id
* @param attach true for an attach action, false for detach
*/
void delete_hotplug_nic(int vid, bool attach);
};
#endif /*VIRTUAL_MACHINE_POOL_H_*/

View File

@ -101,7 +101,7 @@ private:
* VirtualMachineTemplate::check
* @param rattrs Attributes to restrict
*/
static void set_restricted_attributes(vector<const Attribute *>& rattrs)
static void set_restricted_attributes(vector<const SingleAttribute *>& rattrs)
{
Template::set_restricted_attributes(rattrs, restricted_attributes);
};

View File

@ -22,6 +22,7 @@
#include "VirtualNetworkTemplate.h"
#include "Clusterable.h"
#include "AddressRangePool.h"
#include "ObjectCollection.h"
#include <vector>
#include <string>
@ -82,7 +83,7 @@ public:
* @param error_msg If the action fails, this message contains the reason.
* @return 0 on success
*/
int add_var(vector<Attribute *> &var, string& error_msg);
int add_var(vector<VectorAttribute *> &var, string& error_msg);
/**
* Removes an address range from the VNET
@ -156,64 +157,80 @@ public:
/**
* Gets a new address lease for a specific VM
* @param vid VM identifier
* @param ot the type of the object requesting the address
* @param oid the id of the object requesting the address
* @param nic the VM NIC attribute to be filled with the lease info.
* @param inherit attributes from the address range to include in the NIC
* @return 0 if success
*/
int allocate_addr(int vid, VectorAttribute * nic,
const vector<string>& inherit)
int allocate_addr(PoolObjectSQL::ObjectType ot, int oid,
VectorAttribute * nic, const vector<string>& inherit)
{
return ar_pool.allocate_addr(PoolObjectSQL::VM, vid, nic, inherit);
return ar_pool.allocate_addr(ot, oid, nic, inherit);
}
/**
* Gets a new address lease for a specific VM by MAC
* @param vid VM identifier
* @param ot the type of the object requesting the address
* @param oid the id of the object requesting the address
* @param mac the MAC address requested
* @param nic the VM NIC attribute to be filled with the lease info.
* @param inherit attributes from the address range to include in the NIC
* @return 0 if success
*/
int allocate_by_mac(int vid, const string& mac, VectorAttribute * nic,
const vector<string>& inherit)
int allocate_by_mac(PoolObjectSQL::ObjectType ot, int oid, const string& mac,
VectorAttribute * nic, const vector<string>& inherit)
{
return ar_pool.allocate_by_mac(mac, PoolObjectSQL::VM, vid, nic, inherit);
return ar_pool.allocate_by_mac(mac, ot, oid, nic, inherit);
}
/**
* Gets a new address lease for a specific VM by IP
* @param vid VM identifier
* @param ot the type of the object requesting the address
* @param oid the id of the object requesting the address
* @param ip the IP address requested
* @param nic the VM NIC attribute to be filled with the lease info.
* @param inherit attributes from the address range to include in the NIC
* @return 0 if success
*/
int allocate_by_ip(int vid, const string& ip, VectorAttribute * nic,
const vector<string>& inherit)
int allocate_by_ip(PoolObjectSQL::ObjectType ot, int oid, const string& ip,
VectorAttribute * nic, const vector<string>& inherit)
{
return ar_pool.allocate_by_ip(ip, PoolObjectSQL::VM, vid, nic, inherit);
return ar_pool.allocate_by_ip(ip, ot, oid, nic, inherit);
}
/**
* Release previously given address lease
* @param arid of the address range where the address was leased from
* @param vid the ID of the VM
* @param ot the type of the object requesting the address
* @param oid the id of the object requesting the address
* @param mac MAC address identifying the lease
*/
void free_addr(unsigned int arid, int vid, const string& mac)
void free_addr(unsigned int arid, PoolObjectSQL::ObjectType ot, int oid,
const string& mac)
{
ar_pool.free_addr(arid, PoolObjectSQL::VM, vid, mac);
ar_pool.free_addr(arid, ot, oid, mac);
if (ot == PoolObjectSQL::VROUTER)
{
vrouters.del_collection_id(oid);
}
}
/**
* Release previously given address lease
* @param vid the ID of the VM
* @param ot the type of the object requesting the address
* @param oid the id of the object requesting the address
* @param mac MAC address identifying the lease
*/
void free_addr(int vid, const string& mac)
void free_addr(PoolObjectSQL::ObjectType ot, int oid, const string& mac)
{
ar_pool.free_addr(PoolObjectSQL::VM, vid, mac);
ar_pool.free_addr(ot, oid, mac);
if (ot == PoolObjectSQL::VROUTER)
{
vrouters.del_collection_id(oid);
}
}
/**
@ -255,6 +272,21 @@ public:
int vid,
const vector<string>& inherit_attrs);
/**
* Modifies the given nic attribute adding the following attributes:
* * IP: leased from network
* * MAC: leased from network
* @param nic attribute for the VRouter template
* @param vrid of the VRouter getting the lease
* @param inherit_attrs Attributes to be inherited from the vnet template
* into the nic
* @return 0 on success
*/
int vrouter_nic_attribute(
VectorAttribute * nic,
int vrid,
const vector<string>& inherit_attrs);
/**
* From a Security Group rule that uses this vnet, creates a new rule
* copy for each AR.
@ -377,10 +409,12 @@ public:
* A vector containing just -1 means all VMs.
* @param vnet_ids list of VNET the user can access reservation info from.
* A vector containing just -1 means all VNETs.
* @param vrs list of VRouter the user can access reservation info from.
* A vector containing just -1 means all VRouters.
* @return a reference to the generated string
*/
string& to_xml_extended(string& xml, const vector<int>& vms,
const vector<int>& vnets) const;
const vector<int>& vnets, const vector<int>& vrs) const;
/**
* Gets a string based attribute (single) from an address range. If the
@ -458,6 +492,11 @@ private:
*/
AddressRangePool ar_pool;
/**
* Set of Virtual Router IDs
*/
ObjectCollection vrouters;
// *************************************************************************
// DataBase implementation (Private)
// *************************************************************************
@ -490,7 +529,8 @@ private:
* @return a reference to the generated string
*/
string& to_xml_extended(string& xml, bool extended,
const vector<int>& vm_ids, const vector<int>& vnet_oids) const;
const vector<int>& vm_ids, const vector<int>& vnet_oids,
const vector<int>& vr_ids) const;
/**
* Rebuilds the object from an xml formatted string

View File

@ -33,13 +33,10 @@ class VirtualNetworkPool : public PoolSQL
{
public:
VirtualNetworkPool(SqlDB * db,
const string& str_mac_prefix,
int default_size,
vector<const Attribute *>& restricted_attrs,
vector<const Attribute *> hook_mads,
const string& remotes_location,
const vector<const Attribute *>& _inherit_attrs);
VirtualNetworkPool(SqlDB * db, const string& str_mac_prefix, int default_size,
vector<const SingleAttribute *>& restricted_attrs,
vector<const VectorAttribute *>& hook_mads, const string& remotes_location,
const vector<const SingleAttribute *>& _inherit_attrs);
~VirtualNetworkPool(){};
@ -113,18 +110,23 @@ public:
* -2 not using the pool
*/
int nic_attribute(
VectorAttribute* nic,
int nic_id,
int uid,
int vid,
string& error_str);
PoolObjectSQL::ObjectType ot,
VectorAttribute* nic,
int nic_id,
int uid,
int vid,
string& error_str);
/**
* Generates an Authorization token for a NIC attribute
* @param nic the nic to be authorized
* @param ar the AuthRequest
*/
void authorize_nic(VectorAttribute * nic, int uid, AuthRequest * ar);
void authorize_nic(
PoolObjectSQL::ObjectType ot,
VectorAttribute * nic,
int uid,
AuthRequest * ar);
/**
* Bootstraps the database table(s) associated to the VirtualNetwork pool

View File

@ -74,7 +74,7 @@ private:
* VirtualMachineTemplate::check
* @param rattrs Attributes to restrict
*/
static void set_restricted_attributes(vector<const Attribute *>& rattrs)
static void set_restricted_attributes(vector<const SingleAttribute *>& rattrs)
{
Template::set_restricted_attributes(rattrs, restricted_attributes);
};

272
include/VirtualRouter.h Normal file
View File

@ -0,0 +1,272 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 VIRTUAL_ROUTER_H_
#define VIRTUAL_ROUTER_H_
#include "PoolObjectSQL.h"
#include "Template.h"
#include "ObjectCollection.h"
#include "VirtualMachineTemplate.h"
#include "AuthRequest.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/**
* The VirtualRouter class.
*/
class VirtualRouter : public PoolObjectSQL
{
public:
/**
* Function to print the VirtualRouter object into a string in XML format
* @param xml the resulting XML string
* @return a reference to the generated string
*/
string& to_xml(string& xml) const;
int add_vmid(int vmid);
bool has_vmids() const;
/**
* Returns a copy of the VM IDs set
*/
set<int> get_vms() const;
// ------------------------------------------------------------------------
// Template Contents
// ------------------------------------------------------------------------
/**
* Factory method for VirtualRouter templates
*/
Template * get_new_template() const
{
return new Template;
}
/**
* Returns a copy of the Template
* @return A copy of the VirtualMachineTemplate
*/
Template * clone_template() const
{
return new Template(obj_template);
};
Template * get_vm_template() const;
/**
* Replace template for this object. Object should be updated
* after calling this method
* @param tmpl_str new contents
* @param keep_restricted If true, the restricted attributes of the
* current template will override the new template
* @param error string describing the error if any
* @return 0 on success
*/
int replace_template(const string& tmpl_str, bool keep_restricted, string& error);
/**
* Append new attributes to this object's template. Object should be updated
* after calling this method
* @param tmpl_str new contents
* @param keep_restricted If true, the restricted attributes of the
* current template will override the new template
* @param error string describing the error if any
* @return 0 on success
*/
int append_template(const string& tmpl_str, bool keep_restricted, string& error);
// ------------------------------------------------------------------------
// Attach and detach NIC
// ------------------------------------------------------------------------
/**
* Adds a new NIC to the virtual router template.
* @param tmpl Template, should contain only one NIC
* @param error_str error reason, if any
*
* @return 0 on failure, the NIC to attach to each VM on success
*/
VectorAttribute * attach_nic(
VirtualMachineTemplate * tmpl, string& error_str);
/**
* Deletes the NIC from the virtual router template.
*
* @param nic_id of the NIC
* @return 0 if the nic_id was found, -1 otherwise
*/
int detach_nic(int nic_id);
// ------------------------------------------------------------------------
// Authorization related functions
// ------------------------------------------------------------------------
/**
* Sets an authorization request for a Virtual Router template based on
* the networks used
* @param uid for template owner
* @param ar the AuthRequest object
* @param tmpl the virtual router template
*/
static void set_auth_request(int uid,
AuthRequest& ar,
Template *tmpl);
private:
// -------------------------------------------------------------------------
// Friends
// -------------------------------------------------------------------------
friend class VirtualRouterPool;
// *************************************************************************
// Attributes
// *************************************************************************
ObjectCollection vms;
// *************************************************************************
// DataBase implementation (Private)
// *************************************************************************
/**
* Execute an INSERT or REPLACE Sql query.
* @param db The SQL DB
* @param replace Execute an INSERT or a REPLACE
* @param error_str Returns the error reason, if any
* @return 0 one success
*/
int insert_replace(SqlDB *db, bool replace, string& error_str);
/**
* Bootstraps the database table(s) associated to the VirtualRouter
* @return 0 on success
*/
static int bootstrap(SqlDB * db)
{
ostringstream oss(VirtualRouter::db_bootstrap);
return db->exec(oss);
};
/**
* Rebuilds the object from an xml formatted string
* @param xml_str The xml-formatted string
*
* @return 0 on success, -1 otherwise
*/
int from_xml(const string &xml_str);
// *************************************************************************
// Constructor
// *************************************************************************
VirtualRouter( int id,
int uid,
int gid,
const string& uname,
const string& gname,
int umask,
Template * _template_contents);
~VirtualRouter();
// *************************************************************************
// DataBase implementation
// *************************************************************************
static const char * db_names;
static const char * db_bootstrap;
static const char * table;
/**
* Writes the VirtualRouter in the database.
* @param db pointer to the db
* @param error_str Returns the error reason, if any
* @return 0 on success
*/
int insert(SqlDB *db, string& error_str);
/**
* Drops object from the database
* @param db pointer to the db
* @return 0 on success
*/
virtual int drop(SqlDB *db);
/**
* Writes/updates the VirtualRouter data fields in the database.
* @param db pointer to the db
* @return 0 on success
*/
int update(SqlDB *db)
{
string err;
return insert_replace(db, true, err);
};
// -------------------------------------------------------------------------
// NIC Management
// -------------------------------------------------------------------------
/**
* Get all network leases for this Virtual Router
* @return 0 onsuccess
*/
int get_network_leases(string& estr);
/**
* Releases all network leases taken by this Virtual Router
*/
void release_network_leases();
/**
* Releases the network lease taken by this NIC
*
* @param nic NIC to be released
*
* @return 0 on success, -1 otherwise
*/
int release_network_leases(const VectorAttribute * nic);
/**
* Returns the nic with the giver nic_id, or 0
* @param nic_id
* @return nic if found, 0 if not found
*/
VectorAttribute* get_nic(int nic_id) const;
// -------------------------------------------------------------------------
// VM Management
// -------------------------------------------------------------------------
/**
* Tries to shutdown, or delete, all this Virtual Router's VMs
*
* @return 0 on success, -1 otherwise
*/
int shutdown_vms();
};
#endif /*VIRTUAL_ROUTER_H_*/

141
include/VirtualRouterPool.h Normal file
View File

@ -0,0 +1,141 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 VIRTUAL_ROUTER_POOL_H_
#define VIRTUAL_ROUTER_POOL_H_
#include "PoolSQL.h"
#include "VirtualRouter.h"
/**
* The VirtualRouter Pool class.
*/
class VirtualRouterPool : public PoolSQL
{
public:
VirtualRouterPool(SqlDB * db, vector<const VectorAttribute *> hook_mads,
const string& remotes_location) : PoolSQL(db, VirtualRouter::table, true, true)
{
register_hooks(hook_mads, remotes_location);
};
~VirtualRouterPool(){};
/**
* Allocates a new object, writing it in the pool database. No memory is
* allocated for the object.
* @param uid user id (the owner of the VirtualRouter)
* @param gid the id of the group this object is assigned to
* @param uname name of the owner user
* @param gname name of the group
* @param umask permissions umask
* @param template_contents a Template object
* @param oid the id assigned to the VirtualRouter
* @param error_str Returns the error reason, if any
*
* @return the oid assigned to the object, -1 in case of failure
*/
int allocate(int uid,
int gid,
const string& uname,
const string& gname,
int umask,
Template * template_contents,
int * oid,
string& error_str)
{
*oid = PoolSQL::allocate(
new VirtualRouter(-1, uid, gid, uname, gname, umask, template_contents),
error_str);
return *oid;
}
/**
* Gets an object from the pool (if needed the object is loaded from the
* database).
* @param oid the object unique identifier
* @param lock locks the object if true
*
* @return a pointer to the object, 0 in case of failure
*/
VirtualRouter * get(int oid, bool lock)
{
return static_cast<VirtualRouter *>(PoolSQL::get(oid,lock));
};
/**
* Gets an object from the pool (if needed the object is loaded from the
* database).
* @param name of the object
* @param uid id of owner
* @param lock locks the object if true
*
* @return a pointer to the object, 0 in case of failure
*/
VirtualRouter * get(const string& name, int uid, bool lock)
{
return static_cast<VirtualRouter *>(PoolSQL::get(name,uid,lock));
};
/**
* Dumps the pool in XML format. A filter can be also added to the
* query
* @param oss the output stream to dump the pool contents
* @param where filter for the objects, defaults to all
* @param limit parameters used for pagination
*
* @return 0 on success
*/
int dump(ostringstream& oss, const string& where, const string& limit)
{
return PoolSQL::dump(oss, "VROUTER_POOL", VirtualRouter::table, where,
limit);
};
/**
* Bootstraps the database table(s) associated to the pool
* @return 0 on success
*/
static int bootstrap(SqlDB *_db)
{
return VirtualRouter::bootstrap(_db);
};
/**
* Gets the IDs of objects matching the given SQL where string.
* @param oids a vector that contains the IDs
* @param where SQL clause
* @return 0 on success
*/
int search(vector<int>& oids, const string& where)
{
return PoolSQL::search(oids, VirtualRouter::table, where);
};
private:
/**
* Factory method to produce objects
* @return a pointer to the new object
*/
PoolObjectSQL * create()
{
return new VirtualRouter(-1,-1,-1,"","",0,0);
};
};
#endif /*VIRTUAL_ROUTER_POOL_H_*/

View File

@ -91,7 +91,7 @@ public:
* @param zone pointer to Zone
* @return 0 on success
*/
int update(Zone * zone);
int update(PoolObjectSQL * objsql);
/**
* Drops the Zone from the data base. The object mutex SHOULD be

View File

@ -227,7 +227,6 @@ LIB_DIRS="$LIB_LOCATION/ruby \
$LIB_LOCATION/ruby/cloud/ \
$LIB_LOCATION/ruby/cloud/econe \
$LIB_LOCATION/ruby/cloud/econe/views \
$LIB_LOCATION/ruby/cloud/marketplace \
$LIB_LOCATION/ruby/cloud/CloudAuth \
$LIB_LOCATION/ruby/onedb \
$LIB_LOCATION/ruby/onedb/shared \
@ -297,6 +296,10 @@ VAR_DIRS="$VAR_LOCATION/remotes \
$VAR_LOCATION/remotes/datastore/ceph \
$VAR_LOCATION/remotes/datastore/dev \
$VAR_LOCATION/remotes/datastore/vcenter \
$VAR_LOCATION/remotes/market \
$VAR_LOCATION/remotes/market/http \
$VAR_LOCATION/remotes/market/one \
$VAR_LOCATION/remotes/market/s3 \
$VAR_LOCATION/remotes/datastore/iscsi \
$VAR_LOCATION/remotes/auth \
$VAR_LOCATION/remotes/auth/plain \
@ -331,10 +334,6 @@ LIB_ECO_CLIENT_DIRS="$LIB_LOCATION/ruby \
$LIB_LOCATION/ruby/cloud/ \
$LIB_LOCATION/ruby/cloud/econe"
LIB_MARKET_CLIENT_DIRS="$LIB_LOCATION/ruby \
$LIB_LOCATION/ruby/opennebula \
$LIB_LOCATION/ruby/cloud/marketplace"
LIB_OCA_CLIENT_DIRS="$LIB_LOCATION/ruby \
$LIB_LOCATION/ruby/opennebula"
@ -344,7 +343,7 @@ LIB_CLI_CLIENT_DIRS="$LIB_LOCATION/ruby/cli \
CONF_CLI_DIRS="$ETC_LOCATION/cli"
if [ "$CLIENT" = "yes" ]; then
MAKE_DIRS="$MAKE_DIRS $LIB_ECO_CLIENT_DIRS $LIB_MARKET_CLIENT_DIRS \
MAKE_DIRS="$MAKE_DIRS $LIB_ECO_CLIENT_DIRS \
$LIB_OCA_CLIENT_DIRS $LIB_CLI_CLIENT_DIRS $CONF_CLI_DIRS \
$ETC_LOCATION"
elif [ "$ONEGATE" = "yes" ]; then
@ -435,6 +434,9 @@ INSTALL_FILES=(
DATASTORE_DRIVER_DEV_SCRIPTS:$VAR_LOCATION/remotes/datastore/dev
DATASTORE_DRIVER_VCENTER_SCRIPTS:$VAR_LOCATION/remotes/datastore/vcenter
DATASTORE_DRIVER_ISCSI_SCRIPTS:$VAR_LOCATION/remotes/datastore/iscsi
MARKETPLACE_DRIVER_HTTP_SCRIPTS:$VAR_LOCATION/remotes/market/http
MARKETPLACE_DRIVER_ONE_SCRIPTS:$VAR_LOCATION/remotes/market/one
MARKETPLACE_DRIVER_S3_SCRIPTS:$VAR_LOCATION/remotes/market/s3
NETWORK_FILES:$VAR_LOCATION/remotes/vnm
NETWORK_8021Q_FILES:$VAR_LOCATION/remotes/vnm/802.1Q
NETWORK_VXLAN_FILES:$VAR_LOCATION/remotes/vnm/vxlan
@ -453,8 +455,6 @@ INSTALL_FILES=(
ECO_LIB_FILES:$LIB_LOCATION/ruby/cloud/econe
ECO_LIB_VIEW_FILES:$LIB_LOCATION/ruby/cloud/econe/views
ECO_BIN_FILES:$BIN_LOCATION
MARKET_LIB_FILES:$LIB_LOCATION/ruby/cloud/marketplace
MARKET_BIN_FILES:$BIN_LOCATION
MAN_FILES:$MAN_LOCATION
DOCS_FILES:$DOCS_LOCATION
CLI_LIB_FILES:$LIB_LOCATION/ruby/cli
@ -471,8 +471,6 @@ INSTALL_CLIENT_FILES=(
ECO_LIB_CLIENT_FILES:$LIB_LOCATION/ruby/cloud/econe
ECO_BIN_CLIENT_FILES:$BIN_LOCATION
COMMON_CLOUD_CLIENT_LIB_FILES:$LIB_LOCATION/ruby/cloud
MARKET_LIB_CLIENT_FILES:$LIB_LOCATION/ruby/cloud/marketplace
MARKET_BIN_CLIENT_FILES:$BIN_LOCATION
CLI_BIN_FILES:$BIN_LOCATION
CLI_LIB_FILES:$LIB_LOCATION/ruby/cli
ONE_CLI_LIB_FILES:$LIB_LOCATION/ruby/cli/one_helper
@ -592,6 +590,9 @@ BIN_FILES="src/nebula/oned \
src/cli/oneflow-template \
src/cli/onesecgroup \
src/cli/onevdc \
src/cli/onevrouter \
src/cli/onemarket \
src/cli/onemarketapp \
src/cli/onevcenter \
src/onedb/onedb \
src/mad/utils/tty_expect \
@ -668,7 +669,9 @@ MADS_LIB_FILES="src/mad/sh/madcommon.sh \
src/authm_mad/one_auth_mad.rb \
src/authm_mad/one_auth_mad \
src/datastore_mad/one_datastore.rb \
src/datastore_mad/one_datastore"
src/datastore_mad/one_datastore \
src/market_mad/one_market.rb \
src/market_mad/one_market"
#-------------------------------------------------------------------------------
# VMM SH Driver KVM scripts, to be installed under $REMOTES_LOCATION/vmm/kvm
@ -693,7 +696,9 @@ VMM_EXEC_KVM_SCRIPTS="src/vmm_mad/remotes/kvm/cancel \
src/vmm_mad/remotes/kvm/snapshot_create \
src/vmm_mad/remotes/kvm/snapshot_revert \
src/vmm_mad/remotes/kvm/snapshot_delete \
src/vmm_mad/remotes/kvm/shutdown"
src/vmm_mad/remotes/kvm/shutdown \
src/vmm_mad/remotes/kvm/reconfigure \
src/vmm_mad/remotes/kvm/prereconfigure"
#-------------------------------------------------------------------------------
# VMM SH Driver Xen scripts, to be installed under $REMOTES_LOCATION/vmm/xen
@ -1174,7 +1179,9 @@ TM_ISCSI_FILES="src/tm_mad/iscsi/clone \
DATASTORE_DRIVER_COMMON_SCRIPTS="src/datastore_mad/remotes/xpath.rb \
src/datastore_mad/remotes/downloader.sh \
src/datastore_mad/remotes/libfs.sh \
src/datastore_mad/remotes/vcenter_uploader.rb"
src/datastore_mad/remotes/vcenter_uploader.rb \
src/datastore_mad/remotes/url.rb \
src/datastore_mad/remotes/libfs.sh"
DATASTORE_DRIVER_DUMMY_SCRIPTS="src/datastore_mad/remotes/dummy/cp \
src/datastore_mad/remotes/dummy/mkfs \
@ -1184,7 +1191,8 @@ DATASTORE_DRIVER_DUMMY_SCRIPTS="src/datastore_mad/remotes/dummy/cp \
src/datastore_mad/remotes/dummy/snap_delete \
src/datastore_mad/remotes/dummy/snap_revert \
src/datastore_mad/remotes/dummy/snap_flatten \
src/datastore_mad/remotes/dummy/rm"
src/datastore_mad/remotes/dummy/rm \
src/datastore_mad/remotes/dummy/export"
DATASTORE_DRIVER_FS_SCRIPTS="src/datastore_mad/remotes/fs/cp \
src/datastore_mad/remotes/fs/mkfs \
@ -1194,7 +1202,8 @@ DATASTORE_DRIVER_FS_SCRIPTS="src/datastore_mad/remotes/fs/cp \
src/datastore_mad/remotes/fs/snap_delete \
src/datastore_mad/remotes/fs/snap_revert \
src/datastore_mad/remotes/fs/snap_flatten \
src/datastore_mad/remotes/fs/rm"
src/datastore_mad/remotes/fs/rm \
src/datastore_mad/remotes/fs/export"
DATASTORE_DRIVER_VMFS_SCRIPTS="src/datastore_mad/remotes/vmfs/cp \
src/datastore_mad/remotes/vmfs/mkfs \
@ -1261,14 +1270,34 @@ DATASTORE_DRIVER_ISCSI_SCRIPTS="src/datastore_mad/remotes/iscsi/cp \
src/datastore_mad/remotes/iscsi/clone"
#-------------------------------------------------------------------------------
# Migration scripts for onedb command, to be installed under $LIB_LOCATION
# Marketplace drivers, to be installed under $REMOTES_LOCATION/market
# - HTTP based marketplace, $REMOTES_LOCATION/market/http
# - OpenNebula public marketplace, $REMOTES_LOCATION/market/one
# - S3-obeject based marketplace, $REMOTES_LOCATION/market/s3
#-------------------------------------------------------------------------------
MARKETPLACE_DRIVER_HTTP_SCRIPTS="src/market_mad/remotes/http/import \
src/market_mad/remotes/http/delete \
src/market_mad/remotes/http/monitor"
MARKETPLACE_DRIVER_ONE_SCRIPTS="src/market_mad/remotes/one/import \
src/market_mad/remotes/one/delete \
src/market_mad/remotes/one/monitor"
MARKETPLACE_DRIVER_S3_SCRIPTS="src/market_mad/remotes/s3/import \
src/market_mad/remotes/s3/delete \
src/market_mad/remotes/s3/monitor \
src/market_mad/remotes/s3/S3.rb"
#-------------------------------------------------------------------------------
# Migration scripts for onedb command, to be installed under $LIB_LOCATION
#-------------------------------------------------------------------------------
ONEDB_FILES="src/onedb/fsck.rb \
src/onedb/import_slave.rb \
src/onedb/onedb.rb \
src/onedb/onedb_backend.rb"
src/onedb/onedb_backend.rb \
src/onedb/sqlite2mysql.rb"
ONEDB_SHARED_MIGRATOR_FILES="src/onedb/shared/2.0_to_2.9.80.rb \
src/onedb/shared/2.9.80_to_2.9.85.rb \
@ -1311,7 +1340,8 @@ ONEDB_LOCAL_MIGRATOR_FILES="src/onedb/local/4.5.80_to_4.7.80.rb \
src/onedb/local/4.9.80_to_4.10.3.rb \
src/onedb/local/4.10.3_to_4.11.80.rb \
src/onedb/local/4.11.80_to_4.13.80.rb \
src/onedb/local/4.13.80_to_4.13.85.rb"
src/onedb/local/4.13.80_to_4.13.85.rb \
src/onedb/local/4.13.85_to_4.90.0.rb"
ONEDB_PATCH_FILES="src/onedb/patches/4.14_monitoring.rb \
src/onedb/patches/history_times.rb"
@ -1434,7 +1464,13 @@ RUBY_OPENNEBULA_LIB_FILES="src/oca/ruby/opennebula/acl_pool.rb \
src/oca/ruby/opennebula/xml_pool.rb \
src/oca/ruby/opennebula/xml_utils.rb \
src/oca/ruby/opennebula/zone_pool.rb \
src/oca/ruby/opennebula/zone.rb"
src/oca/ruby/opennebula/zone.rb \
src/oca/ruby/opennebula/virtual_router_pool.rb \
src/oca/ruby/opennebula/virtual_router.rb \
src/oca/ruby/opennebula/marketplace_pool.rb \
src/oca/ruby/opennebula/marketplace.rb \
src/oca/ruby/opennebula/marketplaceapp_pool.rb \
src/oca/ruby/opennebula/marketplaceapp.rb"
#-------------------------------------------------------------------------------
# Common Cloud Files
@ -1549,19 +1585,6 @@ ECO_ETC_FILES="src/cloud/ec2/etc/econe.conf"
ECO_ETC_TEMPLATE_FILES="src/cloud/ec2/etc/templates/m1.small.erb"
#-------------------------------------------------------------------------------
# Marketplace Client
#-------------------------------------------------------------------------------
MARKET_LIB_FILES="src/cloud/marketplace/lib/marketplace_client.rb"
MARKET_LIB_CLIENT_FILES="src/cloud/marketplace/lib/marketplace_client.rb"
MARKET_BIN_FILES="src/cloud/marketplace/bin/onemarket"
MARKET_BIN_CLIENT_FILES="src/cloud/marketplace/bin/onemarket"
#-----------------------------------------------------------------------------
# CLI files
#-----------------------------------------------------------------------------
@ -1584,7 +1607,10 @@ ONE_CLI_LIB_FILES="src/cli/one_helper/onegroup_helper.rb \
src/cli/one_helper/onezone_helper.rb \
src/cli/one_helper/onevdc_helper.rb \
src/cli/one_helper/oneacct_helper.rb \
src/cli/one_helper/onesecgroup_helper.rb"
src/cli/one_helper/onesecgroup_helper.rb \
src/cli/one_helper/onevrouter_helper.rb \
src/cli/one_helper/onemarketapp_helper.rb \
src/cli/one_helper/onemarket_helper.rb"
CLI_BIN_FILES="src/cli/onevm \
src/cli/onehost \
@ -1602,7 +1628,10 @@ CLI_BIN_FILES="src/cli/onevm \
src/cli/oneacct \
src/cli/onesecgroup \
src/cli/oneshowback \
src/cli/onevdc"
src/cli/onevdc \
src/cli/onevrouter \
src/cli/onemarketapp \
src/cli/onemarket"
CLI_CONF_FILES="src/cli/etc/onegroup.yaml \
src/cli/etc/onehost.yaml \
@ -1618,7 +1647,10 @@ CLI_CONF_FILES="src/cli/etc/onegroup.yaml \
src/cli/etc/oneacct.yaml \
src/cli/etc/onesecgroup.yaml \
src/cli/etc/oneshowback.yaml \
src/cli/etc/onevdc.yaml"
src/cli/etc/onevdc.yaml \
src/cli/etc/onevrouter.yaml \
src/cli/etc/onemarketapp.yaml \
src/cli/etc/onemarket.yaml"
#-----------------------------------------------------------------------------
# Sunstone files
@ -1644,7 +1676,6 @@ SUNSTONE_ETC_VIEW_FILES="src/sunstone/etc/sunstone-views/admin.yaml \
SUNSTONE_MODELS_FILES="src/sunstone/models/OpenNebulaJSON.rb \
src/sunstone/models/SunstoneServer.rb \
src/sunstone/models/SunstoneMarketplace.rb \
src/sunstone/models/SunstoneViews.rb"
SUNSTONE_MODELS_JSON_FILES="src/sunstone/models/OpenNebulaJSON/HostJSON.rb \
@ -1661,7 +1692,10 @@ SUNSTONE_MODELS_JSON_FILES="src/sunstone/models/OpenNebulaJSON/HostJSON.rb \
src/sunstone/models/OpenNebulaJSON/VirtualNetworkJSON.rb \
src/sunstone/models/OpenNebulaJSON/ZoneJSON.rb \
src/sunstone/models/OpenNebulaJSON/SecurityGroupJSON.rb \
src/sunstone/models/OpenNebulaJSON/VdcJSON.rb"
src/sunstone/models/OpenNebulaJSON/VdcJSON.rb \
src/sunstone/models/OpenNebulaJSON/VirtualRouterJSON.rb \
src/sunstone/models/OpenNebulaJSON/MarketPlaceJSON.rb \
src/sunstone/models/OpenNebulaJSON/MarketPlaceAppJSON.rb"
SUNSTONE_VIEWS_FILES="src/sunstone/views/index.erb \
src/sunstone/views/login.erb \
@ -1889,6 +1923,9 @@ MAN_FILES="share/man/oneacct.1.gz \
share/man/oneflow-template.1.gz \
share/man/onesecgroup.1.gz \
share/man/onevdc.1.gz \
share/man/onevrouter.1.gz \
share/man/onemarket.1.gz \
share/man/onemarketapp.1.gz \
share/man/econe-allocate-address.1.gz \
share/man/econe-associate-address.1.gz \
share/man/econe-attach-volume.1.gz \

View File

@ -650,6 +650,24 @@ DATASTORE_MAD = [
arguments = "-t 15 -d dummy,fs,vmfs,lvm,ceph,dev,iscsi,vcenter -s shared,ssh,ceph,vcenter"
]
#*******************************************************************************
# Marketplace Driver Configuration
#*******************************************************************************
# Drivers to manage different marketplaces, specialized for the storage backend
# executable: path of the transfer 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
# -t number of threads, i.e. number of repo operations at the same time
# -m marketplace mads separated by commas
#*******************************************************************************
MARKET_MAD = [
executable = "one_market",
arguments = "-t 15 -m http,s3,one"
]
#*******************************************************************************
# Hook Manager Configuration
#*******************************************************************************
@ -728,6 +746,7 @@ DATASTORE_MAD = [
# - NO, The hook is executed in the OpenNebula server (default)
#
# Virtual Network (VNET_HOOK)
# Virtual Router (VROUTER_HOOK)
# User (USER_HOOK)
# Group (GROUP_HOOK)
# Image (IMAGE_HOOK)
@ -1063,3 +1082,29 @@ DS_MAD_CONF = [
DS_MAD_CONF = [
NAME = "vcenter", REQUIRED_ATTRS = "VCENTER_CLUSTER", PERSISTENT_ONLY = "YES"
]
#*******************************************************************************
# MarketPlace Driver Behavior Configuration
#*******************************************************************************
# The configuration for each driver is defined in MARKET_MAD_CONF. These
# values are used when creating a new marketplaces and should not be modified
# since they define the marketplace behavior.
# name : name of the market driver
# required_attrs : comma separated list of required attributes in the Market
# template
#*******************************************************************************
MARKET_MAD_CONF = [
NAME = "one",
REQUIRED_ATTRS = ""
]
MARKET_MAD_CONF = [
NAME = "http",
REQUIRED_ATTRS = "BASE_URL,PUBLIC_DIR"
]
MARKET_MAD_CONF = [
NAME = "s3",
REQUIRED_ATTRS = "ACCESS_KEY_ID,SECRET_ACCESS_KEY,REGION,BUCKET"
]

View File

@ -64,6 +64,9 @@ env.Man('onezone')
env.Man('onevcenter')
env.Man('onesecgroup')
env.Man('onevdc')
env.Man('onevrouter')
env.Man('onemarket')
env.Man('onemarketapp')
env.Man('oneflow')
env.Man('oneflow-template')

94
share/man/onemarket.1 Normal file
View File

@ -0,0 +1,94 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "ONEMARKET" "1" "December 2015" "" "onemarket(1) -- manages OpenNebula marketplaces"
.
.SH "NAME"
\fBonemarket\fR \- manages OpenNebula marketplaces
.
.SH "SYNOPSIS"
\fBonemarket\fR \fIcommand\fR [\fIargs\fR] [\fIoptions\fR]
.
.SH "OPTIONS"
.
.nf
\-l, \-\-list x,y,z Selects columns to display with list command
\-d, \-\-delay x Sets the delay in seconds for top command
\-f, \-\-filter x,y,z Filter data\. An array is specified with
column=value pairs\.
\-\-csv Write table in csv format
\-x, \-\-xml Show the resource in xml format
\-n, \-\-numeric Do not translate user and group IDs
\-\-describe Describe list columns
\-a, \-\-append Append new attributes to the current template
\-v, \-\-verbose Verbose mode
\-h, \-\-help Show this message
\-V, \-\-version Show version and copyright information
\-\-user name User name used to connect to OpenNebula
\-\-password password Password to authenticate with OpenNebula
\-\-endpoint endpoint URL of OpenNebula xmlrpc frontend
.
.fi
.
.SH "COMMANDS"
.
.IP "\(bu" 4
create \fIfile\fR Creates a new Marketplace from the given template file
.
.IP "\(bu" 4
delete \fIrange|marketplaceid_list\fR Deletes the given Marketplace
.
.IP "\(bu" 4
chgrp \fIrange|marketplaceid_list\fR \fIgroupid\fR Changes the Marketplace group
.
.IP "\(bu" 4
chown \fIrange|marketplaceid_list\fR \fIuserid\fR [\fIgroupid\fR] Changes the Marketplace owner and group
.
.IP "\(bu" 4
chmod \fIrange|marketplaceid_list\fR \fIoctet\fR Changes the Marketplace permissions
.
.IP "\(bu" 4
list Lists Marketplaces valid options: list, delay, filter, csv, xml, numeric, describe
.
.IP "\(bu" 4
show \fImarketplaceid\fR Shows Marketplace information valid options: xml
.
.IP "\(bu" 4
update \fImarketplaceid\fR [\fIfile\fR] Update the template contents\. If a path is not provided the editor will be launched to modify the current content\. valid options: append
.
.IP "\(bu" 4
rename \fImarketplaceid\fR \fIname\fR Renames the Marketplace
.
.IP "" 0
.
.SH "ARGUMENT FORMATS"
.
.IP "\(bu" 4
file Path to a file
.
.IP "\(bu" 4
range List of id\'s in the form 1,8\.\.15
.
.IP "\(bu" 4
text String
.
.IP "\(bu" 4
marketplaceid OpenNebula MARKETPLACE name or id
.
.IP "\(bu" 4
marketplaceid_list Comma\-separated list of OpenNebula MARKETPLACE names or ids
.
.IP "\(bu" 4
groupid OpenNebula GROUP name or id
.
.IP "\(bu" 4
userid OpenNebula USER name or id
.
.IP "" 0
.
.SH "LICENSE"
OpenNebula 4\.14\.1 Copyright 2002\-2015, OpenNebula Project, OpenNebula Systems
.
.P
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

98
share/man/onemarketapp.1 Normal file
View File

@ -0,0 +1,98 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "ONEMARKETAPP" "1" "December 2015" "" "onemarketapp(1) -- manages OpenNebula marketplace apps"
.
.SH "NAME"
\fBonemarketapp\fR \- manages OpenNebula marketplace apps
.
.SH "SYNOPSIS"
\fBonemarket\fR \fIcommand\fR [\fIargs\fR] [\fIoptions\fR]
.
.SH "OPTIONS"
.
.nf
\-m, \-\-marketplace id|name Selects the marketplace
\-a, \-\-append Append new attributes to the current template
\-l, \-\-list x,y,z Selects columns to display with list command
\-d, \-\-delay x Sets the delay in seconds for top command
\-f, \-\-filter x,y,z Filter data\. An array is specified with
column=value pairs\.
\-\-csv Write table in csv format
\-x, \-\-xml Show the resource in xml format
\-n, \-\-numeric Do not translate user and group IDs
\-\-describe Describe list columns
\-v, \-\-verbose Verbose mode
\-h, \-\-help Show this message
\-V, \-\-version Show version and copyright information
\-\-user name User name used to connect to OpenNebula
\-\-password password Password to authenticate with OpenNebula
\-\-endpoint endpoint URL of OpenNebula xmlrpc frontend
.
.fi
.
.SH "COMMANDS"
.
.IP "\(bu" 4
create \fIfile\fR Creates a new marketplace app in the given marketplace valid options: marketplace
.
.IP "\(bu" 4
delete \fIrange|appid_list\fR Deletes the given marketplace app
.
.IP "\(bu" 4
update \fIappid\fR [\fIfile\fR] Update the template contents for the app\. If a path is not provided the editor will be launched to modify the current content\. valid options: append
.
.IP "\(bu" 4
chgrp \fIrange|appid_list\fR \fIgroupid\fR Changes the marketplace app group
.
.IP "\(bu" 4
chown \fIrange|appid_list\fR \fIuserid\fR [\fIgroupid\fR] Changes the marketplace app owner and group
.
.IP "\(bu" 4
chmod \fIrange|appid_list\fR \fIoctet\fR Changes the marketplace app permissions
.
.IP "\(bu" 4
rename \fIappid\fR \fIname\fR Renames the marketplace app
.
.IP "\(bu" 4
list [\fIfilterflag\fR] Lists marketplace apps valid options: list, delay, filter, csv, xml, numeric, describe
.
.IP "\(bu" 4
show \fIappid\fR Shows information for the given marketplace app valid options: xml
.
.IP "" 0
.
.SH "ARGUMENT FORMATS"
.
.IP "\(bu" 4
file Path to a file
.
.IP "\(bu" 4
range List of id\'s in the form 1,8\.\.15
.
.IP "\(bu" 4
text String
.
.IP "\(bu" 4
groupid OpenNebula GROUP name or id
.
.IP "\(bu" 4
userid OpenNebula USER name or id
.
.IP "\(bu" 4
appid OpenNebula MARKETPLACEAPP name or id
.
.IP "\(bu" 4
appid_list Comma\-separated list of OpenNebula MARKETPLACEAPP names or ids
.
.IP "\(bu" 4
filterflag a, all all the known MARKETPLACEAPPs m, mine the MARKETPLACEAPP belonging to the user in ONE_AUTH g, group \'mine\' plus the MARKETPLACEAPP belonging to the groups the user is member of uid MARKETPLACEAPP of the user identified by this uid user MARKETPLACEAPP of the user identified by the username
.
.IP "" 0
.
.SH "LICENSE"
OpenNebula 4\.14\.1 Copyright 2002\-2015, OpenNebula Project, OpenNebula Systems
.
.P
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

100
share/man/onevrouter.1 Normal file
View File

@ -0,0 +1,100 @@
.\" generated with Ronn/v0.7.3
.\" http://github.com/rtomayko/ronn/tree/0.7.3
.
.TH "ONEVROUTER" "1" "January 2016" "" "onevrouter(1) -- manages OpenNebula Virtual Routers"
.
.SH "NAME"
\fBonevrouter\fR \- manages OpenNebula Virtual Routers
.
.SH "SYNOPSIS"
\fBonevrouter\fR \fIcommand\fR [\fIargs\fR] [\fIoptions\fR]
.
.SH "OPTIONS"
.
.nf
\-a, \-\-append Append new attributes to the current template
\-l, \-\-list x,y,z Selects columns to display with list command
\-d, \-\-delay x Sets the delay in seconds for top command
\-f, \-\-filter x,y,z Filter data\. An array is specified with
column=value pairs\.
\-\-csv Write table in csv format
\-x, \-\-xml Show the resource in xml format
\-n, \-\-numeric Do not translate user and group IDs
\-\-describe Describe list columns
\-v, \-\-verbose Verbose mode
\-h, \-\-help Show this message
\-V, \-\-version Show version and copyright information
\-\-user name User name used to connect to OpenNebula
\-\-password password Password to authenticate with OpenNebula
\-\-endpoint endpoint URL of OpenNebula xmlrpc frontend
.
.fi
.
.SH "COMMANDS"
.
.IP "\(bu" 4
create \fIfile\fR Creates a new Virtual Router from the given description
.
.IP "\(bu" 4
delete \fIrange|vrouterid_list\fR Deletes the given Virtual Router
.
.IP "\(bu" 4
chgrp \fIrange|vrouterid_list\fR \fIgroupid\fR Changes the Virtual Router group
.
.IP "\(bu" 4
chown \fIrange|vrouterid_list\fR \fIuserid\fR [\fIgroupid\fR] Changes the Virtual Router owner and group
.
.IP "\(bu" 4
chmod \fIrange|vrouterid_list\fR \fIoctet\fR Changes the Virtual Router permissions
.
.IP "\(bu" 4
update \fIvrouterid\fR [\fIfile\fR] Update the Virtual Router contents\. If a path is not provided the editor will be launched to modify the current content\. valid options: append
.
.IP "\(bu" 4
rename \fIvrouterid\fR \fIname\fR Renames the Virtual Router
.
.IP "\(bu" 4
list [\fIfilterflag\fR] Lists the Virtual Routers in the pool valid options: list, delay, filter, csv, xml, numeric, describe
.
.IP "\(bu" 4
show \fIsecgroupid\fR Shows information for the given Virtual Router valid options: xml
.
.IP "\(bu" 4
top [\fIfilterflag\fR] Lists Virtual Routers continuously valid options: list, delay, filter, csv, xml, numeric, describe
.
.IP "" 0
.
.SH "ARGUMENT FORMATS"
.
.IP "\(bu" 4
file Path to a file
.
.IP "\(bu" 4
range List of id\'s in the form 1,8\.\.15
.
.IP "\(bu" 4
text String
.
.IP "\(bu" 4
groupid OpenNebula GROUP name or id
.
.IP "\(bu" 4
userid OpenNebula USER name or id
.
.IP "\(bu" 4
vrouterid OpenNebula VROUTER name or id
.
.IP "\(bu" 4
vrouterid_list Comma\-separated list of OpenNebula VROUTER names or ids
.
.IP "\(bu" 4
filterflag a, all all the known VROUTERs m, mine the VROUTER belonging to the user in ONE_AUTH g, group \'mine\' plus the VROUTER belonging to the groups the user is member of uid VROUTER of the user identified by this uid user VROUTER of the user identified by the username
.
.IP "" 0
.
.SH "LICENSE"
OpenNebula 4\.14\.1 Copyright 2002\-2015, OpenNebula Project, OpenNebula Systems
.
.P
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

View File

@ -103,6 +103,15 @@ AclManager::AclManager(
AuthRequest::USE,
AclRule::ALL_ID,
error_str);
// * MARKETPLACE+MARKETPLACEAPP/* USE *
add_rule(AclRule::ALL_ID,
AclRule::ALL_ID |
PoolObjectSQL::MARKETPLACE |
PoolObjectSQL::MARKETPLACEAPP,
AuthRequest::USE,
AclRule::ALL_ID,
error_str);
}
}

View File

@ -28,7 +28,7 @@ const long long AclRule::CLUSTER_ID = 0x0000000800000000LL;
const long long AclRule::NONE_ID = 0x1000000000000000LL;
const int AclRule::num_pool_objects = 13;
const int AclRule::num_pool_objects = 16;
const PoolObjectSQL::ObjectType AclRule::pool_objects[] = {
PoolObjectSQL::VM,
PoolObjectSQL::HOST,
@ -42,7 +42,10 @@ const PoolObjectSQL::ObjectType AclRule::pool_objects[] = {
PoolObjectSQL::DOCUMENT,
PoolObjectSQL::ZONE,
PoolObjectSQL::SECGROUP,
PoolObjectSQL::VDC
PoolObjectSQL::VDC,
PoolObjectSQL::VROUTER,
PoolObjectSQL::MARKETPLACE,
PoolObjectSQL::MARKETPLACEAPP
};
const int AclRule::num_auth_operations = 4;
@ -57,7 +60,8 @@ const long long AclRule::INVALID_CLUSTER_OBJECTS =
PoolObjectSQL::VM | PoolObjectSQL::IMAGE | PoolObjectSQL::USER |
PoolObjectSQL::TEMPLATE | PoolObjectSQL::GROUP | PoolObjectSQL::ACL |
PoolObjectSQL::CLUSTER | PoolObjectSQL::DOCUMENT | PoolObjectSQL::ZONE |
PoolObjectSQL::SECGROUP | PoolObjectSQL::VDC;
PoolObjectSQL::SECGROUP | PoolObjectSQL::VDC | PoolObjectSQL::VROUTER |
PoolObjectSQL::MARKETPLACE | PoolObjectSQL::MARKETPLACEAPP;
const long long AclRule::INVALID_GROUP_OBJECTS =
PoolObjectSQL::HOST | PoolObjectSQL::GROUP | PoolObjectSQL::CLUSTER |
@ -222,7 +226,7 @@ bool AclRule::malformed(string& error_str) const
oss << "when using the ALL bit, [resource] ID must be 0";
}
if ( (resource & 0xFFFF000000000LL) == 0 )
if ( (resource & 0xFFFFFFF000000000LL) == 0 )
{
if ( error )
{
@ -233,7 +237,7 @@ bool AclRule::malformed(string& error_str) const
oss << "[resource] type is missing";
}
if ( (resource & 0xFFFC000000000000LL) != 0 )
if ( (resource & 0xFFE0000000000000LL) != 0 )
{
if ( error )
{

View File

@ -9,9 +9,9 @@
:size: 8
:right: true
:RES_VHNIUTGDCOZSv:
:RES_VHNIUTGDCOZSvRMA:
:desc: Which resource the rule applies to
:size: 17
:size: 20
:RID:
:desc: Resource ID
@ -31,7 +31,7 @@
:default:
- :ID
- :USER
- :RES_VHNIUTGDCOZSv
- :RES_VHNIUTGDCOZSvRMA
- :RID
- :OPE_UMAC
- :ZONE

View File

@ -0,0 +1,35 @@
---
:ID:
:desc: ONE identifier for the Marketplace
:size: 4
:NAME:
:desc: Name of the Marketplace
:size: 30
:left: true
:SIZE:
:desc: Marketplace total size (M)
:size: 10
:AVAIL:
:desc: MarketPlace free size (%)
:size: 10
:left: true
:APPS:
:desc: Number of Marketplace Apps
:size: 6
:MAD:
:desc: Marketplace driver
:size: 7
:left: true
:default:
- :ID
- :SIZE
- :AVAIL
- :APPS
- :MAD
- :NAME

View File

@ -0,0 +1,50 @@
---
:ID:
:desc: ONE identifier for the marketplace app
:size: 4
:NAME:
:desc: Name of the marketplace app
:size: 15
:left: true
:VERSION:
:desc: Version of the marketplace app
:size: 7
:SIZE:
:desc: Marketplace app size (M)
:size: 5
:STAT:
:desc: State of the app
:size: 4
:TYPE:
:desc: Marketplace app type
:size: 4
:DATE:
:desc: Publishing date for the marketplace app
:size: 8
:MARKET:
:desc: ID of the marketplace
:size: 6
:PUBLISHER:
:desc: Publisher of the marketplace app
:size: 25
:left: true
:default:
- :ID
- :NAME
- :VERSION
- :SIZE
- :STAT
- :TYPE
- :DATE
- :MARKET
- :PUBLISHER

View File

@ -0,0 +1,25 @@
---
:ID:
:desc: ONE identifier for the Virtual Router
:size: 4
:NAME:
:desc: Name of the Virtual Router
:size: 27
:left: true
:USER:
:desc: Username of the Virtual Router owner
:size: 15
:left: true
:GROUP:
:desc: Group of the Virtual Router
:size: 15
:left: true
:default:
- :ID
- :USER
- :GROUP
- :NAME

View File

@ -714,16 +714,17 @@ EOT
client=OneHelper.client
pool = case poolname
when "HOST" then OpenNebula::HostPool.new(client)
when "GROUP" then OpenNebula::GroupPool.new(client)
when "USER" then OpenNebula::UserPool.new(client)
when "DATASTORE" then OpenNebula::DatastorePool.new(client)
when "CLUSTER" then OpenNebula::ClusterPool.new(client)
when "VNET" then OpenNebula::VirtualNetworkPool.new(client)
when "IMAGE" then OpenNebula::ImagePool.new(client)
when "VMTEMPLATE" then OpenNebula::TemplatePool.new(client)
when "VM" then OpenNebula::VirtualMachinePool.new(client)
when "ZONE" then OpenNebula::ZonePool.new(client)
when "HOST" then OpenNebula::HostPool.new(client)
when "GROUP" then OpenNebula::GroupPool.new(client)
when "USER" then OpenNebula::UserPool.new(client)
when "DATASTORE" then OpenNebula::DatastorePool.new(client)
when "CLUSTER" then OpenNebula::ClusterPool.new(client)
when "VNET" then OpenNebula::VirtualNetworkPool.new(client)
when "IMAGE" then OpenNebula::ImagePool.new(client)
when "VMTEMPLATE" then OpenNebula::TemplatePool.new(client)
when "VM" then OpenNebula::VirtualMachinePool.new(client)
when "ZONE" then OpenNebula::ZonePool.new(client)
when "MARKETPLACE" then OpenNebula::MarketPlacePool.new(client)
end
rc = pool.info
@ -963,7 +964,7 @@ EOT
end
end
def self.create_template(options)
def self.create_template(options, template_obj=nil)
template=''
template<<"NAME=\"#{options[:name]}\"\n" if options[:name]
@ -1020,6 +1021,17 @@ EOT
context=create_context(options)
template<<context if context
if options[:userdata] && !template_obj.nil?
if template_obj.has_elements?('TEMPLATE/EC2')
template_obj.add_element(
'TEMPLATE/EC2',
'USERDATA' => options[:userdata])
template << template_obj.template_like_str(
'TEMPLATE', false, 'EC2')
end
end
[0, template]
end

View File

@ -44,7 +44,7 @@ private
def self.resource_mask(str)
resource_type=str.split("/")[0]
mask = "-------------"
mask = "----------------"
resource_type.split("+").each{|type|
case type
@ -74,6 +74,12 @@ private
mask[11] = "S"
when "VDC"
mask[12] = "v"
when "VROUTER"
mask[13] = "R"
when "MARKETPLACE"
mask[14] = "M"
when "MARKETPLACEAPP"
mask[15] = "A"
end
}
mask
@ -113,8 +119,8 @@ private
d['STRING'].split(" ")[0]
end
column :RES_VHNIUTGDCOZSv, "Resource to which the rule applies",
:size => 17 do |d|
column :RES_VHNIUTGDCOZSvRMA, "Resource to which the rule applies",
:size => 20 do |d|
OneAclHelper::resource_mask d['STRING'].split(" ")[1]
end
@ -131,7 +137,7 @@ private
OneAclHelper::right_mask d['STRING'].split(" ")[2]
end
default :ID, :USER, :RES_VHNIUTGDCOZSv, :RID, :OPE_UMAC, :ZONE
default :ID, :USER, :RES_VHNIUTGDCOZSvRMA, :RID, :OPE_UMAC, :ZONE
end
table

View File

@ -0,0 +1,138 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# 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_helper'
class OneMarketPlaceHelper < OpenNebulaHelper::OneHelper
MARKETPLACE = {
:name => "marketplace",
:short => "-m id|name",
:large => "--marketplace id|name" ,
:description => "Selects the marketplace",
:format => String,
:proc => lambda { |o, options|
OpenNebulaHelper.rname_to_id(o, "MARKETPLACE")
}
}
def self.rname
"MARKETPLACE"
end
def self.conf_file
"onemarket.yaml"
end
def format_pool(options)
config_file = self.class.table_conf
table = CLIHelper::ShowTable.new(config_file, self) do
column :ID, "ONE identifier for the Marketplace", :size=>4 do |d|
d["ID"]
end
column :NAME, "Name of the Marketplace", :left, :size=>30 do |d|
d["NAME"]
end
column :SIZE, "Marketplace total size", :size =>10 do |d|
OpenNebulaHelper.unit_to_str(d['TOTAL_MB'].to_i, {}, 'M')
end
column :AVAIL, "Marketplace free size", :left, :size =>10 do |d|
if d['TOTAL_MB'].to_i == 0
"-"
else
"#{((d['FREE_MB'].to_f/d['TOTAL_MB'].to_f) * 100).round()}%"
end
end
column :APPS, "Number of marketplace apps", :size=>6 do |d|
if d["MARKETPLACEAPPS"]["ID"].nil?
"0"
else
d["MARKETPLACEAPPS"]["ID"].size
end
end
column :MAD, "Marketplace driver", :left, :size=>7 do |d|
d["MARKET_MAD"]
end
default :ID, :SIZE, :AVAIL, :APPS, :TYPE, :MAD, :NAME
end
table
end
private
def factory(id=nil)
if id
OpenNebula::MarketPlace.new_with_id(id, @client)
else
xml=OpenNebula::MarketPlace.build_xml
OpenNebula::MarketPlace.new(xml, @client)
end
end
def factory_pool(user_flag=-2)
OpenNebula::MarketPlacePool.new(@client)
end
def format_resource(market, options = {})
str="%-15s: %-20s"
str_h1="%-80s"
CLIHelper.print_header(str_h1 % "MARKETPLACE #{market['ID']} INFORMATION")
puts str % ["ID", market.id.to_s]
puts str % ["NAME", market.name]
puts str % ["USER", market['UNAME']]
puts str % ["GROUP", market['GNAME']]
puts str % ["MARKET_MAD", market['MARKET_MAD']]
puts
CLIHelper.print_header(str_h1 % "MARKETPLACE CAPACITY", false)
puts str % ["TOTAL:", OpenNebulaHelper.unit_to_str(market['TOTAL_MB'].to_i,{},'M')]
puts str % ["FREE:", OpenNebulaHelper.unit_to_str(market['FREE_MB'].to_i, {},'M')]
puts str % ["USED: ", OpenNebulaHelper.unit_to_str(market['USED_MB'].to_i, {},'M')]
puts
CLIHelper.print_header(str_h1 % "PERMISSIONS",false)
["OWNER", "GROUP", "OTHER"].each { |e|
mask = "---"
mask[0] = "u" if market["PERMISSIONS/#{e}_U"] == "1"
mask[1] = "m" if market["PERMISSIONS/#{e}_M"] == "1"
mask[2] = "a" if market["PERMISSIONS/#{e}_A"] == "1"
puts str % [e, mask]
}
puts
CLIHelper.print_header(str_h1 % "MARKETPLACE TEMPLATE", false)
puts market.template_str
puts
CLIHelper.print_header("%-15s" % "MARKETAPPS")
market.marketapp_ids.each do |id|
puts "%-15s" % [id]
end
end
end

View File

@ -0,0 +1,148 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# 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_helper'
class OneMarketPlaceAppHelper < OpenNebulaHelper::OneHelper
def self.rname
"MARKETPLACEAPP"
end
def self.conf_file
"onemarketapp.yaml"
end
def self.state_to_str(id)
id = id.to_i
state_str = MarketPlaceApp::MARKETPLACEAPP_STATES[id]
return MarketPlaceApp::SHORT_MARKETPLACEAPP_STATES[state_str]
end
def format_pool(options)
config_file = self.class.table_conf
table = CLIHelper::ShowTable.new(config_file, self) do
column :ID, "ONE identifier for the marketplace app", :size=>4 do |d|
d["ID"]
end
column :NAME, "Name of the marketplace app", :left, :size=>15 do |d|
d["NAME"]
end
column :PUBLISHER, "Publisher of the App", :left, :size=>25 do |d|
d["PUBLISHER"]
end
column :VERSION, "Version of the app", :size=>7 do |d|
d["VERSION"]
end
column :SIZE, "App size", :size =>5 do |d|
OpenNebulaHelper.unit_to_str(d['SIZE'].to_i, {}, 'M')
end
column :STAT, "State of the app", :size=>4 do |d|
OneMarketPlaceAppHelper.state_to_str(d["STATE"])
end
column :DATE, "Publishing date of the app", :size=>8 do |d|
Time.at(d['DATE'].to_i).strftime("%D")
end
column :TYPE, "Marketplace app type", :size=>4 do |d|
type = MarketPlaceApp::MARKETPLACEAPP_TYPES[d["TYPE"].to_i]
MarketPlaceApp::SHORT_MARKETPLACEAPP_TYPES[type]
end
column :MARKET, "ID of the marketplace", :size=>6 do |d|
d["MARKETPLACE_ID"]
end
default :ID,:NAME,:VERSION,:SIZE,:STAT,:TYPE,:DATE,:MARKET,:PUBLISHER
end
table
end
private
def factory(id=nil)
if id
OpenNebula::MarketPlaceApp.new_with_id(id, @client)
else
xml=OpenNebula::MarketPlaceApp.build_xml
OpenNebula::MarketPlaceApp.new(xml, @client)
end
end
def factory_pool(user_flag=-2)
OpenNebula::MarketPlaceAppPool.new(@client, user_flag)
end
def format_resource(app, options = {})
str="%-15s: %-20s"
str_h1="%-80s"
CLIHelper.print_header(str_h1 % "MARKETPLACE APP #{app['ID']} INFORMATION")
puts str % ["ID", app.id.to_s]
puts str % ["NAME", app.name]
puts str % ["TYPE", app.type_str]
puts str % ["USER", app['UNAME']]
puts str % ["GROUP", app['GNAME']]
puts str % ["MARKETPLACE", app['MARKETPLACE']]
puts str % ["STATE", OneMarketPlaceAppHelper.state_to_str(app["STATE"])]
puts
CLIHelper.print_header(str_h1 % "PERMISSIONS",false)
["OWNER", "GROUP", "OTHER"].each { |e|
mask = "---"
mask[0] = "u" if app["PERMISSIONS/#{e}_U"] == "1"
mask[1] = "m" if app["PERMISSIONS/#{e}_M"] == "1"
mask[2] = "a" if app["PERMISSIONS/#{e}_A"] == "1"
puts str % [e, mask]
}
puts
CLIHelper.print_header(str_h1 % "DETAILS", false)
puts str % ["SOURCE", app['SOURCE']]
puts str % ["MD5", app['MD5']]
puts str % ["PUBLISHER", app['PUBLISHER']]
puts str % ["PUB. DATE", Time.at(app['DATE'].to_i).strftime("%c") ]
puts str % ["VERSION", app['VERSION']]
puts str % ["DESCRIPTION", app['DESCRIPTION']]
puts str % ["SIZE", OpenNebulaHelper.unit_to_str(app['SIZE'].to_i,{},'M')]
puts str % ["ORIGIN_ID", app['ORIGIN_ID']]
puts str % ["FORMAT", app['FORMAT']]
puts
CLIHelper.print_header(str_h1 % "IMPORT TEMPLATE", false)
puts Base64.decode64(app['APPTEMPLATE64'])
puts
CLIHelper.print_header(str_h1 % "MARKETPLACE APP TEMPLATE", false)
puts app.template_str
puts
end
end

View File

@ -111,7 +111,7 @@ EOT
table
end
def get_user_inputs(template)
def self.get_user_inputs(template)
user_inputs = template['VMTEMPLATE']['TEMPLATE']['USER_INPUTS']
return "" if !user_inputs

View File

@ -84,6 +84,14 @@ class OneVMHelper < OpenNebulaHelper::OneHelper
}
}
IP={
:name => "ip",
:short => "-i ip",
:large => "--ip ip",
:format => String,
:description => "IP address for the new NIC"
}
FILE = {
:name => "file",
:short => "-f file",
@ -170,16 +178,11 @@ class OneVMHelper < OpenNebulaHelper::OneHelper
end
vm_nics.each do |nic|
if nic.has_key?("IP")
ips.push(nic["IP"])
end
if nic.has_key?("IP6_GLOBAL")
ips.push(nic["IP6_GLOBAL"])
end
if nic.has_key?("IP6_ULA")
ips.push(nic["IP6_ULA"])
["IP", "IP6_GLOBAL", "IP6_ULA",
"VROUTER_IP", "VROUTER_IP6_GLOBAL", "VROUTER_IP6_ULA"].each do |attr|
if nic.has_key?(attr)
ips.push(nic[attr])
end
end
end
@ -517,6 +520,8 @@ in the frontend machine.
OpenNebulaHelper.time_to_str(vm['/VM/ETIME'])]
value=vm['DEPLOY_ID']
puts str % ["DEPLOY ID", value=="" ? "-" : value]
value=vm['TEMPLATE/VROUTER_ID']
puts str % ["VIRTUAL ROUTER ID", value] if value
puts
@ -735,37 +740,31 @@ in the frontend machine.
next if nic.has_key?("CLI_DONE")
if nic.has_key?("IP6_LINK")
shown_ips << nic["IP6_LINK"]
["IP6_LINK", "IP6_ULA", "IP6_GLOBAL"].each do |attr|
if nic.has_key?(attr)
shown_ips << nic[attr]
ip6_link = {"IP" => nic.delete("IP6_LINK"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
ipstr = {"IP" => nic.delete(attr),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ipstr)
array_id += 1
array_id += 1
end
end
if nic.has_key?("IP6_ULA")
shown_ips << nic["IP6_ULA"]
["VROUTER_IP", "VROUTER_IP6_LINK",
"VROUTER_IP6_ULA", "VROUTER_IP6_GLOBAL"].each do |attr|
if nic.has_key?(attr)
shown_ips << nic[attr]
ip6_link = {"IP" => nic.delete("IP6_ULA"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
ipstr = {"IP" => nic.delete(attr) + " (VRouter)",
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ipstr)
array_id += 1
end
if nic.has_key?("IP6_GLOBAL")
shown_ips << nic["IP6_GLOBAL"]
ip6_link = {"IP" => nic.delete("IP6_GLOBAL"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
array_id += 1
array_id += 1
end
end
shown_ips << nic["IP"] if nic.has_key?("IP")

View File

@ -308,6 +308,8 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
"V:#{d['VM']}"
elsif d['VNET']
"N:#{d['VNET']}"
elsif d['VROUTER']
"R:#{d['VROUTER']}"
end
end
@ -324,6 +326,13 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
end
end.show(leases, {})
puts
CLIHelper.print_header("%-15s" % "VIRTUAL ROUTERS")
vn.vrouter_ids.each do |id|
puts "%-15s" % [id]
end
if options[:show_ar]
ar_list.each do |ar_id|
puts

View File

@ -0,0 +1,225 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# 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_helper'
class OneVirtualRouterHelper < OpenNebulaHelper::OneHelper
ALL_TEMPLATE = {
:name => "all",
:large => "--all",
:description => "Show all template data"
}
def self.rname
"VROUTER"
end
def self.conf_file
"onevrouter.yaml"
end
def show_resource(id, options)
resource = retrieve_resource(id)
if !options[:extended].nil?
rc = resource.info(options[:extended])
else
rc = resource.info
end
return -1, rc.message if OpenNebula.is_error?(rc)
if options[:xml]
return 0, resource.to_xml(true)
else
format_resource(resource, options)
return 0
end
end
def format_pool(options)
config_file = self.class.table_conf
table = CLIHelper::ShowTable.new(config_file, self) do
column :ID, "ONE identifier for the Virtual Router", :size=>4 do |d|
d["ID"]
end
column :NAME, "Name of the Virtual Router", :left, :size=>27 do |d|
d["NAME"]
end
column :USER, "Username of the Virtual Router owner", :left,
:size=>15 do |d|
helper.user_name(d, options)
end
column :GROUP, "Group of the Virtual Router", :left, :size=>15 do |d|
helper.group_name(d, options)
end
default :ID, :USER, :GROUP, :NAME
end
table
end
private
def factory(id=nil)
if id
OpenNebula::VirtualRouter.new_with_id(id, @client)
else
xml=OpenNebula::VirtualRouter.build_xml
OpenNebula::VirtualRouter.new(xml, @client)
end
end
def factory_pool(user_flag=-2)
OpenNebula::VirtualRouterPool.new(@client, user_flag)
end
def format_resource(obj, options = {})
str="%-15s: %-20s"
str_h1="%-80s"
CLIHelper.print_header(
str_h1 % "VIRTUAL ROUTER #{obj['ID']} INFORMATION")
puts str % ["ID", obj.id.to_s]
puts str % ["NAME", obj.name]
puts str % ["USER", obj['UNAME']]
puts str % ["GROUP", obj['GNAME']]
puts
CLIHelper.print_header(str_h1 % "PERMISSIONS",false)
["OWNER", "GROUP", "OTHER"].each { |e|
mask = "---"
mask[0] = "u" if obj["PERMISSIONS/#{e}_U"] == "1"
mask[1] = "m" if obj["PERMISSIONS/#{e}_M"] == "1"
mask[2] = "a" if obj["PERMISSIONS/#{e}_A"] == "1"
puts str % [e, mask]
}
if obj.has_elements?("/VROUTER/TEMPLATE/NIC")
puts
CLIHelper.print_header(str_h1 % "VIRTUAL ROUTER NICS",false)
nic_default = {"NETWORK" => "-",
"IP" => "-"}
shown_ips = []
array_id = 0
vm_nics = [obj.to_hash['VROUTER']['TEMPLATE']['NIC']].flatten.compact
vm_nics.each {|nic|
next if nic.has_key?("CLI_DONE")
if nic.has_key?("IP6_LINK")
shown_ips << nic["IP6_LINK"]
ip6_link = {"IP" => nic.delete("IP6_LINK"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
array_id += 1
end
if nic.has_key?("IP6_ULA")
shown_ips << nic["IP6_ULA"]
ip6_link = {"IP" => nic.delete("IP6_ULA"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
array_id += 1
end
if nic.has_key?("IP6_GLOBAL")
shown_ips << nic["IP6_GLOBAL"]
ip6_link = {"IP" => nic.delete("IP6_GLOBAL"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
array_id += 1
end
shown_ips << nic["IP"] if nic.has_key?("IP")
nic.merge!(nic_default) {|k,v1,v2| v1}
array_id += 1
}
CLIHelper::ShowTable.new(nil, self) do
column :ID, "", :size=>3 do |d|
if d["DOUBLE_ENTRY"]
""
else
d["NIC_ID"]
end
end
column :NETWORK, "", :left, :size=>20 do |d|
if d["DOUBLE_ENTRY"]
""
else
d["NETWORK"]
end
end
column :MANAGEMENT, "", :left, :size=>10 do |d|
if d["DOUBLE_ENTRY"]
""
else
if !d["VROUTER_MANAGEMENT"].nil?
d["VROUTER_MANAGEMENT"]
else
"NO"
end
end
end
column :IP, "",:left, :donottruncate, :size=>15 do |d|
d["IP"]
end
end.show(vm_nics,{})
end
while obj.has_elements?("/VROUTER/TEMPLATE/NIC")
obj.delete_element("/VROUTER/TEMPLATE/NIC")
end if !options[:all]
puts
CLIHelper.print_header(str_h1 % "TEMPLATE CONTENTS",false)
puts obj.template_str
puts
CLIHelper.print_header("%-15s" % "VIRTUAL MACHINES")
obj.vm_ids.each do |id|
puts "%-15s" % [id]
end
end
end

178
src/cli/onemarket Executable file
View File

@ -0,0 +1,178 @@
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
ONE_LOCATION=ENV["ONE_LOCATION"]
if !ONE_LOCATION
RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end
$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cli"
require 'command_parser'
require 'one_helper/onemarket_helper'
cmd=CommandParser::CmdParser.new(ARGV) do
usage "`onemarket` <command> [<args>] [<options>]"
version OpenNebulaHelper::ONE_VERSION
helper = OneMarketPlaceHelper.new
before_proc do
helper.set_client(options)
end
########################################################################
# Global Options
########################################################################
set :option, CommandParser::OPTIONS+OpenNebulaHelper::CLIENT_OPTIONS
list_options = CLIHelper::OPTIONS
list_options << OpenNebulaHelper::XML
list_options << OpenNebulaHelper::NUMERIC
list_options << OpenNebulaHelper::DESCRIBE
########################################################################
# Formatters for arguments
########################################################################
set :format, :marketplaceid, OneMarketPlaceHelper.to_id_desc do |arg|
helper.to_id(arg)
end
set :format, :marketplaceid_list, OneMarketPlaceHelper.list_to_id_desc do |arg|
helper.list_to_id(arg)
end
set :format, :groupid, OpenNebulaHelper.rname_to_id_desc("GROUP") do |arg|
OpenNebulaHelper.rname_to_id(arg, "GROUP")
end
set :format, :userid, OpenNebulaHelper.rname_to_id_desc("USER") do |arg|
OpenNebulaHelper.rname_to_id(arg, "USER")
end
########################################################################
# Commands
########################################################################
create_desc = <<-EOT.unindent
Creates a new Marketplace from the given template file
EOT
command :create, create_desc, :file do
helper.create_resource(options) do |marketplace|
begin
template = File.read(args[0])
marketplace.allocate(template)
rescue =>e
STDERR.puts e.message
exit -1
end
end
end
delete_desc = <<-EOT.unindent
Deletes the given Marketplace
EOT
command :delete, delete_desc, [:range, :marketplaceid_list] do
helper.perform_actions(args[0],options,"deleted") do |obj|
obj.delete
end
end
chgrp_desc = <<-EOT.unindent
Changes the Marketplace group
EOT
command :chgrp, chgrp_desc,[:range, :marketplaceid_list], :groupid do
helper.perform_actions(args[0],options,"Group changed") do |obj|
obj.chown(-1, args[1].to_i)
end
end
chown_desc = <<-EOT.unindent
Changes the Marketplace owner and group
EOT
command :chown, chown_desc, [:range, :marketplaceid_list], :userid,
[:groupid,nil] do
gid = args[2].nil? ? -1 : args[2].to_i
helper.perform_actions(args[0],options,"Owner/Group changed") do |obj|
obj.chown(args[1].to_i, gid)
end
end
chmod_desc = <<-EOT.unindent
Changes the Marketplace permissions
EOT
command :chmod, chmod_desc, [:range, :marketplaceid_list], :octet do
helper.perform_actions(args[0],options, "Permissions changed") do |obj|
obj.chmod_octet(args[1])
end
end
list_desc = <<-EOT.unindent
Lists Marketplaces
EOT
command :list, list_desc, :options=>list_options do
helper.list_pool(options)
end
show_desc = <<-EOT.unindent
Shows Marketplace information
EOT
command :show, show_desc, :marketplaceid, :options=>OpenNebulaHelper::XML do
helper.show_resource(args[0],options)
end
update_desc = <<-EOT.unindent
Update the template contents. If a path is not provided the editor will
be launched to modify the current content.
EOT
command :update, update_desc, :marketplaceid, [:file, nil],
:options=>OpenNebulaHelper::APPEND do
helper.perform_action(args[0],options,"modified") do |obj|
if options[:append]
str = OpenNebulaHelper.append_template(args[0], obj, args[1])
else
str = OpenNebulaHelper.update_template(args[0], obj, args[1])
end
obj.update(str, options[:append])
end
end
rename_desc = <<-EOT.unindent
Renames the Marketplace
EOT
command :rename, rename_desc, :marketplaceid, :name do
helper.perform_action(args[0],options,"renamed") do |o|
o.rename(args[1])
end
end
end

236
src/cli/onemarketapp Executable file
View File

@ -0,0 +1,236 @@
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
ONE_LOCATION=ENV["ONE_LOCATION"]
if !ONE_LOCATION
RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end
$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cli"
require 'command_parser'
require 'one_helper/onemarketapp_helper'
require 'one_helper/onemarket_helper'
require 'one_helper/onedatastore_helper'
CommandParser::CmdParser.new(ARGV) do
usage "`onemarket` <command> [<args>] [<options>]"
version OpenNebulaHelper::ONE_VERSION
helper = OneMarketPlaceAppHelper.new
before_proc do
helper.set_client(options)
end
########################################################################
# Global Options
########################################################################
set :option, CommandParser::OPTIONS+OpenNebulaHelper::CLIENT_OPTIONS
list_options = CLIHelper::OPTIONS
list_options << OpenNebulaHelper::XML
list_options << OpenNebulaHelper::NUMERIC
list_options << OpenNebulaHelper::DESCRIBE
CREATE_OPTIONS = [OneMarketPlaceHelper::MARKETPLACE]
EXPORT_OPTIONS = [OneDatastoreHelper::DATASTORE]
########################################################################
# Formatters for arguments
########################################################################
set :format, :groupid, OpenNebulaHelper.rname_to_id_desc("GROUP") do |arg|
OpenNebulaHelper.rname_to_id(arg, "GROUP")
end
set :format, :userid, OpenNebulaHelper.rname_to_id_desc("USER") do |arg|
OpenNebulaHelper.rname_to_id(arg, "USER")
end
set :format, :appid, OneMarketPlaceAppHelper.to_id_desc do |arg|
helper.to_id(arg)
end
set :format, :appid_list, OneMarketPlaceAppHelper.list_to_id_desc do |arg|
helper.list_to_id(arg)
end
set :format, :filterflag, OneMarketPlaceAppHelper.filterflag_to_i_desc do |arg|
helper.filterflag_to_i(arg)
end
########################################################################
# Commands
########################################################################
create_desc = <<-EOT.unindent
Creates a new marketplace app in the given marketplace
EOT
command :create, create_desc, :file, :options=>CREATE_OPTIONS do
if options[:marketplace].nil?
STDERR.puts "Marketplace to save the app is mandatory: "
STDERR.puts "\t -m marketplace_id"
exit(-1)
end
helper.create_resource(options) do |app|
begin
template=File.read(args[0])
app.allocate(template, options[:marketplace])
rescue => e
STDERR.puts e.messsage
exit(-1)
end
end
end
export_desc = <<-EOT.unindent
Exports the marketplace app to the OpenNebula cloud
EOT
command :export, export_desc, :appid, :name, :options=>EXPORT_OPTIONS do
helper.perform_action(args[0], options, "exported") do |obj|
rc = obj.export(:dsid=>options[:datastore], :name=>args[1])
next rc if OpenNebula.is_error?(rc)
rc.each { |key, value|
puts "#{key.to_s.upcase}"
value.each{ |id|
puts " ID: #{id}"
}
}
end
end
delete_desc = <<-EOT.unindent
Deletes the given marketplace app
EOT
command :delete, delete_desc, [:range, :appid_list] do
helper.perform_actions(args[0], options, "deleted") do |app|
app.delete
end
end
update_desc = <<-EOT.unindent
Update the template contents for the app. If a path is not provided the
editor will be launched to modify the current content.
EOT
command :update, update_desc, :appid, [:file, nil],
:options=>OpenNebulaHelper::APPEND do
helper.perform_action(args[0],options,"modified") do |obj|
if options[:append]
str = OpenNebulaHelper.append_template(args[0], obj, args[1])
else
str = OpenNebulaHelper.update_template(args[0], obj, args[1])
end
obj.update(str, options[:append])
end
end
chgrp_desc = <<-EOT.unindent
Changes the marketplace app group
EOT
command :chgrp, chgrp_desc,[:range, :appid_list], :groupid do
helper.perform_actions(args[0], options, "Group changed") do |app|
app.chown(-1, args[1].to_i)
end
end
chown_desc = <<-EOT.unindent
Changes the marketplace app owner and group
EOT
command :chown, chown_desc, [:range, :appid_list], :userid,
[:groupid, nil] do
gid = args[2].nil? ? -1 : args[2].to_i
helper.perform_actions(args[0], options, "Owner/Group changed") do |app|
app.chown(args[1].to_i, gid)
end
end
chmod_desc = <<-EOT.unindent
Changes the marketplace app permissions
EOT
command :chmod, chmod_desc, [:range, :appid_list], :octet do
helper.perform_actions(args[0], options, "Permissions changed") do |app|
app.chmod_octet(args[1])
end
end
rename_desc = <<-EOT.unindent
Renames the marketplace app
EOT
command :rename, rename_desc, :appid, :name do
helper.perform_action(args[0], options, "renamed") do |o|
o.rename(args[1])
end
end
list_desc = <<-EOT.unindent
Lists marketplace apps
EOT
command :list, list_desc, [:filterflag, nil], :options=>list_options do
helper.list_pool(options, false, args[0])
end
show_desc = <<-EOT.unindent
Shows information for the given marketplace app
EOT
command :show, show_desc, :appid, :options=>OpenNebulaHelper::XML do
helper.show_resource(args[0], options)
end
enable_desc = <<-EOT.unindent
Enables the marketplace app
EOT
command :enable, enable_desc, [:range, :appid_list] do
helper.perform_actions(args[0], options, "enabled") do |obj|
obj.enable
end
end
disable_desc = <<-EOT.unindent
Disables the marketplace app. A disabled marketplace app cannot be
exported to a cloud
EOT
command :disable, disable_desc, [:range, :appid_list] do
helper.perform_actions(args[0], options, "disabled") do |obj|
obj.disable
end
end
end

View File

@ -160,7 +160,7 @@ cmd=CommandParser::CmdParser.new(ARGV) do
end
delete_desc = <<-EOT.unindent
Deletes the given Image
Deletes the given Template
EOT
command :delete, delete_desc, [:range, :templateid_list] do
@ -208,17 +208,8 @@ cmd=CommandParser::CmdParser.new(ARGV) do
if args[1]
extra_template = File.read(args[1])
elsif options[:userdata]
if t.has_elements?('TEMPLATE/EC2')
t.add_element(
'TEMPLATE/EC2',
'USERDATA' => options[:userdata])
extra_template = t.template_like_str(
'TEMPLATE', false, 'EC2')
end
else
res = OpenNebulaHelper.create_template(options)
res = OpenNebulaHelper.create_template(options, t)
if res.first != 0
STDERR.puts res.last
@ -228,7 +219,7 @@ cmd=CommandParser::CmdParser.new(ARGV) do
extra_template = res.last
end
user_inputs = helper.get_user_inputs(t.to_hash) unless user_inputs
user_inputs = OneTemplateHelper.get_user_inputs(t.to_hash) unless user_inputs
extra_template << "\n" << user_inputs

View File

@ -40,7 +40,7 @@ cmd=CommandParser::CmdParser.new(ARGV) do
helper = OneUserHelper.new
before_proc do
helper.set_client(options) if @comm_name != :login
helper.set_client(options) if ![:login, :key].include?(@comm_name)
end
########################################################################
@ -351,8 +351,6 @@ cmd=CommandParser::CmdParser.new(ARGV) do
end
key_desc = <<-EOT.unindent
DEPRECATED, use login to generate auth files.
Shows a public key from a private SSH key. Use it as password
for the SSH authentication mechanism.
EOT

View File

@ -63,14 +63,6 @@ cmd=CommandParser::CmdParser.new(ARGV) do
:description => "Overrides the DEV_PREFIX of the image"
}
IP={
:name => "ip",
:short => "-i ip",
:large => "--ip ip",
:format => String,
:description => "IP address for the new NIC"
}
CACHE={
:name => "cache",
:large => "--cache cache_mode",
@ -669,7 +661,7 @@ cmd=CommandParser::CmdParser.new(ARGV) do
EOT
command :"nic-attach", nic_attach_desc, :vmid,
:options => [OneVMHelper::FILE, OneVMHelper::NETWORK, IP] do
:options => [OneVMHelper::FILE, OneVMHelper::NETWORK, OneVMHelper::IP] do
if options[:file].nil? and options[:network].nil?
STDERR.puts "Provide a template file or a network:"

305
src/cli/onevrouter Executable file
View File

@ -0,0 +1,305 @@
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
#--------------------------------------------------------------------------- #
ONE_LOCATION=ENV["ONE_LOCATION"]
if !ONE_LOCATION
RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end
$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cli"
require 'command_parser'
require 'one_helper/onevrouter_helper'
require 'one_helper/onetemplate_helper'
require 'one_helper/onevm_helper'
cmd=CommandParser::CmdParser.new(ARGV) do
usage "`onevrouter` <command> [<args>] [<options>]"
version OpenNebulaHelper::ONE_VERSION
helper = OneVirtualRouterHelper.new
before_proc do
helper.set_client(options)
end
########################################################################
# Global Options
########################################################################
set :option, CommandParser::OPTIONS+OpenNebulaHelper::CLIENT_OPTIONS
list_options = CLIHelper::OPTIONS
list_options << OpenNebulaHelper::XML
list_options << OpenNebulaHelper::NUMERIC
list_options << OpenNebulaHelper::DESCRIBE
########################################################################
# Formatters for arguments
########################################################################
set :format, :groupid, OpenNebulaHelper.rname_to_id_desc("GROUP") do |arg|
OpenNebulaHelper.rname_to_id(arg, "GROUP")
end
set :format, :userid, OpenNebulaHelper.rname_to_id_desc("USER") do |arg|
OpenNebulaHelper.rname_to_id(arg, "USER")
end
set :format, :vrouterid, OneVirtualRouterHelper.to_id_desc do |arg|
helper.to_id(arg)
end
set :format, :vrouterid_list, OneVirtualRouterHelper.list_to_id_desc do |arg|
helper.list_to_id(arg)
end
set :format, :filterflag, OneVirtualRouterHelper.filterflag_to_i_desc do |arg|
helper.filterflag_to_i(arg)
end
set :format, :templateid, OpenNebulaHelper.rname_to_id_desc("VMTEMPLATE") do |arg|
OpenNebulaHelper.rname_to_id(arg, "VMTEMPLATE")
end
########################################################################
# Commands
########################################################################
create_desc = <<-EOT.unindent
Creates a new Virtual Router from the given description
EOT
command :create, create_desc, :file do
helper.create_resource(options) do |obj|
begin
template = File.read(args[0])
obj.allocate(template)
rescue => e
STDERR.puts e.messsage
exit -1
end
end
end
instantiate_desc = <<-EOT.unindent
Creates a new VM instance from the given Template. This VM can be
managed with the 'onevm' command.
The NIC elements defined in the Virtual Router will be used. The
source Template can be modified adding or replacing attributes with
the optional file argument, or with the options.
EOT
instantiate_options = [
OneTemplateHelper::VM_NAME,
OneTemplateHelper::MULTIPLE,
OneVMHelper::HOLD
]
command :instantiate, instantiate_desc, :vrouterid, :templateid, [:file, nil],
:options=>instantiate_options+OpenNebulaHelper::TEMPLATE_OPTIONS do
exit_code=0
if args[1] && OpenNebulaHelper.create_template_options_used?(options)
STDERR.puts "You cannot use both template file and template"<<
" creation options."
next -1
end
number = options[:multiple] || 1
user_inputs = nil
helper.perform_action(args[0], options, "instantiated") do |vr|
name = options[:name] || ""
t = OpenNebula::Template.new_with_id(args[1], helper.client)
on_hold = options[:hold] != nil
extra_template = ""
rc = t.info
if OpenNebula.is_error?(rc)
STDERR.puts rc.message
exit(-1)
end
if args[2]
extra_template = File.read(args[2])
else
res = OpenNebulaHelper.create_template(options, t)
if res.first != 0
STDERR.puts res.last
next -1
end
extra_template = res.last
end
user_inputs = OneTemplateHelper.get_user_inputs(t.to_hash) unless user_inputs
extra_template << "\n" << user_inputs
vr.instantiate(number, args[1], name, on_hold, extra_template)
end
end
delete_desc = <<-EOT.unindent
Deletes the given Virtual Router
EOT
command :delete, delete_desc, [:range, :vrouterid_list] do
helper.perform_actions(args[0],options,"deleted") do |obj|
obj.delete
end
end
chgrp_desc = <<-EOT.unindent
Changes the Virtual Router group
EOT
command :chgrp, chgrp_desc,[:range, :vrouterid_list], :groupid do
helper.perform_actions(args[0],options,"Group changed") do |obj|
obj.chown(-1, args[1].to_i)
end
end
chown_desc = <<-EOT.unindent
Changes the Virtual Router owner and group
EOT
command :chown, chown_desc, [:range, :vrouterid_list], :userid,
[:groupid,nil] do
gid = args[2].nil? ? -1 : args[2].to_i
helper.perform_actions(args[0],options,"Owner/Group changed") do |obj|
obj.chown(args[1].to_i, gid)
end
end
chmod_desc = <<-EOT.unindent
Changes the Virtual Router permissions
EOT
command :chmod, chmod_desc, [:range, :vrouterid_list], :octet do
helper.perform_actions(args[0],options, "Permissions changed") do |obj|
obj.chmod_octet(args[1])
end
end
update_desc = <<-EOT.unindent
Update the Virtual Router contents. If a path is not provided the editor
will be launched to modify the current content.
EOT
command :update, update_desc, :vrouterid, [:file, nil],
:options=>OpenNebulaHelper::APPEND do
helper.perform_action(args[0],options,"modified") do |obj|
if options[:append]
str = OpenNebulaHelper.append_template(args[0], obj, args[1])
else
str = OpenNebulaHelper.update_template(args[0], obj, args[1])
end
obj.update(str, options[:append])
end
end
rename_desc = <<-EOT.unindent
Renames the Virtual Router
EOT
command :rename, rename_desc, :vrouterid, :name do
helper.perform_action(args[0],options,"renamed") do |obj|
obj.rename(args[1])
end
end
nic_attach_desc = <<-EOT.unindent
Attaches a NIC to a VirtualRouter, and each one of its VMs. When using
--file add only one NIC instance.
EOT
command :"nic-attach", nic_attach_desc, :vrouterid,
:options => [OneVMHelper::FILE, OneVMHelper::NETWORK, OneVMHelper::IP] do
if options[:file].nil? and options[:network].nil?
STDERR.puts "Provide a template file or a network:"
STDERR.puts "\t--file <file>"
STDERR.puts "\t--network <network>"
exit -1
end
if options[:file]
template = File.read(options[:file])
else
network_id = options[:network]
ip = options[:ip]
if ip
template = "NIC = [ NETWORK_ID = #{network_id}, IP = #{ip} ]"
else
template = "NIC = [ NETWORK_ID = #{network_id} ]"
end
end
helper.perform_action(args[0],options,"Attach NIC") do |vr|
vr.nic_attach(template)
end
end
nic_detach_desc = <<-EOT.unindent
Detaches a NIC from a VirtualRouter, and each one of its VMs
EOT
command :"nic-detach", nic_detach_desc, :vrouterid, :nicid do
nicid = args[1].to_i
helper.perform_action(args[0],options,"Detach NIC") do |vr|
vr.nic_detach(nicid)
end
end
list_desc = <<-EOT.unindent
Lists the Virtual Routers in the pool
EOT
command :list, list_desc, [:filterflag, nil], :options=>list_options do
helper.list_pool(options, false, args[0])
end
show_desc = <<-EOT.unindent
Shows information for the given Virtual Router
EOT
command :show, show_desc, :vrouterid,
:options=>[OpenNebulaHelper::XML, OneVMHelper::ALL_TEMPLATE] do
helper.show_resource(args[0],options)
end
top_desc = <<-EOT.unindent
Lists Virtual Routers continuously
EOT
command :top, top_desc, [:filterflag, nil], :options=>list_options do
helper.list_pool(options, true, args[0])
end
end

View File

@ -1,183 +0,0 @@
#!/usr/bin/env ruby
# ---------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may #
# not use this file except in compliance with the License. You may obtain #
# a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# ---------------------------------------------------------------------------- #
ONE_LOCATION=ENV["ONE_LOCATION"]
if !ONE_LOCATION
RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
TEMPLATES_LOCATION=ONE_LOCATION+"/etc/occi_templates"
CONF_LOCATION=ONE_LOCATION+"/etc"
end
$: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
require 'marketplace/marketplace_client'
require 'cli/command_parser'
require 'cli/cli_helper'
require 'rubygems'
require 'json'
USER_AGENT = "CLI"
#
# Options
#
DEFAULT_OPTIONS = [
ENDPOINT = {
:name => "server",
:short => "-s url",
:large => "--server url",
:format => String,
:description => "Marketplace endpoint"
},
USERNAME={
:name => "username",
:short => "-u name",
:large => "--username name",
:format => String,
:description => "User name"
},
PASSWORD={
:name => "password",
:short => "-p pass",
:large => "--password pass",
:format => String,
:description => "User password"
}
]
JSON_FORMAT={
:name => "json",
:short => "-j",
:large => "--json",
:description => "Show in JSON format"
}
#
# Table
#
TABLE = CLIHelper::ShowTable.new(nil, self) do
column :ID, "Appliance", :size=>25 do |d|
d["_id"]["$oid"]
end
column :NAME, "Name", :size=>50 do |d|
d["name"]
end
column :PUBLISHER, "Publisher", :size=>15 do |d|
d["publisher"]
end
default :ID, :NAME, :PUBLISHER
end
#
# Commands
#
cmd=CommandParser::CmdParser.new(ARGV) do
usage "`onemarket` <command> [<args>] [<options>]"
set :option, DEFAULT_OPTIONS
#
# List
#
list_desc = <<-EOT.unindent
List the available appliances in the Marketplace
EOT
command :list, list_desc, :options => JSON_FORMAT do
client = Market::ApplianceClient.new(
options[:username],
options[:password],
options[:server],
USER_AGENT)
response = client.list
if CloudClient::is_error?(response)
[response.code.to_i, response.to_s]
else
if options[:json]
[0,response.body]
else
array_list = JSON.parse(response.body)
TABLE.show(array_list['appliances'])
0
end
end
end
#
# Create
#
create_desc = <<-EOT.unindent
Create a new appliance in the Marketplace
EOT
command :create, create_desc, :file do
client = Market::ApplianceClient.new(
options[:username],
options[:password],
options[:server],
USER_AGENT)
response = client.create(File.read(args[0]))
if CloudClient::is_error?(response)
[response.code.to_i, response.to_s]
else
[0, response.body]
end
end
#
# Show
#
show_desc = <<-EOT.unindent
Show detailed information of a given appliance
EOT
command :show, show_desc, :id, :options => JSON_FORMAT do
client = Market::ApplianceClient.new(
options[:username],
options[:password],
options[:server],
USER_AGENT)
response = client.show(args[0])
if CloudClient::is_error?(response)
[response.code.to_i, response.to_s]
else
[0,response.body]
end
end
end

View File

@ -1,90 +0,0 @@
# ---------------------------------------------------------------------------- #
# Copyright 2002-2015, OpenNebula Project, OpenNebula Systems #
# #
# 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 'uri'
require 'cloud/CloudClient'
require 'ostruct'
module Market
class Client
def initialize(username, password, url, user_agent="Ruby")
@username = username
@password = password
url ||= 'http://marketplace.opennebula.systems/'
@uri = URI.parse(url)
@user_agent = "OpenNebula #{CloudClient::VERSION} (#{user_agent})"
@host = nil
@port = nil
if ENV['http_proxy']
uri_proxy = URI.parse(ENV['http_proxy'])
@host = uri_proxy.host
@port = uri_proxy.port
end
end
def get(path)
req = Net::HTTP::Proxy(@host, @port)::Get.new(@uri.path + path)
do_request(req)
end
def post(path, body)
req = Net::HTTP::Proxy(@host, @port)::Post.new(@uri.path + path)
req.body = body
do_request(req)
end
private
def do_request(req)
if @username && @password
req.basic_auth @username, @password
end
req['User-Agent'] = @user_agent
res = CloudClient::http_start(@uri, @timeout) do |http|
http.request(req)
end
res
end
end
class ApplianceClient < Client
def initialize(user, password, url, agent)
super(user, password, url, agent)
end
def list
get("/appliance")
end
def create(body)
post("/appliance", body)
end
def show(id)
get("/appliance/#{id}")
end
end
end

View File

@ -307,188 +307,3 @@ int VectorAttribute::vector_value(const char *name, bool& value) const
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VectorAttribute::vector_value(const char *name, int & value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
return -1;
}
if ( it->second.empty() )
{
return -1;
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VectorAttribute::vector_value(const char *name, unsigned int & value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
return -1;
}
if ( it->second.empty() )
{
return -1;
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VectorAttribute::vector_value(const char *name, long long& value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
return -1;
}
if ( it->second.empty() )
{
return -1;
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int VectorAttribute::vector_value(const char *name, float & value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
return -1;
}
if ( it->second.empty() )
{
return -1;
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string VectorAttribute::vector_value_str(const char *name, int& value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
value = -1;
return "";
}
if ( it->second.empty() )
{
value = -1;
return "";
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
value = -1;
return "";
}
return it->second;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string VectorAttribute::vector_value_str(const char *name, float& value) const
{
map<string,string>::const_iterator it;
it = attribute_value.find(name);
if ( it == attribute_value.end() )
{
value = -1;
return "";
}
if ( it->second.empty() )
{
value = -1;
return "";
}
istringstream iss(it->second);
iss >> value;
if (iss.fail() || !iss.eof())
{
value = -1;
return "";
}
return it->second;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -25,6 +25,7 @@
#include <string>
#include <sstream>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <math.h>
@ -306,3 +307,29 @@ std::string one_util::trim(const std::string& str)
return tstr;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
std::string one_util::gsub(const std::string& st, const std::string& sfind,
const std::string& srepl)
{
std::string result = st;
std::string::size_type pos = 0;
size_t srepl_len = srepl.length();
size_t sfind_len = sfind.length();
pos = result.find(sfind, pos);
while(pos != std::string::npos)
{
result.replace(pos, sfind_len , srepl);
pos += srepl_len;
pos = result.find(sfind, pos);
}
return result;
}

View File

@ -711,9 +711,9 @@ int Datastore::from_xml(const string& xml)
rc += xpath(cluster_id, "/DATASTORE/CLUSTER_ID", -1);
rc += xpath(cluster, "/DATASTORE/CLUSTER", "not_found");
rc += xpath(total_mb, "/DATASTORE/TOTAL_MB", 0);
rc += xpath(free_mb, "/DATASTORE/FREE_MB", 0);
rc += xpath(used_mb, "/DATASTORE/USED_MB", 0);
rc += xpath<long long>(total_mb,"/DATASTORE/TOTAL_MB",0);
rc += xpath<long long>(free_mb, "/DATASTORE/FREE_MB", 0);
rc += xpath<long long>(used_mb, "/DATASTORE/USED_MB", 0);
// Permissions
rc += perms_from_xml();

View File

@ -40,20 +40,18 @@ const int DatastorePool::FILE_DS_ID = 2;
DatastorePool::DatastorePool(
SqlDB * db,
const vector<const Attribute *>& _inherit_attrs) :
const vector<const SingleAttribute *>& _inherit_attrs) :
PoolSQL(db, Datastore::table, true, true)
{
ostringstream oss;
string error_str;
vector<const Attribute *>::const_iterator it;
vector<const SingleAttribute *>::const_iterator it;
for (it = _inherit_attrs.begin(); it != _inherit_attrs.end(); it++)
{
const SingleAttribute* sattr = static_cast<const SingleAttribute *>(*it);
inherit_attrs.push_back(sattr->value());
inherit_attrs.push_back((*it)->value());
}
if (get_lastOID() == -1) //lastOID is set in PoolSQL::init_cb

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