Merge remote-tracking branch 'origin/feature-2858'

This commit is contained in:
Javi Fontan committed 2014-06-23 11:55:28 +02:00
commit e6a157c25d
66 files changed
+6505 -4063

No files matched your search

+501
View File
@@ -0,0 +1,501 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 ADDRESS_RANGE_H_
#define ADDRESS_RANGE_H_
#include <string>
#include <set>
#include <vector>
#include "PoolObjectSQL.h"
#include "AddressRangePool.h"
using namespace std;
class VectorAttribute;
/**
* The Lease class represents an address lease from a Virtual Network.
*/
class AddressRange
{
public:
AddressRange(unsigned int _id):id(_id),next(0),used_addr(0){};
virtual ~AddressRange(){};
// *************************************************************************
// Address Range types
// *************************************************************************
/**
* Type of Addresses defined by this address range
*/
enum AddressType
{
NONE = 0x00000000, /** Undefined Address Type */
ETHER = 0x00000001, /** MAC address type */
IP4 = 0x00000003, /** IP version 4 address */
IP6 = 0x00000005, /** IP version 6 address */
IP4_6 = 0x00000007 /** IP dual stack version 4 & 6 addresses */
};
/**
* Return the string representation of an AddressType
* @param ob the type
* @return the string
*/
static string type_to_str(AddressType ob);
/**
* Return the string representation of an AddressType
* @param ob the type
* @return the string
*/
static AddressType str_to_type(string& str_type);
// *************************************************************************
// Address Range initialization functions
// *************************************************************************
/**
* Init an Address Range based on a vector attribute the following
* attributes will be parsed (* are optional):
* - TYPE = ETHER | IP4 | IP6 | IP4_6
* - SIZE
* - MAC
* - IP
* - ULA_PREFIX
* - GLOBAL_PREFIX
*
* The following can be defined to override VNET values:
* - BRIDGE
* - VLAN
* - VLAN_ID
* - PHYDEV
*
* Any value defined in the INHERIT_VNET_ATTR can be defined as well.
*
* Any value for context can be included in the AR.
*
* Example:
* - AR = [ TYPE = "ETHER", SIZE = 128, MAC = "00:02:01:02:03:04"]
* - AR = [ TYPE = "ETHER", SIZE = 128]
* - AR = [ TYPE = IP4,
* SIZE = 256,
* IP = 10.0.0.0,
* DNS = 10.0.0.5]
* - AR = [ TYPE = "IP6",
* SIZE = 1024,
* ULA_PREFIX = "fd00:0:0:1::",
* GLOBAL_PREFIX = "2001::"]
*/
int from_vattr(VectorAttribute * attr, string& error_msg);
/**
* Builds an Address Range from a vector attribute stored in the DB
* @param vattr the VectorAttribute stored in a ADDRESS_RANGE template
*/
int from_vattr_db(VectorAttribute *vattr);
/**
* Builds an extended XML representation of the AR to send it back to
* clients
*/
void to_xml(ostringstream &oss) const;
// *************************************************************************
// Address allocation functions
// *************************************************************************
/**
* Returns an unused address, which becomes used and fills a NIC attribute
* with the configuration parameters from the address range.
* @param ot the type of the object allocating the address
* @param obid the id of the object
* @param nic the VM NIC attribute
* @param inherit attributes to be added to the NIC attribute
* @return 0 if success
*/
int allocate_addr(PoolObjectSQL::ObjectType ot, int obid,
VectorAttribute * nic, const vector<string> &inherit);
/**
* Returns the specific address by mac if is not allocated. The NIC attr
* is filled with the configuration parameters from the address range.
* @param mac the mac address
* @param ot the type of the object allocating the address
* @param obid the id of the object
* @param nic the VM NIC attribute
* @param inherit attributes to be added to the NIC attribute
* @return 0 if success
*/
int allocate_by_mac(const string& mac, PoolObjectSQL::ObjectType ot,
int obid, VectorAttribute * nic, const vector<string> &inherit);
/**
* Returns the specific address by ip if is not allocated. The NIC attr
* is filled with the configuration parameters from the address range.
* @param ot the type of the object allocating the address
* @param obid the id of the object
* @param nic the VM NIC attribute
* @param inherit attributes to be added to the NIC attribute
* @return 0 if success
*/
int allocate_by_ip(const string& ip, PoolObjectSQL::ObjectType ot,
int obid, VectorAttribute * nic, const vector<string> &inherit);
/**
* Sets the given ip on hold, the address is associated to a VM of id -1.
* @param ip the ip to hold
*/
int hold_by_ip(const string& ip);
/**
* Sets the given mac on hold, the address is associated to a VM of id -1.
* @param mac the mac to hold
*/
int hold_by_mac(const string& mac);
/**
* Frees a previous allocated address, referenced by its MAC address
* @param ot the object type of the owner of the address
* @param obid the id of the owner of the address
* @param mac the MAC address in string form
* @return 0 if the address was freed
*/
int free_addr(PoolObjectSQL::ObjectType ot, int obid, const string& mac);
/**
* Frees a previous allocated address, referenced by its IP address
* @param ot the object type of the owner of the address
* @param obid the id of the owner of the address
* @param ip the IP address in string form
* @return 0 if the address was freed
*/
int free_addr_by_ip(PoolObjectSQL::ObjectType ot, int id, const string& ip);
/**
* Frees all previous allocated address to the given object
* @param ot the object type of the owner of the address
* @param obid the id of the owner of the address
* @return the number of addresses freed
*/
int free_addr_by_owner(PoolObjectSQL::ObjectType ot, int obid);
/**
* Frees a previous allocated address range, referenced by its MAC address
* and size
* @param ot the object type of the owner of the address
* @param obid the id of the owner of the address
* @param mac the first MAC address in string form
* @param rsize the size of the range
* @return the number of addresses freed
*/
int free_addr_by_range(PoolObjectSQL::ObjectType ot, int obid,
const string& mac, unsigned int rsize);
// *************************************************************************
// Address Reservation
// *************************************************************************
/**
* Reserve a given number of addresses from this address range
* @param vid the id of the VNET making the reservation
* @param size number of addresses to reserve
* @param rar a new address range to place the reservation
* @return 0 on success
*/
int reserve_addr(int vid, unsigned int rsize, AddressRange *rar);
/**
* Reserve a given number of addresses from this address range
* @param vid the id of the VNET making the reservation
* @param size number of addresses to reserve
* @param rar a new address range to place the reservation
* @param ip the firs ip in the Reservation
* @return 0 on success
*/
int reserve_addr_by_ip(int vid, unsigned int rsize, const string& ip,
AddressRange *rar);
/**
* Reserve a given number of addresses from this address range
* @param vid the id of the VNET making the reservation
* @param size number of addresses to reserve
* @param rar a new address range to place the reservation
* @param mac the firs mac in the Reservation
* @return 0 on success
*/
int reserve_addr_by_mac(int vid, unsigned int rsize, const string& mac,
AddressRange *rar);
// *************************************************************************
// Helpers
// *************************************************************************
/**
* Return the id for this address range
*/
unsigned int ar_id() const
{
return id;
}
/**
* Return the number of used addresses
*/
unsigned int get_used_addr() const
{
return used_addr;
}
/**
* Return the number of free addresses
*/
unsigned int get_free_addr() const
{
return size - used_addr;
}
/**
* Return the total number of addresses
*/
unsigned int get_size() const
{
return size;
}
/**
* Returns the string value of an Address Range Attribute
* @param name of the attribute
* @return the value of the attribute if found, empty otherwise
*/
string get_attribute(const char *name) const
{
return attr->vector_value(name);
}
/**
* Returns the int value of an Address Range Attribute
* @param name of the attribute
* @param value of the attribute
* @return 0 on success
*/
int get_attribute(const char *name, int& value) const
{
return attr->vector_value(name, value);
}
/**
* Updates the Address Range with the attributes provided. The following
* CANNOT be updated: TYPE, SIZE, IP, MAC (plus the internal AR_ID and
* ALLOCATED)
* @param vup the new vector attributes for the address range
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int update_attributes(VectorAttribute *vup, string& error_msg);
/*
* add_ar from AddressRangePool needs to access the internal representation
* of the AR to include it in the ARPool template.
*/
friend int AddressRangePool::add_ar(AddressRange * ar);
private:
/* ---------------------------------------------------------------------- */
/* String to binary conversion functions for different address types */
/* ---------------------------------------------------------------------- */
/**
* MAC to binary (48 bits)
* @param mac in string form 00:02:01:02:03:04
* @return 0 on success
*/
int mac_to_i(string mac, unsigned int i_mac[]) const;
/**
* IP version 4 to binary (32 bits)
* @param ip in string form 192.168.0.2
* @return 0 on success
*/
int ip_to_i(const string& _ip, unsigned int& i_ip) const;
/**
* IPv6 64bits prefix conversion
* @param prefix in string form 2a00:1bc0:b001:A::
* @return 0 on success
*/
int prefix6_to_i(const string& prefix, unsigned int ip[]) const;
/* ---------------------------------------------------------------------- */
/* NIC setup functions */
/* ---------------------------------------------------------------------- */
/**
* Writes MAC address to the given NIC attribute
* @param addr_index internal index for the lease
* @param nic attribute of a VMTemplate
*/
void set_mac(unsigned int addr_index, VectorAttribute * nic) const;
/**
* Writes IP address to the given NIC attribute
* @param addr_index internal index for the lease
* @param nic attribute of a VMTemplate
*/
void set_ip(unsigned int addr_index, VectorAttribute * nic) const;
/**
* Writes IPv6 address to the given NIC attribute
* @param addr_index internal index for the lease
* @param nic attribute of a VMTemplate
*/
void set_ip6(unsigned int addr_index, VectorAttribute * nic) const;
/**
* Writes VNET configuration attributes to the given NIC attribute. It
* includes: BRIDGE, VLAN, VLAN_ID, PHYDEV and INHERIT_VNET_ATTR in oned.conf
* @param addr_index internal index for the lease
* @param nic attribute of a VMTemplate
*/
void set_vnet(VectorAttribute *nic, const vector<string> &inherit) const;
/* ---------------------------------------------------------------------- */
/* Address index map helper functions */
/* ---------------------------------------------------------------------- */
/**
* This function generates a string representation of the in-memory allocated
* addresses. It'll be stored along side the AR vector attribute in the
* ADDRESS_RANGE template.
*/
void allocated_to_attr();
/**
* Generates a memory map for the addresses.
* @param allocated_s the string representation of the allocated addresses
* generated by allocated_to_attr()
* @return 0 on success
*/
int attr_to_allocated(const string& allocated_s);
/**
* Adds a new allocated address to the map. Updates the ALLOCATED attribute
*/
void allocate_addr(PoolObjectSQL::ObjectType ot, int obid,
unsigned int addr_index);
/**
* Frees an address from the map. Updates the ALLOCATED attribute
*/
int free_addr(PoolObjectSQL::ObjectType ot, int obid,
unsigned int addr_index);
/**
* Reserve a set of addresses from an starting one
* @param vid the id of the VNET making the reservation
* @param rsize number of addresses to reserve
* @param sindex the first index to start the reservation
* @param rar a new address range to place the reservation
* @return 0 on success
*/
int reserve_addr_by_index(int vid, unsigned int rsize, unsigned int sindex,
AddressRange *rar);
/* ---------------------------------------------------------------------- */
/* Restricted Attributes functions */
/* ---------------------------------------------------------------------- */
bool check(string& rs_attr) const;
static void set_restricted_attributes(vector<const Attribute *>& rattrs);
/* ---------------------------------------------------------------------- */
/* Address Range data */
/* ---------------------------------------------------------------------- */
/**
* The type of addresses defined in the range
*/
AddressType type;
/**
* ID for this range, unique within the Virtual Network
*/
unsigned int id;
/**
* Number of addresses in the range
*/
unsigned int size;
/**
* First IP4 in the range
*/
unsigned int ip;
/**
* First MAC in the range
*/
unsigned int mac[2];
/**
* Binary representation of the IPv6 address global unicast prefix
*/
unsigned int global6[2];
/**
* Binary representation of the IPv6 address site unicast prefix
*/
unsigned int ula6[2];
/**
* The Address Range attributes as a Template VectorAttribute. This is
* used to generate XML or a template representation of the AR.
*/
VectorAttribute * attr;
/* ---------------------------------------------------------------------- */
/* Allocated address & control */
/* ---------------------------------------------------------------------- */
/**
* Map to store the allocated address indexed by the address index relative
* to the mac/ip values. It contains also the type and id of the object
* owning the address ObjectType(32bits) | Object ID (32)
*/
map<unsigned int, long long> allocated;
unsigned int next;
unsigned int used_addr;
/* ---------------------------------------------------------------------- */
/* Restricted Attributes */
/* ---------------------------------------------------------------------- */
/**
* TRUE if restricted attributes have been defined for Address Ranges
*/
static bool restricted_set;
/**
* The restricted attributes from oned.conf
*/
static set<string> restricted_attributes;
};
#endif
+346
View File
@@ -0,0 +1,346 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 ADDRESS_RANGE_POOL_H_
#define ADDRESS_RANGE_POOL_H_
#include <string>
#include <vector>
#include <map>
#include <libxml/parser.h>
#include "Template.h"
#include "PoolObjectSQL.h"
class VectorAttribute;
class AddressRange;
using namespace std;
class AddressRangePool
{
public:
AddressRangePool();
virtual ~AddressRangePool();
// *************************************************************************
// Inititalization functions
// *************************************************************************
/**
* Builds the address range from a VectorAttribute. This function is used
* to create address ranges.
* @param ars the vector of address ranges
* @param error_msg describing the error
* @return 0 on success
*/
int from_vattr(VectorAttribute * ar, string& error_msg);
/**
* Builds the address range set from its XML representation. This function
* is used to rebuild the address ranges from the DB.
* @param node xmlNode for the template
* @return 0 on success
*/
int from_xml_node(const xmlNodePtr node);
// *************************************************************************
// Address Range management interface
// *************************************************************************
/**
* Removes an address range from the pool if it does not contain any used
* leases
* @param arid of the address range to be removed
* @return 0 on success, -1 if not exists or has used addresses
*/
int rm_ar(unsigned int ar_id, string& error_msg);
/**
* Updates the given address ranges
* @param ars vector of address ranges as VectorAttributes obtained from
* template in the form AR = [...]. Only one AR is processed.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int update_ar(vector<Attribute *> ars, string& error_msg);
/**
* Allocates a new *empty* address range. It is not added to the pool as it
* needs to be initialized. Only the AR_ID is set.
* @return the new address range.
*/
AddressRange * allocate_ar();
/**
* Adds a new address range to the pool. It should be allocated by the
* allocate_ar() function.
* @param ar the new address range;
* @return 0 on success
*/
int add_ar(AddressRange * ar);
// *************************************************************************
// Address allocation interface
// *************************************************************************
/**
* Allocates an address in a suitable address range from the pool
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param nic the NIC attribute to be filled with lease attributes
* @param inherit attributes to be added to the NIC
* @return 0 if success
*/
int allocate_addr(PoolObjectSQL::ObjectType ot, int obid,
VectorAttribute * nic, const vector<string> &inherit);
/**
* Allocates an address in a suitable address range from the pool by mac
* @param mac the specific MAC address requested
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param nic the NIC attribute to be filled with lease attributes
* @param inherit attributes to be added to the NIC
* @return 0 if success
*/
int allocate_by_mac(const string &mac, PoolObjectSQL::ObjectType ot, int obid,
VectorAttribute * nic, const vector<string> &inherit);
/**
* Allocates an address in a suitable address range from the pool by mac
* @param ip the specific IP address requested
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param nic the NIC attribute to be filled with lease attributes
* @param inherit attributes to be added to the NIC
* @return 0 if success
*/
int allocate_by_ip(const string &ip, PoolObjectSQL::ObjectType ot, int obid,
VectorAttribute * nic, const vector<string> &inherit);
/**
* Holds an address from the specified address range.
* @param arid of the address range
* @param ip the ip to hold
* @return 0 on success
*/
int hold_by_ip(unsigned int arid, const string& ip);
/**
* Holds an address from the first address range containing the MAC
* @param mac the mac to hold
* @return 0 on success
*/
int hold_by_ip(const string& ip);
/**
* Holds an address from the specified address range.
* @param arid of the address range
* @param mac the mac to hold
* @return 0 on success
*/
int hold_by_mac(unsigned int arid, const string& mac);
/**
* Holds an address from the first address range containing the MAC
* @param mac the mac to hold
* @return 0 on success
*/
int hold_by_mac(const string& mac);
/**
* Frees the given address by MAC on the given address range
* @param arid the ID of the address range
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param mac the specific MAC address requested
*/
void free_addr(unsigned int arid, PoolObjectSQL::ObjectType ot, int obid,
const string& mac);
/**
* Frees the given address by IP on the given address range
* @param arid the ID of the address range
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param ip the specific IP address requested
*/
void free_addr_by_ip(unsigned int arid, PoolObjectSQL::ObjectType ot,
int obid, const string& ip);
/**
* Frees the given address by MAC from all address ranges containing
* the MAC
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param mac the specific MAC address requested
*/
void free_addr(PoolObjectSQL::ObjectType ot, int obid, const string& mac);
/**
* Frees the given address by IP from all address ranges containing
* the IP
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param ip the specific IP address requested
*/
void free_addr_by_ip(PoolObjectSQL::ObjectType ot, int id, const string& ip);
/**
* Frees all the addressed owned by the given object
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @return the number of addresses freed
*/
int free_addr_by_owner(PoolObjectSQL::ObjectType ot, int obid);
/**
* Frees the given address range
* @param arid the ID of the address range
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @param mac the first MAC address in the range
* @param rsize size of the address range
*/
int free_addr_by_range(unsigned int arid, PoolObjectSQL::ObjectType ot,
int obid, const string& mac, unsigned int rsize);
// *************************************************************************
// Address reservation
// *************************************************************************
/**
* Reserve a given number of addresses from the first address range with
* enough free addresses to allocate the reservation
* @param vid the id of the VNET making the reservation
* @param size number of addresses to reserve
* @param rar a new address range to place the reservation
* @return 0 on success
*/
int reserve_addr(int vid, unsigned int rsize, AddressRange *rar);
/**
* Reserve a given number of addresses from the given address range
* @param vid the id of the VNET making the reservation
* @param rsize number of addresses to reserve
* @param ar_id the address range to reserve the addresses from
* @param rar a new address range to place the reservation
* @return 0 on success
*/
int reserve_addr(int vid, unsigned int rsize, unsigned int ar_id,
AddressRange *rar);
/**
* Reserve a number of addresses from an address range from a given ip
* @param vid the id of the VNET making the reservation
* @param rsize number of addresses to reserve
* @param ar_id the address range to reserve the addresses from
* @param ip the first IP in the reservation
* @param rar a new address range to place the reservation
* @return 0 on success
*/
int reserve_addr_by_ip(int vid, unsigned int rsize, unsigned int ar_id,
const string& ip, AddressRange *rar);
/**
* Reserve a number of addresses from an address range from a given ip
* @param vid the id of the VNET making the reservation
* @param rsize number of addresses to reserve
* @param ar_id the address range to reserve the addresses from
* @param mac the first IP in the reservation
* @param rar a new address range to place the reservation
* @return 0 on success
*/
int reserve_addr_by_mac(int vid, unsigned int rsize, unsigned int ar_id,
const string& mac, AddressRange *rar);
// *************************************************************************
// Helpers & Formatting
// *************************************************************************
/**
* Return the number of used addresses
*/
unsigned int get_used_addr() const
{
return used_addr;
}
/**
* Return the total number addresses
*/
unsigned int get_size() const;
/**
* Return the parent id of an address range
* @param ar_id of the address range
* @return the parent ar id, -1 if none
*/
int get_ar_parent(int ar_id) const;
/**
* Gets an attribute from the Address Range
* @param name of the attribute
* @param value of the attribute
* @param ar_id to get the attribute from
*/
void get_attribute(const char * name, string& value, int ar_id) const;
/**
* Gets an attribute from the Address Range, int version
* @param name of the attribute
* @param value of the attribute
* @param ar_id to get the attribute from
* @return 0 on success
*/
int get_attribute(const char * name, int& value, int ar_id) const;
/**
* Generate a XML representation of the Address Range Pool
* @param sstream where the ARPool is written
* @param extended true to include lease information
* @return the string with the XML
*/
string& to_xml(string& sstream, bool extended) const;
private:
/**
* Stores the Address Ranges in a template form. This template is used
* to store the pool in the DB
*/
Template ar_template;
/**
* ID for the next Address Range
*/
unsigned int next_ar;
/**
* Map to access each range
*/
map<unsigned int, AddressRange *> ar_pool;
/**
* Used addresses
*/
unsigned int used_addr;
};
#endif
+35
View File
@@ -265,6 +265,16 @@ public:
*/
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
*
@@ -329,6 +339,11 @@ public:
*/
string * to_xml() const;
/**
* Same as above but the attribute is written in an string stream;
*/
void to_xml(ostringstream &oss) const;
/**
* Builds a new attribute from a string of the form:
* "VAL_NAME_1=VAL_VALUE_1,...,VAL_NAME_N=VAL_VALUE_N".
@@ -357,6 +372,18 @@ 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
*/
@@ -420,6 +447,14 @@ public:
return new VectorAttribute(*this);
};
/**
* Clear the vector attribute values
*/
void clear()
{
attribute_value.clear();
}
private:
static const char * magic_sep;
+1 -1
View File
@@ -265,7 +265,7 @@ private:
int cluster_id,
const string& cluster_name);
virtual ~Datastore(){};
virtual ~Datastore();
// *************************************************************************
// DataBase implementation (Private)
-159
View File
@@ -1,159 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 FIXED_LEASES_H_
#define FIXED_LEASES_H_
#include "Leases.h"
using namespace std;
/**
* The FixedLeases class represents a pool of fixed IP-MAC leases. A lease can
* be either a IP (the MAC is then PREFIX:IP) or the IP and MAC addresses. The
* pool is read from a template file, each lease is in the form:
* LEASE = [ IP = "<the ip>", MAC = "<the mac>"]
*/
class FixedLeases : public Leases
{
public:
/**
* Create a FixedLeases from template
*/
FixedLeases(SqlDB * db,
int _oid,
unsigned int _mac_prefix,
unsigned int _global[],
unsigned int _site[],
vector<const Attribute*>& vector_leases);
/**
* Create a plain FixedLeases, you can populate the lease pool using
* select()
*/
FixedLeases(SqlDB * db,
int _oid,
unsigned int _mac_prefix,
unsigned int _global[],
unsigned int _site[]):
Leases(db,_oid,0,_mac_prefix,_global,_site),
current(leases.begin()){};
~FixedLeases(){};
/**
* Returns an unused lease, which becomes used
* @param vid identifier of the VM getting this lease
* @param ip ip of the returned lease
* @param mac mac of the returned lease
* @return 0 if success
*/
int get(int vid, string& ip, string& mac, unsigned int eui64[]);
/**
* Ask for a specific lease in the network
* @param vid identifier of the VM getting this lease
* @param ip ip of lease requested
* @param mac mac of the lease
* @return 0 if success
*/
int set(int vid, const string& ip, string& mac, unsigned int eui64[]);
/**
* Release an used lease, which becomes unused
* @param ip of the lease in use
*/
void release(const string& ip)
{
unset(ip);
}
/**
* Adds New leases.
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int add_leases(vector<const Attribute*>& leases, string& error_msg);
/**
* Removes leases; if they are not used.
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int remove_leases(vector<const Attribute*>& leases, string& error_msg);
/**
* Loads the leases from the DB.
*/
int select(SqlDB * db)
{
//Read the leases from the DB
int rc = Leases::select(db);
//Update the size
size = leases.size();
return rc;
}
private:
/**
* Current lease pointer
*/
map<unsigned int, Lease *>::iterator current;
/**
* Add a lease, from the Lease interface
* @param ip ip of the lease
* @param mac mac of the lease
* @param vid identifier of the VM getting this lease
* @param error_msg If the action fails, this message contains the reason.
* @param used Flag to insert the lease as used.
* @return 0 if success
*/
int add(const string& ip,
const string& mac,
int vid,
string& error_msg,
bool used=true);
/**
* Remove an existing lease, if it is not in use.
* @param ip ip of the lease
* @param error_msg If the action fails, this message contains the reason
*/
int remove(const string& ip, string& error_msg);
/**
* Sets a lease as not used, from the Lease interface
* @param ip ip of the lease to be deleted
* @return 0 if success
*/
int unset(const string& ip);
/**
* Updates the DB entry for this lease
* @param lease Lease to be updated
* @return 0 if success
*/
int update_lease(Lease * lease);
};
#endif /*FIXED_LEASES_H_*/
-382
View File
@@ -1,382 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 LEASES_H_
#define LEASES_H_
#include "ObjectSQL.h"
#include "ObjectXML.h"
#include "Attribute.h"
#include <map>
#include <vector>
#include <sstream>
using namespace std;
/**
* The Leases class represents all the IP and MAC addresses (lease) that can
* be asigned (or are asigned) in a Virtual Network
*/
class Leases : public ObjectSQL
{
public:
/**
* Creates a new Lease set for a given Virtual Network (oid)
* @param _db pinter to the DB object used to store the leases
* @param _oid the virtual network unique identifier
* @param _size the max number of leases
*/
Leases(SqlDB * _db, int _oid, unsigned long _size, unsigned int _mac_prefix,
unsigned int _global[], unsigned int _site[]):
ObjectSQL(), oid(_oid), size(_size), n_used(0), mac_prefix(_mac_prefix)
, db(_db)
{
global[1] = _global[1];
global[0] = _global[0];
site[1] = _site[1];
site[0] = _site[0];
};
virtual ~Leases()
{
map<unsigned int, Lease *>::iterator it;
for(it=leases.begin();it!=leases.end();it++)
{
delete it->second;
}
};
friend ostream& operator<<(ostream& os, Leases& _leases);
/**
* Returns an unused lease, which becomes used
* @param vid identifier of the VM getting this lease
* @param ip ip of the returned lease
* @param mac mac of the returned lease
* @param eui64 extended unique identifier
* @return 0 if success
*/
virtual int get(int vid, string& ip, string& mac, unsigned int *eui64) = 0;
/**
* Ask for a specific lease in the network
* @param vid identifier of the VM getting this lease
* @param ip ip of lease requested
* @param mac mac of the lease
* @param eui64 extended unique identifier
* @return 0 if success
*/
virtual int set(int vid, const string& ip, string& mac, unsigned int *eui64) = 0;
/**
* Release an used lease, which becomes unused
* @param ip of the lease in use
*/
virtual void release(const string& ip) = 0;
/**
* Adds New leases. (Only implemented for FIXED networks)
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
virtual int add_leases(vector<const Attribute*>& vector_leases,
string& error_msg) = 0;
/**
* Removes leases; if they are not used. (Only available for FIXED networks)
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
virtual int remove_leases(vector<const Attribute*>& vector_leases,
string& error_msg) = 0;
/**
* Holds a Lease, marking it as used
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int hold_leases(vector<const Attribute*>& vector_leases, string& error_msg);
/**
* Releases a Lease on hold
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int free_leases(vector<const Attribute*>& vector_leases, string& error_msg);
protected:
/**
* The Lease class, it represents a pair of IP and MAC assigned to
* a Virtual Machine
*/
class Lease : public ObjectXML
{
public:
/**
* Creates a new lease, numeric form.
* @param _ip, the Lease IP in numeric format
* @param _mac, the Lease MAC in numeric format
* @param _vid, the ID of the VM owning the lease
* @param _used, the lease is in use
*/
Lease(unsigned int _ip,
unsigned int _mac[],
int _vid,
bool _used)
:ObjectXML(),ip(_ip), vid(_vid), used(_used)
{
mac[1]=_mac[1];
mac[0]=_mac[0];
mac_to_eui64(mac, eui64);
};
/**
* Creates a new empty lease. Method from_xml should be called right
* after this constructor.
*/
Lease():ObjectXML(){};
~Lease(){};
/**
* Conversion from string IP to unsigned int IP
* @return 0 if success
*/
static int ip_to_number(const string& ip, unsigned int& i_ip);
/**
* Conversion from unsigned int IP to string IP
*/
static void ip_to_string(const unsigned int i_ip, string& ip);
/**
* Generates IPv6 strings based on the modified EUI64 and global and
* site network prefixes.
*/
static void ip6_to_string(const unsigned int eui64[],
const unsigned int prefix[],
string& ip6s);
/**
* Conversion from string MAC to unsigned int[] MAC
* @return 0 if success
*/
static int mac_to_number(const string& mac, unsigned int i_mac[]);
/**
* Generates the modified extended unique identifier based on MAC
* @param i_mac the MAC address
* @param i_meui64 the modified EUI64
*/
static void mac_to_eui64(const unsigned int mac[], unsigned int eui64[]);
/**
* Conversion from string IP to unsigned int IP
*/
static void mac_to_string(const unsigned int i_mac[], string& mac);
/**
* Conversion from string IP to unsigned int IP
*/
static int prefix6_to_number(const string& prefix, unsigned int ip[]);
/**
* Function to print the Lease 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 unsigned int global[],
const unsigned int site[]) const;
/**
* Function to print the Lease object into a string in
* XML format. The output contains all the internal attributes,
* to be saved in the DB as a blob
* @param xml the resulting XML string
* @return a reference to the generated string
*/
string& to_xml_db(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);
unsigned int ip;
unsigned int mac[2];
unsigned int eui64[2];
int vid;
bool used;
};
friend class VirtualNetwork;
friend class VirtualNetworkPool;
// -------------------------------------------------------------------------
// Leases fields
// -------------------------------------------------------------------------
/**
* Leases identifier. Connects it to a Virtual Network
*/
int oid;
/**
* Number of possible leases (free + assigned)
*/
unsigned int size;
/**
* Hash of leases, indexed by lease.ip
*/
map<unsigned int, Lease *> leases;
/**
* Number of used leases
*/
int n_used;
/**
* The default MAC prefix for the Leases
*/
unsigned int mac_prefix;
/**
* Global prefix for IPv6 addresses (64 upper bits)
*/
unsigned int global[2];
/**
* Global prefix for IPv6 addresses (64 upper bits)
*/
unsigned int site[2];
// -------------------------------------------------------------------------
// DataBase implementation variables
// -------------------------------------------------------------------------
/**
* Pointer to the DataBase
*/
SqlDB * db;
static const char * table;
static const char * db_names;
static const char * db_bootstrap;
// -------------------------------------------------------------------------
// Leases methods
// -------------------------------------------------------------------------
/**
* Check if the passed ip corresponds with a given lease
* @param ip of the lease to be checked
* @return true if the ip was already assigned
*/
bool check(const string& ip);
/**
* Check if the passed ip corresponds with a given lease
* @param ip of the lease to be checked
* @return true if the ip was already assigned
*/
bool check(unsigned int ip);
/**
* Check if a VM is the owner of the ip
* @param ip of the lease to be checked
* @param vid the ID of the VM
* @return true if the ip was already assigned
*/
bool is_owner(const string& ip, int vid);
/**
* Reads the leases from the DB, and updates the lease hash table
* @param db pointer to the database.
* @return 0 on success.
*/
virtual int select(SqlDB * db);
friend ostream& operator<<(ostream& os, Lease& _lease);
/**
* Function to print the Leases 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;
private:
/**
* Callback function to unmarshall a Lease object (Lease::select)
* @param num the number of columns read from the DB
* @para names the column names
* @para vaues the column values
* @return 0 on success
*/
int select_cb(void *nil, int num, char **values, char **names);
/**
* This method should not be called, leases are added/removed/updated
* through add/del interface
* @param db pointer to the database.
* @return 0 on success.
*/
int insert(SqlDB * db, string& error_str);
/**
* Leases are added/removed/updated through add/del interface
* This method is for pool management.
* @param db pointer to the database.
* @return 0 on success.
*/
int drop(SqlDB * db);
/**
* This method should not be called, leases are added/removed/updated
* through add/del interface
* @param db pointer to the database.
* @return 0 on success.
*/
int update(SqlDB * db);
};
#endif /*LEASES_H_*/
+14
View File
@@ -475,6 +475,20 @@ public:
return obj_template->replace(name, value);
}
/**
* Removes an attribute from the template. The attributes are returned, and
* MUST be freed by the calling funtion
* @param name of the attribute
* @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)
{
return obj_template->remove(name, values);
}
/**
* Generates a XML string for the template of the Object
* @param xml the string to store the XML description.
-148
View File
@@ -1,148 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 RANGED_LEASES_H_
#define RANGED_LEASES_H_
#include "Leases.h"
#include "VirtualNetwork.h"
using namespace std;
class RangedLeases : public Leases
{
public:
// *************************************************************************
// Constructor
// *************************************************************************
RangedLeases(SqlDB * db,
int _oid,
unsigned int _mac_prefix,
unsigned int _global[],
unsigned int _site[],
unsigned int _ip_start,
unsigned int _ip_end);
~RangedLeases(){};
/**
* Reads (and clears) the necessary attributes to define a Ranged VNet
* @param vn Virtual Network
* @param ip_start First IP of the range
* @param ip_end Last IP of the range
* @param error_str Error reason, if any
* @return 0 on success, -1 otherwise
*/
static int process_template(VirtualNetwork * vn,
unsigned int& ip_start, unsigned int& ip_end, string& error_str);
/**
* Returns an unused lease, which becomes used
* @param vid identifier of the VM getting this lease
* @param ip ip of the returned lease
* @param mac mac of the returned lease
* @return 0 if success
*/
int get(int vid, string& ip, string& mac, unsigned int eui64[]);
/**
* Ask for a specific lease in the network
* @param vid identifier of the VM getting this lease
* @param ip ip of lease requested
* @param mac mac of the lease
* @return 0 if success
*/
int set(int vid, const string& ip, string& mac, unsigned int eui64[]);
/**
* Release an used lease, which becomes unused
* @param ip of the lease in use
*/
void release(const string& ip)
{
del(ip);
}
/**
* Adds New leases.
* Only available for FIXED networks.
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int add_leases(vector<const Attribute*>& vector_leases, string& error_msg)
{
error_msg = "Adding new leases is only supported for FIXED networks.";
return -1;
}
/**
* Removes leases; if they are not used.
* Only available for FIXED networks.
* @param vector_leases vector of VectorAttribute objects. For the
* moment, the vector can only contain one LEASE.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int remove_leases(vector<const Attribute*>& vector_leases, string& error_msg)
{
error_msg = "Removing leases is only supported for FIXED networks.";
return -1;
}
/**
* Loads the leases from the DB.
*/
int select(SqlDB * db)
{
//Read the leases from the DB
int rc = Leases::select(db);
return rc;
}
private:
unsigned int ip_start;
unsigned int ip_end;
unsigned int current;
/**
* Add a lease, from the Lease interface
* @param ip ip of the lease
* @param mac mac of the lease
* @param vid identifier of the VM getting this lease
* @return 0 if success
*/
int add(unsigned int ip, unsigned int mac[], int vid, bool used=true);
/**
* Remove a lease, from the Lease interface
* @param db pointer to DB
* @param ip ip of the lease to be deleted
* @return 0 if success
*/
int del(const string& ip);
};
#endif /*RANGED_LEASES_H_*/
+7 -1
View File
@@ -73,11 +73,13 @@ protected:
string uname; /**< name of the user */
string gname; /**< name of the user's group */
set<int> group_ids; /**< set of user's group ids */
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(){};
@@ -92,6 +94,8 @@ protected:
session = ra.session;
retval = ra.retval;
umask = ra.umask;
};
RequestAttributes(int _uid, int _gid, const RequestAttributes& ra)
@@ -102,6 +106,8 @@ protected:
uname = "";
gname = "";
umask = 0;
session = ra.session;
retval = ra.retval;
};
+38 -50
View File
@@ -61,12 +61,11 @@ protected:
virtual Template * get_object_template() { return 0; };
virtual int pool_allocate(xmlrpc_c::paramList const& _paramList,
virtual int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
return -1;
};
@@ -77,10 +76,9 @@ protected:
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask)
const string& cluster_name)
{
return pool_allocate(_paramList, tmpl, id, error_str, att, umask);
return pool_allocate(_paramList, tmpl, id, error_str, att);
};
virtual int get_cluster_id(xmlrpc_c::paramList const& paramList)
@@ -122,7 +120,7 @@ public:
"Allocates a new virtual machine",
"A:ssb",
true)
{
{
Nebula& nd = Nebula::instance();
pool = nd.get_vmpool();
auth_object = PoolObjectSQL::VM;
@@ -132,17 +130,16 @@ public:
/* --------------------------------------------------------------------- */
Template * get_object_template()
{
return new VirtualMachineTemplate;
Template * get_object_template()
{
return new VirtualMachineTemplate;
};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
bool allocate_authorization(Template * obj_template,
RequestAttributes& att,
@@ -160,7 +157,7 @@ public:
"Allocates a new virtual network",
"A:ssi",
true)
{
{
Nebula& nd = Nebula::instance();
pool = nd.get_vnpool();
auth_object = PoolObjectSQL::NET;
@@ -170,9 +167,9 @@ public:
/* --------------------------------------------------------------------- */
Template * get_object_template()
{
return new VirtualNetworkTemplate;
Template * get_object_template()
{
return new VirtualNetworkTemplate;
};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
@@ -181,8 +178,7 @@ public:
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask);
const string& cluster_name);
int get_cluster_id(xmlrpc_c::paramList const& paramList)
{
@@ -235,7 +231,7 @@ public:
"Allocates a new virtual machine template",
"A:ss",
true)
{
{
Nebula& nd = Nebula::instance();
pool = nd.get_tpool();
auth_object = PoolObjectSQL::TEMPLATE;
@@ -245,17 +241,16 @@ public:
/* --------------------------------------------------------------------- */
Template * get_object_template()
{
return new VirtualMachineTemplate;
Template * get_object_template()
{
return new VirtualMachineTemplate;
};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
@@ -269,7 +264,7 @@ public:
"Allocates a new host",
"A:sssssi",
false)
{
{
Nebula& nd = Nebula::instance();
pool = nd.get_hpool();
auth_object = PoolObjectSQL::HOST;
@@ -285,8 +280,7 @@ public:
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask);
const string& cluster_name);
int get_cluster_id(xmlrpc_c::paramList const& paramList)
{
@@ -314,7 +308,7 @@ public:
"Returns user information",
"A:ssss",
false)
{
{
Nebula& nd = Nebula::instance();
pool = nd.get_upool();
auth_object = PoolObjectSQL::USER;
@@ -322,12 +316,11 @@ public:
~UserAllocate(){};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
void log_xmlrpc_param(
const xmlrpc_c::value& v,
@@ -346,7 +339,7 @@ public:
"Allocates a new group",
"A:ss",
false)
{
{
Nebula& nd = Nebula::instance();
pool = nd.get_gpool();
auth_object = PoolObjectSQL::GROUP;
@@ -354,12 +347,11 @@ public:
~GroupAllocate(){};
int pool_allocate(xmlrpc_c::paramList const& _paramList,
int pool_allocate(xmlrpc_c::paramList const& _paramList,
Template * tmpl,
int& id,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
@@ -394,8 +386,7 @@ public:
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask);
const string& cluster_name);
int get_cluster_id(xmlrpc_c::paramList const& paramList)
{
@@ -449,8 +440,7 @@ public:
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
@@ -483,8 +473,7 @@ public:
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
@@ -520,8 +509,7 @@ public:
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask);
RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
+6 -9
View File
@@ -49,8 +49,7 @@ protected:
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask) = 0;
RequestAttributes& att) = 0;
};
/* ------------------------------------------------------------------------- */
@@ -84,15 +83,14 @@ public:
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
VMTemplatePool * tpool = static_cast<VMTemplatePool *>(pool);
VirtualMachineTemplate * ttmpl =
static_cast<VirtualMachineTemplate *>(tmpl);
return tpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
return tpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
ttmpl, &id, error_str);
};
};
@@ -129,14 +127,13 @@ public:
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
DocumentPool * docpool = static_cast<DocumentPool *>(pool);
Document * doc = docpool->get(source_id, true);
return docpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
doc->get_document_type(), tmpl, &id, error_str);
return docpool->allocate(att.uid, att.gid, att.uname, att.gname,
att.umask, doc->get_document_type(), tmpl, &id, error_str);
};
};
+1
View File
@@ -144,6 +144,7 @@ public:
Nebula& nd = Nebula::instance();
pool = nd.get_vnpool();
auth_object = PoolObjectSQL::NET;
auth_op = AuthRequest::ADMIN;
};
~VirtualNetworkUpdateTemplate(){};
+100 -14
View File
@@ -49,6 +49,7 @@ protected:
virtual int leases_action(VirtualNetwork * vn,
VirtualNetworkTemplate * tmpl,
RequestAttributes& att,
string& error_str) = 0;
/* -------------------------------------------------------------------- */
@@ -58,39 +59,101 @@ protected:
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualNetworkAddLeases : public RequestManagerVirtualNetwork
class VirtualNetworkAddAddressRange: public RequestManagerVirtualNetwork
{
public:
VirtualNetworkAddLeases():
RequestManagerVirtualNetwork("VirtualNetworkAddLeases",
"Adds leases to a virtual network"){};
~VirtualNetworkAddLeases(){};
VirtualNetworkAddAddressRange():
RequestManagerVirtualNetwork("VirtualNetworkAddAddressRange",
"Adds address ranges to a virtual network")
{
auth_op = AuthRequest::ADMIN;
};
~VirtualNetworkAddAddressRange(){};
int leases_action(VirtualNetwork * vn,
VirtualNetworkTemplate * tmpl,
RequestAttributes& att,
string& error_str)
{
return vn->add_leases(tmpl, error_str);
return vn->add_ar(tmpl, error_str);
}
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualNetworkRemoveLeases : public RequestManagerVirtualNetwork
class VirtualNetworkRmAddressRange : public Request
{
public:
VirtualNetworkRemoveLeases():
RequestManagerVirtualNetwork("VirtualNetworkRemoveLeases",
"Removes leases from a virtual network"){};
~VirtualNetworkRemoveLeases(){};
VirtualNetworkRmAddressRange(
const string& name = "VirtualNetworkRmAddressRange",
const string& sign = "A:sii",
const string& help = "Removes an address range from a virtual network")
: Request(name, sign, help)
{
Nebula& nd = Nebula::instance();
pool = nd.get_vnpool();
auth_object = PoolObjectSQL::NET;
auth_op = AuthRequest::ADMIN;
};
virtual ~VirtualNetworkRmAddressRange(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualNetworkFreeAddressRange : public VirtualNetworkRmAddressRange
{
public:
VirtualNetworkFreeAddressRange():VirtualNetworkRmAddressRange(
"VirtualNetworkFreeAddressRange",
"A:sii",
"Frees a reserved address range from a virtual network")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vnpool();
auth_object = PoolObjectSQL::NET;
auth_op = AuthRequest::MANAGE;
};
~VirtualNetworkFreeAddressRange(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att)
{
VirtualNetworkRmAddressRange::request_execute(_paramList, att);
}
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualNetworkUpdateAddressRange: public RequestManagerVirtualNetwork
{
public:
VirtualNetworkUpdateAddressRange():
RequestManagerVirtualNetwork("VirtualNetworkUpdateAddressRange",
"Updates address ranges to a virtual network")
{
auth_op = AuthRequest::ADMIN;
};
~VirtualNetworkUpdateAddressRange(){};
int leases_action(VirtualNetwork * vn,
VirtualNetworkTemplate * tmpl,
string& error_str)
RequestAttributes& att,
string& error_str)
{
return vn->remove_leases(tmpl, error_str);
}
return vn->update_ar(tmpl, error_str);
};
};
/* ------------------------------------------------------------------------- */
@@ -106,6 +169,7 @@ public:
int leases_action(VirtualNetwork * vn,
VirtualNetworkTemplate * tmpl,
RequestAttributes& att,
string& error_str)
{
return vn->hold_leases(tmpl, error_str);
@@ -125,12 +189,34 @@ public:
int leases_action(VirtualNetwork * vn,
VirtualNetworkTemplate * tmpl,
RequestAttributes& att,
string& error_str)
{
return vn->free_leases(tmpl, error_str);
}
};
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
class VirtualNetworkReserve: public Request
{
public:
VirtualNetworkReserve():Request("VirtualNetworkReserve", "A:sis",
"Reserve network addresses")
{
Nebula& nd = Nebula::instance();
pool = nd.get_vnpool();
auth_object = PoolObjectSQL::NET;
auth_op = AuthRequest::USE;
};
~VirtualNetworkReserve(){};
void request_execute(xmlrpc_c::paramList const& _paramList,
RequestAttributes& att);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
+7
View File
@@ -168,6 +168,13 @@ public:
*/
int get_umask() const;
/**
* Returns the default UMASK attribute (octal) from oned.conf
*
* @return the UMASK to create new objects
*/
static int get_default_umask();
/**
* Returns a copy of the groups for the user
*/
+9 -4
View File
@@ -140,6 +140,7 @@ public:
* @param uname of the user if authN succeeded "" otherwise
* @param gname of the group if authN succeeded "" otherwise
* @param group_ids the user groups if authN succeeded, is empty otherwise
* @param umask of the user, 0 otherwise
*
* @return false if authn failed, true otherwise
*/
@@ -148,7 +149,8 @@ public:
int& gid,
string& uname,
string& gname,
set<int>& group_ids);
set<int>& group_ids,
int& umask);
/**
* Returns whether the operations described in a authorization request are
* authorized ot not.
@@ -223,7 +225,8 @@ private:
int& group_id,
string& uname,
string& gname,
set<int>& group_ids);
set<int>& group_ids,
int& umask);
/**
* Function to authenticate internal users using a server driver
@@ -234,7 +237,8 @@ private:
int& group_id,
string& uname,
string& gname,
set<int>& group_ids);
set<int>& group_ids,
int& umask);
/**
@@ -246,7 +250,8 @@ private:
int& group_id,
string& uname,
string& gname,
set<int>& group_ids);
set<int>& group_ids,
int& umask);
/**
* Factory method to produce User objects
* @return a pointer to the new User
+235 -148
View File
@@ -19,9 +19,9 @@
#include "PoolSQL.h"
#include "Leases.h"
#include "VirtualNetworkTemplate.h"
#include "Clusterable.h"
#include "AddressRangePool.h"
#include <vector>
#include <string>
@@ -44,17 +44,6 @@ class VirtualNetwork : public PoolObjectSQL, public Clusterable
{
public:
/**
* Possible types of networks
*/
enum NetworkType
{
UNINITIALIZED = -1,
RANGED = 0,
FIXED = 1
};
// *************************************************************************
// Virtual Network Public Methods
// *************************************************************************
@@ -67,26 +56,67 @@ public:
return new VirtualNetworkTemplate;
}
// *************************************************************************
// Address Range management interface
// *************************************************************************
/**
* Adds Leases to the virtual network (Only implemented for FIXED networks)
* @param leases template in the form LEASES = [IP=XX, MAC=XX].
* MAC is optional. The template can only contain one LEASE
* definition.
* Add a set of address ranges to the virtual network
* @param ars_tmpl template in the form AR = [TYPE=...,IP=...,SIZE=...].
* @param error_msg If the action fails, this message contains the reason.
* @return 0 on success
*/
int add_leases(VirtualNetworkTemplate * leases, string& error_msg);
int add_ar(VirtualNetworkTemplate * ars_tmpl, string& error_msg);
/**
* Removes Leases from the virtual network; if they are not used.(Only
* implemented for FIXED networks)
* @param leases template in the form LEASES = [IP=XX].
* The template can only contain one LEASE definition.
* @param error_msg If the action fails, this message contains
* the reason.
* Adds a set of address ranges
* @param var a vector of address ranges
* @param error_msg If the action fails, this message contains the reason.
* @return 0 on success
*/
int remove_leases(VirtualNetworkTemplate* leases, string& error_msg);
int add_var(vector<Attribute *> &var, string& error_msg);
/**
* Removes an address range from the VNET
* @param ar_id of the address range
* @param error_msg If the action fails, this message contains the reason.
* @return 0 on success
*/
int rm_ar(unsigned int ar_id, string& error_msg);
/**
* Allocates a new (and empty) address range. It is not added to the
* ar_pool
* @return pointer to the new address range
*/
AddressRange * allocate_ar()
{
return ar_pool.allocate_ar();
}
/**
* Adds a previously allocated address range to the AR pool
* @param rar pointer to the address range
* @return 0 on success
*/
int add_ar(AddressRange * rar)
{
return ar_pool.add_ar(rar);
}
/**
* Update an address range to the virtual network
* @param ars_tmpl template in the form AR = [AR_ID=...]. The address range
* is specified by the AR_ID attribute.
* @param error_msg If the action fails, this message contains
* the reason.
* @return 0 on success
*/
int update_ar(VirtualNetworkTemplate * ars_tmpl, string& error_msg);
// *************************************************************************
// Address hold/release interface
// *************************************************************************
/**
* Holds a Lease, marking it as used
@@ -107,75 +137,187 @@ public:
*/
int free_leases(VirtualNetworkTemplate* leases, string& error_msg);
// *************************************************************************
// Address allocation funtions
// *************************************************************************
/**
* Gets a new lease for a specific VM
* Gets a new address lease for a specific VM
* @param vid VM identifier
* @param _ip pointer to string for IP to be stored into
* @param _mac pointer to string for MAC to be stored into
* @param _bridge name of the physical bridge this VN binds to
* @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 get_lease(int vid, string& _ip, string& _mac, string& _bridge)
int allocate_addr(int vid, VectorAttribute * nic,
const vector<string>& inherit)
{
unsigned int eui64[2];
_bridge = bridge;
return leases->get(vid, _ip, _mac, eui64);
};
return ar_pool.allocate_addr(PoolObjectSQL::VM, vid, nic, inherit);
}
/**
* Asks for an specific lease of the given virtual network
* Gets a new address lease for a specific VM by MAC
* @param vid VM identifier
* @param _ip the ip of the requested lease
* @param _mac pointer to string for MAC to be stored into
* @param _bridge name of the physical bridge this VN binds to
* @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 set_lease(int vid, const string& _ip, string& _mac, string& _bridge)
int allocate_by_mac(int vid, const string& mac, VectorAttribute * nic,
const vector<string>& inherit)
{
unsigned int eui64[2];
_bridge = bridge;
return leases->set(vid, _ip, _mac, eui64);
};
return ar_pool.allocate_by_mac(mac, PoolObjectSQL::VM, vid, nic, inherit);
}
/**
* Release previously given lease
* @param _ip IP identifying the lease
* Gets a new address lease for a specific VM by IP
* @param vid VM identifier
* @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
*/
void release_lease(const string& ip)
int allocate_by_ip(int vid, const string& ip, VectorAttribute * nic,
const vector<string>& inherit)
{
return leases->release(ip);
};
return ar_pool.allocate_by_ip(ip, PoolObjectSQL::VM, vid, nic, inherit);
}
/**
* Check if a VM is the owner of the ip
* @param ip of the lease to be checked
* Release previously given address lease
* @param arid of the address range where the address was leased from
* @param vid the ID of the VM
* @return true if the ip was already assigned
* @param mac MAC address identifying the lease
*/
bool is_owner (const string& ip, int vid)
void free_addr(unsigned int arid, int vid, const string& mac)
{
return leases->is_owner(ip, vid);
};
ar_pool.free_addr(arid, PoolObjectSQL::VM, vid, mac);
}
/**
* Gets size of the network (used + free)
* @return number of hosts that can be fitted in this network
* Release all previously given address leases to the given object
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @return the number of addresses freed
*/
unsigned int get_size()
int free_addr_by_owner(PoolObjectSQL::ObjectType ot, int obid)
{
return leases->size;
};
return ar_pool.free_addr_by_owner(ot, obid);
}
/**
* Release a previously leased address range
* @param ot the type of the object requesting the address (VM or NET)
* @param obid the id of the object requesting the address
* @return the number of addresses freed
*/
int free_addr_by_range(unsigned int arid, PoolObjectSQL::ObjectType ot,
int obid, const string& mac, unsigned int rsize)
{
return ar_pool.free_addr_by_range(arid, ot, obid, mac, rsize);
}
/**
* Modifies the given nic attribute adding the following attributes:
* * IP: leased from network
* * MAC: leased from network
* * BRIDGE: for this virtual network
* @param nic attribute for the VM template
* @param vid of the VM getting the lease
* @param inherit_attrs Attributes to be inherited from the vnet template
* into the nic
* @return 0 on success
*/
int nic_attribute(
VectorAttribute * nic,
int vid,
const vector<string>& inherit_attrs);
// *************************************************************************
// Network Reservation functions
// *************************************************************************
/**
* Reserve an address range for this network and add it to the given vnet
* @param rvnet the VNET to store the reserved AR
* @param rsize number of addresses to reserve
* @param error_str error message
* @return 0 on success
*/
int reserve_addr(VirtualNetwork *rvnet, unsigned int rsize,
string& error_str);
/**
* Reserve an address range for this network and add it to the given vnet
* @param rvnet the VNET to store the reserved AR
* @param rsize number of addresses to reserve
* @param ar_id id of the address range to obtain the addresses
* @param error_str error message
* @return 0 on success
*/
int reserve_addr(VirtualNetwork *rvnet, unsigned int rsize,
unsigned int ar_id, string& error_str);
/**
* Reserve an address range for this network and add it to the given vnet
* @param rvnet the VNET to store the reserved AR
* @param rsize number of addresses to reserve
* @param ar_id id of the address range to obtain the addresses
* @param error_str error message
* @param ip the first ip in the reservations
* @return 0 on success
*/
int reserve_addr_by_ip(VirtualNetwork *rvnet, unsigned int rsize,
unsigned int ar_id, const string& ip, string& error_str);
/**
* Reserve an address range for this network and add it to the given vnet
* @param rvnet the VNET to store the reserved AR
* @param rsize number of addresses to reserve
* @param ar_id id of the address range to obtain the addresses
* @param mac the first mac in the reservations
* @param error_str error message
* @return 0 on success
*/
int reserve_addr_by_mac(VirtualNetwork *rvnet, unsigned int rsize,
unsigned int ar_id, const string& mac, string& error_str);
// *************************************************************************
// Formatting & Helper functions
// *************************************************************************
/**
* Gets used leases
* @return number of network leases in used
*/
unsigned int get_used()
{
return leases->n_used;
return ar_pool.get_used_addr();
};
/**
* Gets total number of addresses
* @return the number of addresses
*/
unsigned int get_size()
{
return ar_pool.get_size();
};
/**
* Returns the parent network used to create this VNET (if any)
* @return the parent vnet id or -1 this vnet has no parent
*/
int get_parent() const
{
return parent_vid;
};
/**
* Returns the parent address range used to create this AR (if any)
* @param ar_id the id of the AR
* @return the parent AR id or -1 this vnet has no parent
*/
int get_ar_parent(int ar_id) const
{
return ar_pool.get_ar_parent(ar_id);
};
/**
@@ -203,22 +345,6 @@ public:
*/
string& to_xml_extended(string& xml) const;
/**
* Modifies the given nic attribute adding the following attributes:
* * IP: leased from network
* * MAC: leased from network
* * BRIDGE: for this virtual network
* @param nic attribute for the VM template
* @param vid of the VM getting the lease
* @param inherit_attrs Attributes to be inherited from the vnet template
* into the nic
* @return 0 on success
*/
int nic_attribute(
VectorAttribute * nic,
int vid,
const vector<string>& inherit_attrs);
/**
* Replace the template of the virtual network it also updates the BRIDGE,
* PHY_DEV, VLAN_ID and VLAN attributes.
@@ -226,6 +352,32 @@ public:
*/
int replace_template(const string& tmpl_str, string& error);
/**
* Gets a string based attribute (single) from an address range. If the
* attribute is not found in the address range, the VNET template will be
* used
* @param name of the attribute
* @param value of the attribute (a string), will be "" if not defined or
* not a single attribute
* @param ar_id of the address attribute.
*/
void get_template_attribute(const char * name, string& value, int ar_id) const;
/**
* int version of get_template_attribute
* @return 0 on success
*/
int get_template_attribute(const char * name, int& value, int ar_id) const;
/**
* @return A copy of the VNET Template
*/
VirtualNetworkTemplate * clone_template() const
{
return new VirtualNetworkTemplate(
*(static_cast<VirtualNetworkTemplate *>(obj_template)));
};
private:
// -------------------------------------------------------------------------
@@ -262,41 +414,14 @@ private:
int vlan;
/**
* IPv6 address global unicast prefix
* Parent VNET ID if any
*/
string global;
int parent_vid;
/**
* Binary representation of the IPv6 address global unicast prefix
* The Address Range Pool
*/
unsigned int global_bin[2];
/**
* IPv6 address site unicast prefix
*/
string site;
/**
* Binary representation of the IPv6 address site unicast prefix
*/
unsigned int site_bin[2];
// -------------------------------------------------------------------------
// Virtual Network Description
// -------------------------------------------------------------------------
/**
* Holds the type of this network
*/
NetworkType type;
/**
* Pointer to leases class, can be fixed or ranged.
* Holds information on given (and, optionally, possible) leases
*/
Leases * leases;
unsigned int ip_start;
unsigned int ip_end;
AddressRangePool ar_pool;
// *************************************************************************
// DataBase implementation (Private)
@@ -317,15 +442,9 @@ private:
*/
static int bootstrap(SqlDB * db)
{
int rc;
ostringstream oss_vnet(VirtualNetwork::db_bootstrap);
ostringstream oss_lease(Leases::db_bootstrap);
rc = db->exec(oss_vnet);
rc += db->exec(oss_lease);
return rc;
return db->exec(oss_vnet);
};
/**
@@ -354,6 +473,7 @@ private:
const string& _uname,
const string& _gname,
int _umask,
int _parent_vid,
int _cluster_id,
const string& _cluster_name,
VirtualNetworkTemplate * _vn_template = 0);
@@ -370,30 +490,6 @@ private:
static const char * db_bootstrap;
/**
* Reads the Virtual Network (identified with its OID) from the database.
* @param db pointer to the db
* @return 0 on success
*/
int select(SqlDB * db);
/**
* Reads the Virtual Network (identified with its OID) from the database.
* @param db pointer to the db
* @param name of the network
* @param uid of the owner
*
* @return 0 on success
*/
int select(SqlDB * db, const string& name, int uid);
/**
* Reads the Virtual Network leases from the database.
* @param db pointer to the db
* @return 0 on success
*/
int select_leases(SqlDB * db);
/**
* Writes the Virtual Network and its associated template and leases in the database.
* @param db pointer to the db
@@ -411,15 +507,6 @@ private:
string error_str;
return insert_replace(db, true, error_str);
}
/**
* Deletes a VNW from the database and all its associated information:
* - VNW template
* - given leases
* @param db pointer to the db
* @return 0 on success
*/
int drop(SqlDB * db);
};
#endif /*VIRTUAL_NETWORK_H_*/
+2 -1
View File
@@ -62,6 +62,7 @@ public:
const string& uname,
const string& gname,
int umask,
int parent_vid,
VirtualNetworkTemplate * vn_template,
int * oid,
int cluster_id,
@@ -188,7 +189,7 @@ private:
*/
PoolObjectSQL * create()
{
return new VirtualNetwork(-1,-1,"","",0,-1,"",0);
return new VirtualNetwork(-1,-1,"","",0,-1,-1,"",0);
};
/**
+7 -5
View File
@@ -821,7 +821,7 @@ EOT
return update_template_helper(true, id, resource, path, xpath)
end
def OpenNebulaHelper.update_template_helper(append, id, resource, path, xpath)
def OpenNebulaHelper.update_template_helper(append, id, resource, path, xpath, update=true)
unless path
require 'tempfile'
@@ -829,11 +829,13 @@ EOT
path = tmp.path
if !append
rc = resource.info
if update
rc = resource.info
if OpenNebula.is_error?(rc)
puts rc.message
exit -1
if OpenNebula.is_error?(rc)
puts rc.message
exit -1
end
end
tmp << resource.template_like_str(xpath)
+4 -4
View File
@@ -248,8 +248,8 @@ class OneVMHelper < OpenNebulaHelper::OneHelper
puts str % ["HOST",
vm['/VM/HISTORY_RECORDS/HISTORY[last()]/HOSTNAME']] if
%w{ACTIVE SUSPENDED POWEROFF}.include? vm.state_str
puts str % ["CLUSTER ID",
vm['/VM/HISTORY_RECORDS/HISTORY[last()]/CID'] ] if
puts str % ["CLUSTER ID",
vm['/VM/HISTORY_RECORDS/HISTORY[last()]/CID'] ] if
%w{ACTIVE SUSPENDED POWEROFF}.include? vm.state_str
puts str % ["START TIME",
OpenNebulaHelper.time_to_str(vm['/VM/STIME'])]
@@ -380,8 +380,8 @@ class OneVMHelper < OpenNebulaHelper::OneHelper
array_id += 1
end
if nic.has_key?("IP6_SITE")
ip6_link = {"IP" => nic.delete("IP6_SITE"),
if nic.has_key?("IP6_ULA")
ip6_link = {"IP" => nic.delete("IP6_ULA"),
"CLI_DONE" => true,
"DOUBLE_ENTRY" => true}
vm_nics.insert(array_id+1,ip6_link)
+144 -41
View File
@@ -18,6 +18,70 @@ require 'one_helper'
require 'one_helper/onevm_helper'
class OneVNetHelper < OpenNebulaHelper::OneHelper
AR = {
:name => "ar_id",
:short => "-a ar_id",
:large => "--address_range ar_id",
:format => Integer,
:description => "ID of the address range"
}
AR_MAC = {
:name => "mac",
:short => "-m mac",
:large => "--address_range_mac mac",
:format => String,
:description => "First MAC address in : notation"
}
AR_IP = {
:name => "ip",
:short => "-i ip",
:large => "--address_range_ip ip",
:format => String,
:description => "First IP address in . notation"
}
AR_SIZE = {
:name => "size",
:short => "-s size",
:large => "--address_range_size size",
:format => String,
:description => "Number of addresses in the range"
}
AR_IP6_GLOBAL = {
:name => "ip6_global",
:short => "-g ip6_pref",
:large => "--address_range_ip6g ip6_pref",
:format => String,
:description => "IP6 global prefix"
}
AR_IP6_ULA = {
:name => "ip6_ula",
:short => "-u ip6_pref",
:large => "--address_range_ip6u ip6_pref",
:format => String,
:description => "IP6 ula prefix"
}
R_NAME = {
:name => "rname",
:short => "-n reservation name",
:large => "--name reservation name",
:format => String,
:description => "Name of the address reservation"
}
R_SIZE = {
:name => "rsize",
:short => "-s reservation size",
:large => "--size reservation size",
:format => String,
:description => "Number of addresses to reserve"
}
def self.rname
"VNET"
end
@@ -26,12 +90,6 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
"onevnet.yaml"
end
def self.type_to_str(id)
id = id.to_i
type_str = VirtualNetwork::VN_TYPES[id]
return VirtualNetwork::SHORT_VN_TYPES[type_str]
end
def format_pool(options)
config_file = self.class.table_conf
@@ -57,10 +115,6 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
column :CLUSTER, "Name of the Cluster", :left, :size=>10 do |d|
OpenNebulaHelper.cluster_str(d["CLUSTER"])
end
column :TYPE, "Type of Virtual Network", :size=>6 do |d|
OneVNetHelper.type_to_str(d["TYPE"])
end
column :SIZE, "Size of the Virtual Network", :size=>5 do |d|
@@ -74,7 +128,7 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
column :LEASES, "Number of this Virtual Network's given leases",
:size=>6 do |d|
d["TOTAL_LEASES"]
d["USED_LEASES"]
end
default :ID, :USER, :GROUP, :NAME, :CLUSTER, :TYPE, :BRIDGE, :LEASES
@@ -109,14 +163,11 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
puts str % ["USER", vn['UNAME']]
puts str % ["GROUP", vn['GNAME']]
puts str % ["CLUSTER", OpenNebulaHelper.cluster_str(vn['CLUSTER'])]
puts str % ["TYPE", vn.type_str]
puts str % ["BRIDGE", vn["BRIDGE"]]
puts str % ["VLAN", OpenNebulaHelper.boolean_to_str(vn['VLAN'])]
puts str % ["PHYSICAL DEVICE", vn["PHYDEV"]] if !vn["PHYDEV"].empty?
puts str % ["VLAN ID", vn["VLAN_ID"]] if !vn["VLAN_ID"].empty?
puts str % ["GLOBAL PREFIX", vn["GLOBAL_PREFIX"]] if !vn["GLOBAL_PREFIX"].empty?
puts str % ["SITE PREFIX", vn["SITE_PREFIX"]] if !vn["SITE_PREFIX"].empty?
puts str % ["USED LEASES", vn['TOTAL_LEASES']]
puts str % ["USED LEASES", vn['USED_LEASES']]
puts
CLIHelper.print_header(str_h1 % "PERMISSIONS",false)
@@ -129,45 +180,97 @@ class OneVNetHelper < OpenNebulaHelper::OneHelper
puts str % [e, mask]
}
puts
CLIHelper.print_header(str_h1 % ["VIRTUAL NETWORK TEMPLATE"], false)
puts vn.template_str(false)
if vn.type_str == "RANGED"
puts
CLIHelper.print_header(str_h1 % ["RANGE"], false)
puts str % ["IP_START", vn['RANGE/IP_START']]
puts str % ["IP_END", vn['RANGE/IP_END']]
puts
CLIHelper.print_header(str_h1 % ["ADDRESS RANGE POOL"], false)
if !vn.to_hash['VNET']['AR_POOL']['AR'].nil?
arlist = [vn.to_hash['VNET']['AR_POOL']['AR']].flatten
end
lease_types = [ ["LEASES ON HOLD", 'LEASE[USED=1 and VID=-1]'],
["USED LEASES", 'LEASE[USED=1 and VID>-1]'],
["FREE LEASES", 'LEASE[USED=0]'] ]
lease_types.each { |pair|
leases_str = vn.template_like_str('/VNET/LEASES', false, pair[1])
if !leases_str.empty?
puts
CLIHelper.print_header(str_h1 % [pair[0]], false)
puts leases_str
CLIHelper::ShowTable.new(nil, self) do
column :AR, "", :size=>3 do |d|
d["AR_ID"]
end
}
column :TYPE, "", :left, :size=>5 do |d|
d["TYPE"]
end
column :SIZE, "", :size=>6 do |d|
d["SIZE"]
end
column :LEASES, "", :size=>6 do |d|
d["USED_LEASES"]
end
column :MAC, "", :size=>17 do |d|
d["MAC"]
end
column :IP, "", :size=>15 do |d|
d["IP"]||"-"
end
column :GLOBAL_PREFIX, "", :right, :size=>22 do |d|
d["GLOBAL_PREFIX"]||"-"
end
end.show(arlist, {})
puts
CLIHelper.print_header("VIRTUAL MACHINES", false)
puts
CLIHelper.print_header(str_h1 % ["LEASES"], false)
vms=vn.retrieve_elements("LEASES/LEASE/VID")
if !vn.to_hash['VNET']['AR_POOL']['AR'].nil?
lease_list = [vn.to_hash['VNET']['AR_POOL']['AR']].flatten
leases = Array.new
if vms
vms=vms.delete_if {|vm| vm=="-1" }
vms.map!{|e| e.to_i }
onevm_helper=OneVMHelper.new
onevm_helper.client=@client
onevm_helper.list_pool({:ids=>vms}, false)
lease_list.each do |ar|
id = ar['AR_ID']
if ar['LEASES'] && !ar['LEASES']['LEASE'].nil?
lease = [ar['LEASES']['LEASE']].flatten
lease.each do |l|
l['AR_ID'] = id
end
leases << lease
end
end
leases.flatten!
end
CLIHelper::ShowTable.new(nil, self) do
column :AR, "", :left, :size=>3 do |d|
d['AR_ID']
end
column :OWNER, "", :left, :size=>10 do |d|
if d['VM']
"VM : #{d['VM']}"
elsif d['VNET']
"NET: #{d['VNET']}"
end
end
column :MAC, "", :size=>17 do |d|
d["MAC"]
end
column :IP, "", :size=>15 do |d|
d["IP"]||"-"
end
column :IP6_GLOBAL, "", :size=>31 do |d|
d["IP6_GLOBAL"]||"-"
end
end.show(leases, {})
end
end
+129 -13
View File
@@ -47,6 +47,7 @@ cmd=CommandParser::CmdParser.new(ARGV) do
set :option, CommandParser::OPTIONS+OpenNebulaHelper::CLIENT_OPTIONS
CREATE_OPTIONS = [OneClusterHelper::CLUSTER]
STD_OPTIONS = CommandParser::OPTIONS + OpenNebulaHelper::CLIENT_OPTIONS
########################################################################
# Formatters for arguments
@@ -71,6 +72,10 @@ cmd=CommandParser::CmdParser.new(ARGV) do
helper.filterflag_to_i(arg)
end
set :format, :ar_id, "Integer" do |arg|
format_int(arg)
end
########################################################################
# Commands
########################################################################
@@ -103,23 +108,65 @@ cmd=CommandParser::CmdParser.new(ARGV) do
end
end
addleases_desc = <<-EOT.unindent
Adds a lease to the Virtual Network
addar_desc = <<-EOT.unindent
Adds an address range to the Virtual Network
EOT
command :addleases, addleases_desc, :vnetid, :ip, [:mac, nil] do
command :addar, addar_desc, :vnetid, :options=>STD_OPTIONS + [OneVNetHelper::AR_SIZE,
OneVNetHelper::AR_MAC, OneVNetHelper::AR_IP, OneVNetHelper::AR_IP6_GLOBAL,
OneVNetHelper::AR_IP6_ULA ] do
helper.perform_action(args[0],options,"lease added") do |vn|
vn.addleases(args[1], args[2])
ar = "AR = [ "
if options[:ip]
if options[:ip6_global] || options[:ip6_ula]
ar << "TYPE=\"IP4_6\""
else
ar << "TYPE=\"IP4\""
end
else
if options[:ip6_global] || options[:ip6_ula]
ar << "TYPE=\"IP6\""
else
ar << "TYPE=\"ETHER\""
end
end
if options[:size]
ar << ", SIZE = " << options[:size]
else
STDERR.puts "Address range needs to specify size (-s size)"
exit -1
end
ar << ", IP = " << options[:ip] if options[:ip]
ar << ", MAC = " << options[:mac] if options[:mac]
ar << ", GLOBAL_PREFIX = " << options[:ip6_global] if options[:ip6_global]
ar << ", ULA_PREFIX = " << options[:ip6_ula] if options[:ip6_ula]
ar << "]"
vn.add_ar(ar)
end
end
rmleases_desc = <<-EOT.unindent
Removes a lease from the Virtual Network
rmar_desc = <<-EOT.unindent
Removes an address range from the Virtual Network
EOT
command :rmleases, rmleases_desc, :vnetid, :ip do
helper.perform_action(args[0],options,"lease removed") do |vn|
vn.rmleases(args[1])
command :rmar, rmar_desc, :vnetid, :ar_id do
helper.perform_action(args[0],options,"address range removed") do |vn|
vn.rm_ar(args[1])
end
end
free_desc = <<-EOT.unindent
Frees a reserved address range from the Virtual Network
EOT
command :free, free_desc, :vnetid, :ar_id do
helper.perform_action(args[0],options,"address range freed") do |vn|
vn.free(args[1])
end
end
@@ -127,9 +174,12 @@ cmd=CommandParser::CmdParser.new(ARGV) do
Holds a Virtual Network lease, marking it as used
EOT
command :hold, hold_desc, :vnetid, :ip do
command :hold, hold_desc, :vnetid, :ip,
:options=>STD_OPTIONS + [OneVNetHelper::AR] do
helper.perform_action(args[0],options,"lease on hold") do |vn|
vn.hold(args[1])
ar = options[:ar_id] || -1
vn.hold(args[1], ar)
end
end
@@ -137,12 +187,48 @@ cmd=CommandParser::CmdParser.new(ARGV) do
Releases a Virtual Network lease on hold
EOT
command :release, release_desc, :vnetid, :ip do
command :release, release_desc, :vnetid, :ip,
:options=>STD_OPTIONS + [OneVNetHelper::AR] do
helper.perform_action(args[0],options,"lease released") do |vn|
vn.release(args[1])
ar = options[:ar_id] || -1
vn.release(args[1], ar)
end
end
reserve_desc = <<-EOT.unindent
Reserve addresses from the Virtual Network. A new virtual network will
be created to hold the reservation. Optionally the reservation can be
put on an exisiting VNET, as long as it contains a valid reservation
from the same VNET
EOT
command :reserve, reserve_desc, :vnetid, [:vnetid, nil],
:options=>STD_OPTIONS + [OneVNetHelper::AR, OneVNetHelper::R_NAME,
OneVNetHelper::R_SIZE, OneVNetHelper::AR_MAC, OneVNetHelper::AR_IP] do
helper.perform_action(args[0],options,"reservation made") do |vn|
rsize = options[:rsize] || -1
rname = options[:rname] || -1
addr = nil
addr = options[:mac] if options[:mac]
addr = options[:ip] if options[:ip]
if rsize == -1
STDERR.puts "Specify a size (-s size) for the reservation"
exit -1
end
if rname == -1 && args[1].nil?
STDERR.puts "Specify a name (-n name) for the reservation"
exit -1
end
vn.reserve(rname, rsize, options[:ar_id], addr, args[1])
end
end
chgrp_desc = <<-EOT.unindent
Changes the Virtual Network group
EOT
@@ -212,6 +298,36 @@ cmd=CommandParser::CmdParser.new(ARGV) do
end
end
update_ar_desc = <<-EOT.unindent
Update Address Range variables. SIZE, IP, MAC and TYPE cannot be updated
EOT
command :updatear, update_ar_desc, :vnetid, :ar_id, [:file, nil] do
helper.perform_action(args[0],options,"modified") do |obj|
rc = obj.info
if OpenNebula.is_error?(rc)
puts rc.message
exit -1
end
obj.delete_element("AR_POOL/AR[AR_ID!=#{args[1]}]")
obj.delete_element("AR_POOL/AR/LEASES")
obj.delete_element("AR_POOL/AR/USED_LEASES")
if obj.template_like_str("AR_POOL").empty?
puts "Address Range #{args[1]} does not exit for "<<
"Virtual Network #{args[0]}"
exit -1
end
str = OpenNebulaHelper.update_template_helper(false, args[0], obj,
args[2], "AR_POOL", false)
obj.update_ar(str)
end
end
rename_desc = <<-EOT.unindent
Renames the Virtual Network
EOT
+54 -17
View File
@@ -68,14 +68,28 @@ string * VectorAttribute::marshall(const char * _sep) const
string * VectorAttribute::to_xml() const
{
map<string,string>::const_iterator it;
ostringstream oss;
string * xml;
ostringstream oss;
oss << "<" << name() << ">";
to_xml(oss);
for (it=attribute_value.begin();it!=attribute_value.end();it++)
{
string * xml = new string;
*xml = oss.str();
return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void VectorAttribute::to_xml(ostringstream &oss) const
{
map<string,string>::const_iterator it;
oss << "<" << name() << ">";
for (it=attribute_value.begin();it!=attribute_value.end();it++)
{
if ( it->first.empty() )
{
continue;
@@ -87,21 +101,14 @@ string * VectorAttribute::to_xml() const
}
else
{
oss << "<" << it->first << "><![CDATA[" << it->second
<< "]]></"<< it->first << ">";
oss << "<" << it->first << "><![CDATA[" << it->second
<< "]]></"<< it->first << ">";
}
}
}
oss << "</"<< name() << ">";
xml = new string;
*xml = oss.str();
return xml;
oss << "</"<< name() << ">";
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
@@ -281,6 +288,36 @@ int VectorAttribute::vector_value(const char *name, int & value) const
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
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;
+5
View File
@@ -68,6 +68,11 @@ Datastore::Datastore(
group_u = 1;
}
Datastore::~Datastore()
{
delete obj_template;
};
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
+5 -2
View File
@@ -29,7 +29,7 @@ int NebulaTemplate::load_configuration()
string aname;
Attribute * attr;
map<string, Attribute *>::iterator iter, j;
map<string, Attribute *>::iterator iter, j, prev;
set_conf_default();
@@ -59,7 +59,10 @@ int NebulaTemplate::load_configuration()
else
{
delete iter->second;
conf_default.erase(iter++);
prev = iter++;
conf_default.erase(prev);
}
}
+94 -47
View File
@@ -23,26 +23,21 @@ module OpenNebula
# Constants and Class Methods
#######################################################################
VN_METHODS = {
:info => "vn.info",
:allocate => "vn.allocate",
:delete => "vn.delete",
:addleases => "vn.addleases",
:rmleases => "vn.rmleases",
:add_ar => "vn.add_ar",
:rm_ar => "vn.rm_ar",
:update_ar => "vn.update_ar",
:chown => "vn.chown",
:chmod => "vn.chmod",
:update => "vn.update",
:hold => "vn.hold",
:release => "vn.release",
:rename => "vn.rename"
}
VN_TYPES=%w{RANGED FIXED}
SHORT_VN_TYPES={
"RANGED" => "R",
"FIXED" => "F"
:rename => "vn.rename",
:reserve => "vn.reserve",
:free_ar => "vn.free_ar"
}
# Creates a VirtualNetwork description with just its identifier
@@ -116,38 +111,52 @@ module OpenNebula
super(VN_METHODS[:delete])
end
# Adds a lease to the VirtualNetwork
def addleases(ip, mac = nil)
# Adds Address Ranges to the VirtualNetwork
def add_ar(ar_template)
return Error.new('ID not defined') if !@pe_id
lease_template = "LEASES = [ IP = #{ip}"
lease_template << ", MAC = #{mac}" if mac
lease_template << " ]"
rc = @client.call(VN_METHODS[:addleases], @pe_id, lease_template)
rc = @client.call(VN_METHODS[:add_ar], @pe_id, ar_template)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
# Removes a lease from the VirtualNetwork
def rmleases(ip)
# Removes an Address Range from the VirtualNetwork
def rm_ar(ar_id)
return Error.new('ID not defined') if !@pe_id
lease_template = "LEASES = [ IP = #{ip} ]"
rc = @client.call(VN_METHODS[:rmleases], @pe_id, lease_template)
rc = @client.call(VN_METHODS[:rm_ar], @pe_id, ar_id.to_i)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
# Holds a virtual network Lease as used
# @param ip [String] IP to hold
def hold(ip)
# Updates Address Ranges from the VirtualNetwork
def update_ar(ar_template)
return Error.new('ID not defined') if !@pe_id
lease_template = "LEASES = [ IP = #{ip} ]"
rc = @client.call(VN_METHODS[:update_ar], @pe_id, ar_template)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
# Holds a virtual network address
# @param ip [String] address to hold, if contains ":" a MAC address is assumed
# @param ar_id [Integer] The address range to hold the lease. If not set
# the lease will be held from all possible address ranges
def hold(ip, ar_id=-1)
return Error.new('ID not defined') if !@pe_id
if ip.include?':'
addr_name = "MAC"
else
addr_name = "IP"
end
lease_template = "LEASES = [ #{addr_name} = #{ip}"
lease_template << ", AR_ID = #{ar_id}" if ar_id != -1
lease_template << "]"
rc = @client.call(VN_METHODS[:hold], @pe_id, lease_template)
rc = nil if !OpenNebula.is_error?(rc)
@@ -155,12 +164,22 @@ module OpenNebula
return rc
end
# Releases a virtual network Lease on hold
# @param ip [String] IP to release
def release(ip)
# Releases an address on hold
# @param ip [String] IP to release, if contains ":" a MAC address is assumed
# @param ar_id [Integer] The address range to release the lease. If not
# set the lease will be freed from all possible address ranges
def release(ip, ar_id=-1)
return Error.new('ID not defined') if !@pe_id
lease_template = "LEASES = [ IP = #{ip} ]"
if ip.include?':'
addr_name = "MAC"
else
addr_name = "IP"
end
lease_template = "LEASES = [ #{addr_name} = #{ip}"
lease_template << ", AR_ID = #{ar_id}" if ar_id != -1
lease_template << "]"
rc = @client.call(VN_METHODS[:release], @pe_id, lease_template)
rc = nil if !OpenNebula.is_error?(rc)
@@ -168,6 +187,49 @@ module OpenNebula
return rc
end
# Reserve a set of addresses from this virtual network
# @param name [String] of the reservation
# @param rsize[String] number of addresses to reserve
# @param ar_id[String] the ar_id to make the reservation. If set to nil
# any address range will be used
# @param addr [String] the first address in the reservation. If set to
# nil the first free address will be used
# @param vnet [String] ID of the VNET to add the reservation to. If not
# set a new VNET will be created.
def reserve(rname, rsize, ar_id, addr, vnet)
return Error.new('ID not defined') if !@pe_id
rtmpl = "SIZE = #{rsize}\n"
rtmpl << "NAME = #{rname}\n" if !rname.nil?
rtmpl << "AR_ID = #{ar_id}\n" if !ar_id.nil?
rtmpl << "NETWORK_ID = #{vnet}\n" if !vnet.nil?
if !addr.nil?
if addr.include?':'
addr_name = "MAC"
else
addr_name = "IP"
end
rtmpl << "#{addr_name} = #{addr}\n"
end
rc = @client.call(VN_METHODS[:reserve], @pe_id, rtmpl)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
# Removes an Address Range from the VirtualNetwork
def free(ar_id)
return Error.new('ID not defined') if !@pe_id
rc = @client.call(VN_METHODS[:free_ar], @pe_id, ar_id.to_i)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
# Changes the owner/group
#
# @param uid [Integer] the new owner id. Set to -1 to leave the current one
@@ -198,7 +260,7 @@ module OpenNebula
super(VN_METHODS[:chmod], owner_u, owner_m, owner_a, group_u,
group_m, group_a, other_u, other_m, other_a)
end
# Renames this virtual network
#
# @param name [String] New name for the virtual network.
@@ -219,21 +281,6 @@ module OpenNebula
self['GID'].to_i
end
# Returns the type of the Virtual Network (numeric value)
def type
self['TYPE'].to_i
end
# Returns the type of the Virtual Network (string value)
def type_str
VN_TYPES[type]
end
# Returns the state of the Virtual Network (string value)
def short_type_str
SHORT_VN_TYPES[type_str]
end
def public?
if self['PERMISSIONS/GROUP_U'] == "1" || self['PERMISSIONS/OTHER_U'] == "1"
true
+7 -6
View File
@@ -36,12 +36,13 @@ void Request::execute(
Nebula& nd = Nebula::instance();
UserPool* upool = nd.get_upool();
bool authenticated = upool->authenticate( att.session,
att.uid,
att.gid,
att.uname,
att.gname,
att.group_ids);
bool authenticated = upool->authenticate(att.session,
att.uid,
att.gid,
att.uname,
att.gname,
att.group_ids,
att.umask);
log_method_invoked(att, _paramList);
+10 -4
View File
@@ -276,10 +276,13 @@ void RequestManager::register_xml_methods()
xmlrpc_c::methodPtr vm_pool_monitoring(new VirtualMachinePoolMonitoring());
// VirtualNetwork Methods
xmlrpc_c::methodPtr vn_addleases(new VirtualNetworkAddLeases());
xmlrpc_c::methodPtr vn_rmleases(new VirtualNetworkRemoveLeases());
xmlrpc_c::methodPtr vn_add_ar(new VirtualNetworkAddAddressRange());
xmlrpc_c::methodPtr vn_rm_ar(new VirtualNetworkRmAddressRange());
xmlrpc_c::methodPtr vn_free_ar(new VirtualNetworkFreeAddressRange());
xmlrpc_c::methodPtr vn_update_ar(new VirtualNetworkUpdateAddressRange());
xmlrpc_c::methodPtr vn_hold(new VirtualNetworkHold());
xmlrpc_c::methodPtr vn_release(new VirtualNetworkRelease());
xmlrpc_c::methodPtr vn_reserve(new VirtualNetworkReserve());
// Update Template Methods
xmlrpc_c::methodPtr image_update(new ImageUpdateTemplate());
@@ -485,8 +488,11 @@ void RequestManager::register_xml_methods()
RequestManagerRegistry.addMethod("one.groupquota.update", group_set_default_quota);
/* Network related methods*/
RequestManagerRegistry.addMethod("one.vn.addleases", vn_addleases);
RequestManagerRegistry.addMethod("one.vn.rmleases", vn_rmleases);
RequestManagerRegistry.addMethod("one.vn.reserve", vn_reserve);
RequestManagerRegistry.addMethod("one.vn.add_ar", vn_add_ar);
RequestManagerRegistry.addMethod("one.vn.rm_ar", vn_rm_ar);
RequestManagerRegistry.addMethod("one.vn.update_ar", vn_update_ar);
RequestManagerRegistry.addMethod("one.vn.free_ar", vn_free_ar);
RequestManagerRegistry.addMethod("one.vn.hold", vn_hold);
RequestManagerRegistry.addMethod("one.vn.release", vn_release);
RequestManagerRegistry.addMethod("one.vn.allocate", vn_allocate);
+19 -67
View File
@@ -131,31 +131,13 @@ void RequestManagerAllocate::request_execute(xmlrpc_c::paramList const& params,
Template * tmpl = 0;
string error_str;
int rc, id, umask;
int rc, id;
Cluster * cluster = 0;
int cluster_id = ClusterPool::NONE_CLUSTER_ID;
string cluster_name = ClusterPool::NONE_CLUSTER_NAME;
PoolObjectAuth cluster_perms;
User * user;
UserPool * upool = Nebula::instance().get_upool();
user = upool->get(att.uid, true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER), att.uid),
att);
return;
}
umask = user->get_umask();
user->unlock();
if ( do_template == true )
{
string str_tmpl = xmlrpc_c::value_string(params.getString(1));
@@ -197,7 +179,7 @@ void RequestManagerAllocate::request_execute(xmlrpc_c::paramList const& params,
return;
}
rc = pool_allocate(params, tmpl, id, error_str, att, cluster_id, cluster_name, umask);
rc = pool_allocate(params, tmpl, id, error_str,att,cluster_id,cluster_name);
if ( rc < 0 )
{
@@ -257,8 +239,7 @@ int VirtualMachineAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
bool on_hold = false;
@@ -272,7 +253,7 @@ int VirtualMachineAllocate::pool_allocate(
Template tmpl_back(*tmpl);
int rc = vmpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
int rc = vmpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
ttmpl, &id, error_str, on_hold);
if ( rc < 0 )
@@ -294,13 +275,12 @@ int VirtualNetworkAllocate::pool_allocate(
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask)
const string& cluster_name)
{
VirtualNetworkPool * vpool = static_cast<VirtualNetworkPool *>(pool);
VirtualNetworkTemplate * vtmpl=static_cast<VirtualNetworkTemplate *>(tmpl);
return vpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
return vpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,-1,
vtmpl, &id, cluster_id, cluster_name, error_str);
}
@@ -330,7 +310,6 @@ void ImageAllocate::request_execute(xmlrpc_c::paramList const& params,
Nebula& nd = Nebula::instance();
UserPool * upool = nd.get_upool();
DatastorePool * dspool = nd.get_dspool();
ImagePool * ipool = static_cast<ImagePool *>(pool);
ImageManager * imagem = nd.get_imagem();
@@ -338,32 +317,13 @@ void ImageAllocate::request_execute(xmlrpc_c::paramList const& params,
ImageTemplate * tmpl;
Template img_usage;
User * user;
Datastore * ds;
Image::DiskType ds_disk_type;
long long avail;
int umask;
bool ds_check;
// ------------------------- Get user's umask ------------------------------
user = upool->get(att.uid, true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER), att.uid),
att);
return;
}
umask = user->get_umask();
user->unlock();
// ------------------------- Parse image template --------------------------
tmpl = new ImageTemplate;
@@ -512,7 +472,7 @@ void ImageAllocate::request_execute(xmlrpc_c::paramList const& params,
att.gid,
att.uname,
att.gname,
umask,
att.umask,
tmpl,
ds_id,
ds_name,
@@ -552,15 +512,14 @@ int TemplateAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
VMTemplatePool * tpool = static_cast<VMTemplatePool *>(pool);
VirtualMachineTemplate * ttmpl=static_cast<VirtualMachineTemplate *>(tmpl);
return tpool->allocate(att.uid, att.gid, att.uname, att.gname, umask, ttmpl,
&id, error_str);
return tpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
ttmpl, &id, error_str);
}
/* -------------------------------------------------------------------------- */
@@ -573,8 +532,7 @@ int HostAllocate::pool_allocate(
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask)
const string& cluster_name)
{
string host = xmlrpc_c::value_string(paramList.getString(1));
string im_mad = xmlrpc_c::value_string(paramList.getString(2));
@@ -596,8 +554,7 @@ int UserAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
string uname = xmlrpc_c::value_string(paramList.getString(1));
string passwd = xmlrpc_c::value_string(paramList.getString(2));
@@ -647,8 +604,7 @@ int GroupAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
string gname = xmlrpc_c::value_string(paramList.getString(1));
@@ -667,13 +623,12 @@ int DatastoreAllocate::pool_allocate(
string& error_str,
RequestAttributes& att,
int cluster_id,
const string& cluster_name,
int umask)
const string& cluster_name)
{
DatastorePool * dspool = static_cast<DatastorePool *>(pool);
DatastoreTemplate * ds_tmpl = static_cast<DatastoreTemplate *>(tmpl);
return dspool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
return dspool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
ds_tmpl, &id, cluster_id, cluster_name, error_str);
}
@@ -685,8 +640,7 @@ int ClusterAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
string name = xmlrpc_c::value_string(paramList.getString(1));
@@ -703,14 +657,13 @@ int DocumentAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
int type = xmlrpc_c::value_int(paramList.getInt(2));
DocumentPool * docpool = static_cast<DocumentPool *>(pool);
return docpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
return docpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
type, tmpl, &id, error_str);
}
@@ -739,8 +692,7 @@ int ZoneAllocate::pool_allocate(
Template * tmpl,
int& id,
string& error_str,
RequestAttributes& att,
int umask)
RequestAttributes& att)
{
string name = xmlrpc_c::value_string(paramList.getString(1));
+36 -3
View File
@@ -49,12 +49,12 @@ PoolObjectSQL * RequestManagerChown::get_and_quota(
return 0;
}
if ( auth_object == PoolObjectSQL::VM )
if (auth_object == PoolObjectSQL::VM)
{
tmpl = (static_cast<VirtualMachine*>(object))->clone_template();
qtype = Quotas::VIRTUALMACHINE;
}
else
else if (auth_object == PoolObjectSQL::IMAGE)
{
Image * img = static_cast<Image *>(object);
tmpl = new Template;
@@ -64,6 +64,38 @@ PoolObjectSQL * RequestManagerChown::get_and_quota(
qtype = Quotas::DATASTORE;
}
else if (auth_object == PoolObjectSQL::NET)
{
VirtualNetwork * vn = static_cast<VirtualNetwork *>(object);
unsigned int total = vn->get_size();
ostringstream oss;
string tmp_error;
int parent = vn->get_parent();
if (parent == -1)
{
return object;
}
tmpl = new Template;
for (unsigned int i= 0 ; i < total ; i++)
{
oss << " NIC = [ NETWORK_ID = " << parent << " ]" << endl;
}
tmpl->parse_str_or_xml(oss.str(), error_str);
qtype = Quotas::NETWORK;
}
else
{
object->unlock();
return 0;
}
if ( new_uid == -1 )
{
@@ -257,7 +289,8 @@ void RequestManagerChown::request_execute(xmlrpc_c::paramList const& paramList,
// --------------- Update the object and check quotas ----------------------
if ( auth_object == PoolObjectSQL::VM ||
auth_object == PoolObjectSQL::IMAGE )
auth_object == PoolObjectSQL::IMAGE ||
auth_object == PoolObjectSQL::NET)
{
object = get_and_quota(oid, noid, ngid, att);
}
+2 -20
View File
@@ -28,33 +28,15 @@ void RequestManagerClone::request_execute(
int source_id = xmlrpc_c::value_int(paramList.getInt(1));
string name = xmlrpc_c::value_string(paramList.getString(2));
int rc, new_id, umask;
int rc, new_id;
PoolObjectAuth perms;
Template * tmpl;
PoolObjectSQL * source_obj;
User * user;
UserPool * upool = Nebula::instance().get_upool();
string error_str;
user = upool->get(att.uid, true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER), att.uid),
att);
return;
}
umask = user->get_umask();
user->unlock();
source_obj = pool->get(source_id, true);
if ( source_obj == 0 )
@@ -98,7 +80,7 @@ void RequestManagerClone::request_execute(
}
}
rc = pool_allocate(source_id, tmpl, new_id, error_str, att, umask);
rc = pool_allocate(source_id, tmpl, new_id, error_str, att);
if ( rc < 0 )
{
+38 -1
View File
@@ -334,5 +334,42 @@ int VirtualNetworkDelete::drop(int oid, PoolObjectSQL * object, string& error_ms
return -1;
}
return RequestManagerDelete::drop(oid, object, error_msg);
int pvid = vnet->get_parent();
int uid = vnet->get_uid();
int gid = vnet->get_gid();
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if (pvid != -1)
{
vnet = (static_cast<VirtualNetworkPool *>(pool))->get(pvid, true);
if (vnet == 0)
{
return rc;
}
int freed = vnet->free_addr_by_owner(PoolObjectSQL::NET, oid);
pool->update(vnet);
vnet->unlock();
if (freed > 0)
{
ostringstream oss;
Template tmpl;
for (int i= 0 ; i < freed ; i++)
{
oss << " NIC = [ NETWORK_ID = " << pvid << " ]" << endl;
}
tmpl.parse_str_or_xml(oss.str(), error_msg);
Quotas::quota_del(Quotas::NETWORK, uid, gid, &tmpl);
}
}
return rc;
}
+2 -21
View File
@@ -230,7 +230,7 @@ void ImageClone::request_execute(
string name = xmlrpc_c::value_string(paramList.getString(2));
long long avail, size;
int rc, new_id, ds_id, umask;
int rc, new_id, ds_id;
string error_str, ds_name, ds_data;
bool ds_check;
@@ -241,30 +241,11 @@ void ImageClone::request_execute(
Template img_usage;
Image * img;
Datastore * ds;
User * user;
Nebula& nd = Nebula::instance();
DatastorePool * dspool = nd.get_dspool();
ImagePool * ipool = static_cast<ImagePool *>(pool);
UserPool * upool = nd.get_upool();
// ------------------------- Get user's umask ------------------------------
user = upool->get(att.uid, true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER), att.uid),
att);
return;
}
umask = user->get_umask();
user->unlock();
// ------------------------- Get source Image info -------------------------
@@ -391,7 +372,7 @@ void ImageClone::request_execute(
att.gid,
att.uname,
att.gname,
umask,
att.umask,
tmpl,
ds_id,
ds_name,
+1 -23
View File
@@ -31,7 +31,6 @@ void VMTemplateInstantiate::request_execute(xmlrpc_c::paramList const& paramList
int rc;
int vid;
int umask;
ostringstream sid;
@@ -41,12 +40,10 @@ void VMTemplateInstantiate::request_execute(xmlrpc_c::paramList const& paramList
VirtualMachinePool* vmpool = nd.get_vmpool();
VMTemplatePool * tpool = static_cast<VMTemplatePool *>(pool);
UserPool * upool = nd.get_upool();
VirtualMachineTemplate * tmpl;
VirtualMachineTemplate uattrs;
VMTemplate * rtmpl;
User * user;
string error_str;
string aname;
@@ -60,25 +57,6 @@ void VMTemplateInstantiate::request_execute(xmlrpc_c::paramList const& paramList
str_uattrs = xmlrpc_c::value_string(paramList.getString(4));
}
/* ---------------------------------------------------------------------- */
/* Get user's umask */
/* ---------------------------------------------------------------------- */
user = upool->get(att.uid, true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER), att.uid),
att);
return;
}
umask = user->get_umask();
user->unlock();
/* ---------------------------------------------------------------------- */
/* Get, check and clone the template */
/* ---------------------------------------------------------------------- */
@@ -212,7 +190,7 @@ void VMTemplateInstantiate::request_execute(xmlrpc_c::paramList const& paramList
Template tmpl_back(*tmpl);
rc = vmpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
rc = vmpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
tmpl, &vid, error_str, on_hold);
if ( rc < 0 )
+2 -25
View File
@@ -775,10 +775,6 @@ void VirtualMachineDeploy::request_execute(xmlrpc_c::paramList const& paramList,
}
}
// ------------------------------------------------------------------------
// Add a new history record and deploy the VM
// ------------------------------------------------------------------------
@@ -1029,7 +1025,6 @@ void VirtualMachineSaveDisk::request_execute(xmlrpc_c::paramList const& paramLis
ImagePool * ipool = nd.get_ipool();
DatastorePool * dspool = nd.get_dspool();
UserPool * upool = nd.get_upool();
VMTemplatePool* tpool = nd.get_tpool();
int id = xmlrpc_c::value_int(paramList.getInt(1));
@@ -1061,24 +1056,6 @@ void VirtualMachineSaveDisk::request_execute(xmlrpc_c::paramList const& paramLis
string target;
string dev_prefix;
// -------------------------------------------------------------------------
// Get user's umask
// -------------------------------------------------------------------------
User * user = upool->get(att.uid, true);
if ( user == 0 )
{
failure_response(NO_EXISTS,
get_error(object_name(PoolObjectSQL::USER), att.uid),
att);
return;
}
int umask = user->get_umask();
user->unlock();
// -------------------------------------------------------------------------
// Prepare and check the VM/DISK to be saved_as
// -------------------------------------------------------------------------
@@ -1310,7 +1287,7 @@ void VirtualMachineSaveDisk::request_execute(xmlrpc_c::paramList const& paramLis
att.gid,
att.uname,
att.gname,
umask,
att.umask,
itemplate,
ds_id,
ds_name,
@@ -1423,7 +1400,7 @@ void VirtualMachineSaveDisk::request_execute(xmlrpc_c::paramList const& paramLis
//Allocate the template
rc = tpool->allocate(att.uid, att.gid, att.uname, att.gname, umask,
rc = tpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
tmpl, &ntid, error_str);
if (rc < 0)
+427 -5
View File
@@ -24,7 +24,7 @@ using namespace std;
string RequestManagerVirtualNetwork::leases_error (const string& error)
{
return request_error("Error modifying network leases",error);
return request_error("Error modifying network leases", error);
}
/* ------------------------------------------------------------------------- */
@@ -64,14 +64,14 @@ void RequestManagerVirtualNetwork::
return;
}
rc = leases_action(vn,&tmpl,error_str);
rc = leases_action(vn, &tmpl, att, error_str);
if ( rc < 0 )
{
failure_response(INTERNAL,
failure_response(INTERNAL,
request_error("Error modifying network leases",error_str),
att);
vn->unlock();
return;
}
@@ -79,7 +79,429 @@ void RequestManagerVirtualNetwork::
pool->update(vn);
vn->unlock();
success_response(id, att);
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void VirtualNetworkRmAddressRange::
request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int id = xmlrpc_c::value_int(paramList.getInt(1));
int ar_id = xmlrpc_c::value_int(paramList.getInt(2));
VirtualNetwork * vn;
string error_str;
// -------------------------------------------------------------------------
// Authorize the operation VNET:MANAGE
// -------------------------------------------------------------------------
if (basic_authorization(id, att) == false)
{
return;
}
// -------------------------------------------------------------------------
// Get VNET and data for reservations
// -------------------------------------------------------------------------
vn = static_cast<VirtualNetwork *>(pool->get(id,true));
if ( vn == 0 )
{
failure_response(NO_EXISTS, get_error(object_name(auth_object),id),att);
return;
}
string mac;
int rsize;
int parent = vn->get_parent();
int parent_ar = vn->get_ar_parent(ar_id);
int uid = vn->get_uid();
int gid = vn->get_gid();
int rc = vn->get_template_attribute("SIZE", rsize, ar_id);
vn->get_template_attribute("MAC" , mac , ar_id);
if ( vn->rm_ar(ar_id, error_str) < 0 )
{
failure_response(INTERNAL,
request_error("Error removing address range",error_str),
att);
vn->unlock();
return;
}
pool->update(vn);
vn->unlock();
// -------------------------------------------------------------------------
// Free addresses in parent VNET for reservations
// -------------------------------------------------------------------------
if (parent != -1 && parent_ar != -1 && !mac.empty() && rc == 0)
{
vn = static_cast<VirtualNetwork *>(pool->get(parent, true));
if ( vn != 0 )
{
int freed = vn->free_addr_by_range((unsigned int) parent_ar,
PoolObjectSQL::NET, id, mac, rsize);
pool->update(vn);
vn->unlock();
if (freed > 0)
{
ostringstream oss;
Template tmpl;
for (int i= 0 ; i < freed ; i++)
{
oss << " NIC = [ NETWORK_ID = " << parent << " ]" << endl;
}
tmpl.parse_str_or_xml(oss.str(), error_str);
Quotas::quota_del(Quotas::NETWORK, uid, gid, &tmpl);
}
}
}
success_response(id, att);
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void VirtualNetworkReserve::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int id = xmlrpc_c::value_int (paramList.getInt(1));
string str_tmpl = xmlrpc_c::value_string (paramList.getString(2));
VirtualNetworkPool * vnpool = static_cast<VirtualNetworkPool *>(pool);
VirtualNetworkTemplate tmpl;
VirtualNetwork * vn = 0;
VirtualNetwork * rvn = 0;
string error_str;
int rc;
int cluster_id;
PoolObjectAuth reserv_perms;
// -------------------------------------------------------------------------
// Process the Reservation Template
// -------------------------------------------------------------------------
rc = tmpl.parse_str_or_xml(str_tmpl, error_str);
if ( rc != 0 )
{
failure_response(ACTION,
request_error("Error in reservation request", error_str), att);
return;
}
/* ------------------- Reservation SIZE ---------------- */
int size;
if ( !tmpl.get("SIZE", size) || size <= 0 )
{
failure_response(ACTION, request_error("Error in reservation request",
"Reservation SIZE must be a greater than 0"), att);
return;
}
/* ------------------- Target reservation NETWORK_ID ---------------- */
int rid;
bool on_exisiting = tmpl.get("NETWORK_ID", rid);
if ( on_exisiting)
{
/* ------------------- Check reservation consistency ---------------- */
if (rid < 0)
{
failure_response(ACTION, request_error("Error in reservation request",
"NETWORK_ID must be equal or greater than 0"), att);
return;
}
if (rid == id)
{
failure_response(ACTION, request_error("Error in reservation request",
"Cannot add a reservation from the same network"), att);
return;
}
rvn = vnpool->get(rid,true);
if (rvn == 0)
{
failure_response(NO_EXISTS, get_error(object_name(auth_object),rid),
att);
return;
}
int parent = rvn->get_parent();
if (parent == -1)
{
failure_response(ACTION, request_error("Error in reservation request",
"Cannot add reservations to a non-reservation VNET"), att);
rvn->unlock();
return;
}
if (parent != id)
{
ostringstream oss;
oss << "New reservations for virtual network " << rid
<< " have to be from network " << parent;
failure_response(ACTION, request_error("Error in reservation request",
oss.str()), att);
rvn->unlock();
return;
}
rvn->get_permissions(reserv_perms);
rvn->unlock();
}
/* ------------------- Reservation NAME ---------------- */
string name;
tmpl.get("NAME", name);
if (name.empty() && !on_exisiting)
{
failure_response(ACTION, request_error("Error in reservation request",
"NAME for reservation has to be set"), att);
return;
}
/* ------------------- Starting AR_ID, IP & MAC ---------------- */
int ar_id;
bool with_ar_id = tmpl.get("AR_ID", ar_id);
if ( with_ar_id && (ar_id < 0))
{
failure_response(ACTION, request_error("Error in reservation request",
"AR_ID must be equal or greater than 0"), att);
return;
}
string ip, mac;
tmpl.get("IP", ip);
tmpl.get("MAC", mac);
if (!with_ar_id && (!ip.empty()||!mac.empty()))
{
failure_response(ACTION, request_error("Error in reservation request",
"AR_ID must be specified for IP/MAC based reservations"), att);
return;
}
// -------------------------------------------------------------------------
// Authorize the operation Parent:USE Reservation:MANAGE
// -------------------------------------------------------------------------
vn = vnpool->get(id,true);
if ( vn == 0 )
{
failure_response(NO_EXISTS, get_error(object_name(auth_object),id),att);
return;
}
if (vn->get_parent() != -1)
{
failure_response(ACTION, request_error("Error in reservation request",
"Cannot reserve addresses from a reserved VNET"), att);
vn->unlock();
return;
}
PoolObjectAuth parent_perms;
AuthRequest ar(att.uid, att.group_ids);
vn->get_permissions(parent_perms);
ar.add_auth(AuthRequest::USE, parent_perms);
if (on_exisiting)
{
ar.add_auth(AuthRequest::MANAGE, reserv_perms);
}
if (UserPool::authorize(ar) == -1)
{
failure_response(AUTHORIZATION, authorization_error(ar.message, att),
att);
vn->unlock();
return;
}
// -------------------------------------------------------------------------
// Create a new VNET to place the reservation (if needed)
// -------------------------------------------------------------------------
if (!on_exisiting)
{
VirtualNetworkTemplate * vtmpl = vn->clone_template();
vtmpl->replace("NAME", name);
cluster_id = vn->get_cluster_id();
rc = vnpool->allocate(att.uid, att.gid, att.uname, att.gname, att.umask,
id, vtmpl, &rid, cluster_id, vn->get_cluster_name(), error_str);
if (rc < 0)
{
failure_response(INTERNAL,
request_error("Cannot create a reservation VNET",error_str),att);
vn->unlock();
return;
}
}
rvn = vnpool->get(rid, true);
if (rvn == 0)
{
failure_response(NO_EXISTS, get_error(object_name(auth_object),rid),
att);
vn->unlock();
return;
}
// -------------------------------------------------------------------------
// Check & update quotas on the target VNET & *reservation owner*
// -------------------------------------------------------------------------
ostringstream qtmpl_s;
Template qtmpl;
RequestAttributes reservation_att(rvn->get_uid(), rvn->get_gid(), att);
for (int i=0; i< size ; i++)
{
qtmpl_s << "NIC = [ NETWORK_ID = " << id << "]" << endl;
}
qtmpl.parse_str_or_xml(qtmpl_s.str(), error_str);
if (quota_authorization(&qtmpl, Quotas::NETWORK, reservation_att) == false)
{
rvn->unlock();
vn->unlock();
return;
}
// -------------------------------------------------------------------------
// Make address reservation and set it
// -------------------------------------------------------------------------
if (with_ar_id)
{
if (!ip.empty())
{
rc = vn->reserve_addr_by_ip(rvn, size, ar_id, ip, error_str);
}
else if (!mac.empty())
{
rc = vn->reserve_addr_by_mac(rvn, size, ar_id, mac, error_str);
}
else
{
rc = vn->reserve_addr(rvn, size, ar_id, error_str);
}
}
else
{
rc = vn->reserve_addr(rvn, size, error_str);
}
if (rc != 0 )
{
quota_rollback(&qtmpl, Quotas::NETWORK, reservation_att);
failure_response(ACTION, request_error(error_str,""), att);
if (!on_exisiting)
{
pool->drop(rvn, error_str);
}
rvn->unlock();
vn->unlock();
return;
}
pool->update(rvn);
pool->update(vn);
rvn->unlock();
vn->unlock();
// -------------------------------------------------------------------------
// Add the reservation to the same cluster as the parent VNET
// -------------------------------------------------------------------------
if ((cluster_id != ClusterPool::NONE_CLUSTER_ID) && (!on_exisiting))
{
Nebula& nd = Nebula::instance();
ClusterPool * clpool = nd.get_clpool();
Cluster * cluster = clpool->get(cluster_id, true);
if ( cluster != 0 )
{
cluster->add_vnet(rid, error_str);
clpool->update(cluster);
cluster->unlock();
}
}
success_response(rid, att);
}
+6 -4
View File
@@ -322,6 +322,7 @@ tabs:
vnets-tab:
panel_tabs:
vnet_info_tab: true
vnet_ar_list_tab: true
vnet_leases_tab: true
table_columns:
- 0 # Checkbox
@@ -329,8 +330,8 @@ tabs:
- 2 # Owner
- 3 # Group
- 4 # Name
- 5 # Cluster
- 6 # Type
- 5 # Reservation
- 6 # Cluster
#- 7 # Bridge
- 8 # Leases
actions:
@@ -341,10 +342,11 @@ tabs:
Network.chgrp: true
Network.chmod: true
Network.delete: true
Network.addleases: true
Network.hold_lease: true
Network.remove_lease: true
Network.release_lease: true
Network.add_ar: true
Network.remove_ar: true
Network.update_ar: true
marketplace-tab:
panel_tabs:
marketplace_info_tab: true
+6 -4
View File
@@ -319,6 +319,7 @@ tabs:
vnets-tab:
panel_tabs:
vnet_info_tab: false
vnet_ar_list_tab: false
vnet_leases_tab: true
table_columns:
- 0 # Checkbox
@@ -326,8 +327,8 @@ tabs:
- 2 # Owner
- 3 # Group
- 4 # Name
- 5 # Cluster
- 6 # Type
- 5 # Reservation
- 6 # Cluster
#- 7 # Bridge
- 8 # Leases
actions:
@@ -338,10 +339,11 @@ tabs:
Network.chgrp: false
Network.chmod: true
Network.delete: false
Network.addleases: false
Network.hold_lease: false
Network.remove_lease: false
Network.release_lease: false
Network.add_ar: false
Network.remove_ar: false
Network.update_ar: false
marketplace-tab:
panel_tabs:
marketplace_info_tab: true
+6 -4
View File
@@ -322,6 +322,7 @@ tabs:
vnets-tab:
panel_tabs:
vnet_info_tab: false
vnet_ar_list_tab: false
vnet_leases_tab: true
table_columns:
- 0 # Checkbox
@@ -329,8 +330,8 @@ tabs:
- 2 # Owner
- 3 # Group
- 4 # Name
- 5 # Cluster
- 6 # Type
- 5 # Reservation
- 6 # Cluster
#- 7 # Bridge
- 8 # Leases
actions:
@@ -341,10 +342,11 @@ tabs:
Network.chgrp: false
Network.chmod: true
Network.delete: false
Network.addleases: false
Network.hold_lease: false
Network.remove_lease: false
Network.release_lease: false
Network.add_ar: false
Network.remove_ar: false
Network.update_ar: false
marketplace-tab:
panel_tabs:
marketplace_info_tab: true
@@ -319,6 +319,7 @@ tabs:
vnets-tab:
panel_tabs:
vnet_info_tab: false
vnet_ar_list_tab: false
vnet_leases_tab: true
table_columns:
- 0 # Checkbox
@@ -326,8 +327,8 @@ tabs:
- 2 # Owner
- 3 # Group
- 4 # Name
- 5 # Cluster
- 6 # Type
- 5 # Reservation
- 6 # Cluster
#- 7 # Bridge
- 8 # Leases
actions:
@@ -338,10 +339,11 @@ tabs:
Network.chgrp: false
Network.chmod: true
Network.delete: false
Network.addleases: false
Network.hold_lease: false
Network.remove_lease: false
Network.release_lease: false
Network.add_ar: false
Network.remove_ar: false
Network.update_ar: false
marketplace-tab:
panel_tabs:
marketplace_info_tab: true
@@ -322,6 +322,7 @@ tabs:
vnets-tab:
panel_tabs:
vnet_info_tab: false
vnet_ar_list_tab: false
vnet_leases_tab: true
table_columns:
#- 0 # Checkbox
@@ -329,8 +330,8 @@ tabs:
#- 2 # Owner
#- 3 # Group
- 4 # Name
#- 5 # Cluster
#- 6 # Type
- 5 # Reservation
# 6 # Cluster
#- 7 # Bridge
- 8 # Leases
actions:
@@ -341,10 +342,11 @@ tabs:
Network.chgrp: false
Network.chmod: false
Network.delete: false
Network.addleases: false
Network.hold_lease: false
Network.remove_lease: false
Network.release_lease: false
Network.add_ar: false
Network.remove_ar: false
Network.update_ar: false
marketplace-tab:
panel_tabs:
marketplace_info_tab: true
@@ -42,8 +42,6 @@ module OpenNebulaJSON
end
rc = case action_hash['perform']
when "addleases" then self.addleases(action_hash['params'])
when "rmleases" then self.rmleases(action_hash['params'])
when "publish" then self.publish
when "unpublish" then self.unpublish
when "update" then self.update(action_hash['params'])
@@ -52,6 +50,10 @@ module OpenNebulaJSON
when "hold" then self.hold(action_hash['params'])
when "release" then self.release(action_hash['params'])
when "rename" then self.rename(action_hash['params'])
when "rm_ar" then self.rm_ar(action_hash['params'])
when "add_ar" then self.add_ar(action_hash['params'])
when "update_ar" then self.update_ar(action_hash['params'])
when "reserve" then self.reserve(action_hash['params'])
else
error_msg = "#{action_hash['perform']} action not " <<
" available for this resource"
@@ -59,14 +61,6 @@ module OpenNebulaJSON
end
end
def addleases(params=Hash.new)
super(params['ip'],params['mac'])
end
def rmleases(params=Hash.new)
super(params['ip'])
end
def update(params=Hash.new)
super(params['template_raw'])
end
@@ -90,5 +84,28 @@ module OpenNebulaJSON
def rename(params=Hash.new)
super(params['name'])
end
def rm_ar(params=Hash.new)
super(params['ar_id'])
end
def add_ar(params=Hash.new)
template_json = params['ar_template']
template = template_to_str(template_json)
super(template)
end
def update_ar(params=Hash.new)
template_json = params['ar_template']
template = template_to_str(template_json)
super(template)
end
def reserve(params=Hash.new)
super(params['name'], params['size'], params['ar_id'],
params['addr'], params['vnet'])
end
end
end
+28 -14
View File
@@ -767,20 +767,6 @@ var OpenNebula = {
"unpublish": function(params){
OpenNebula.Action.simple_action(params,OpenNebula.Network.resource,"unpublish");
},
"addleases" : function(params){
var action_obj = params.data.extra_param;
OpenNebula.Action.simple_action(params,
OpenNebula.Network.resource,
"addleases",
action_obj);
},
"rmleases" : function(params){
var action_obj = params.data.extra_param;
OpenNebula.Action.simple_action(params,
OpenNebula.Network.resource,
"rmleases",
action_obj);
},
"hold" : function(params){
var action_obj = params.data.extra_param;
OpenNebula.Action.simple_action(params,
@@ -795,6 +781,34 @@ var OpenNebula = {
"release",
action_obj);
},
"add_ar" : function(params){
var action_obj = {"ar_template" : params.data.extra_param };
OpenNebula.Action.simple_action(params,
OpenNebula.Network.resource,
"add_ar",
action_obj);
},
"rm_ar" : function(params){
var action_obj = params.data.extra_param;
OpenNebula.Action.simple_action(params,
OpenNebula.Network.resource,
"rm_ar",
action_obj);
},
"update_ar": function(params){
var action_obj = {"ar_template" : params.data.extra_param };
OpenNebula.Action.simple_action(params,
OpenNebula.Network.resource,
"update_ar",
action_obj);
},
"reserve": function(params){
var action_obj = params.data.extra_param;
OpenNebula.Action.simple_action(params,
OpenNebula.Network.resource,
"reserve",
action_obj);
},
"update": function(params){
var action_obj = {"template_raw" : params.data.extra_param };
OpenNebula.Action.simple_action(params,
@@ -45,8 +45,8 @@ var vnet_datatable_table_tmpl='<thead>\
<th>'+tr("Owner")+'</th>\
<th>'+tr("Group")+'</th>\
<th>'+tr("Name")+'</th>\
<th>'+tr("Reservation")+'</th>\
<th>'+tr("Cluster")+'</th>\
<th>'+tr("Type")+'</th>\
<th>'+tr("Bridge")+'</th>\
<th>'+tr("Leases")+'</th>\
</tr>\
@@ -687,7 +687,7 @@ var service_actions = {
call: function () {
var tab = dataTable_services.parents(".tab");
if (Sunstone.rightInfoVisible(tab)) {
selected_row_role_id = $($('td.markrowselected',servicerolesDataTable.fnGetNodes())[1]).html();
selected_row_role_id = $($('td.markrowchecked',servicerolesDataTable.fnGetNodes())[1]).html();
checked_row_rolevm_ids = new Array();
if (typeof(serviceroleVMsDataTable) !== 'undefined') {
@@ -1103,13 +1103,13 @@ function updateServiceInfo(request,elem){
if(last_selected_row_role) {
last_selected_row_role.children().each(function(){
$(this).removeClass('markrowselected');
$(this).removeClass('markrowchecked');
});
}
last_selected_row_role = $(this);
$(this).children().each(function(){
$(this).addClass('markrowselected');
$(this).addClass('markrowchecked');
});
}
});
@@ -806,13 +806,13 @@ function updateServiceTemplateInfo(request,elem){
if(last_selected_row_template_role) {
last_selected_row_template_role.children().each(function(){
$(this).removeClass('markrowselected');
$(this).removeClass('markrowchecked');
});
}
last_selected_row_template_role = $(this);
$(this).children().each(function(){
$(this).addClass('markrowselected');
$(this).addClass('markrowchecked');
});
});
});
@@ -1559,8 +1559,8 @@ function generate_nic_tab_content(str_nic_tab_id, str_datatable_id){
'<th>'+tr("Owner")+'</th>'+
'<th>'+tr("Group")+'</th>'+
'<th>'+tr("Name")+'</th>'+
'<th>'+tr("Reservation")+'</th>'+
'<th>'+tr("Cluster")+'</th>'+
'<th>'+tr("Type")+'</th>'+
'<th>'+tr("Bridge")+'</th>'+
'<th>'+tr("Leases")+'</th>'+
'</tr>'+
+1 -1
View File
@@ -2320,7 +2320,7 @@ function printNics(vm_info){
<tr nic_id="'+(nic.NIC_ID)+'">\
<td>' + nic.NIC_ID + '</td>\
<td>' + nic.NETWORK + '</td>\
<td>' + nic.IP + '</td>\
<td>' + (nic.IP ? nic.IP : "--") + '</td>\
<td>' + nic.MAC + '</td>\
<td>' + (nic.IP6_SITE ? nic.IP6_SITE : "--") +'</td>\
<td>' + (nic.IP6_GLOBAL ? nic.IP6_GLOBAL : "--") +'</td>\
File diff suppressed because it is too large. Load diff
+334 -6
View File
@@ -1244,7 +1244,6 @@ function tableCheckboxesListener(dataTable, custom_context){
else
{
$(this).parents('tr').children().removeClass('markrowchecked');
$(this).parents('tr').children().removeClass('markrowselected');
}
recountCheckboxes(datatable, context);
@@ -1254,10 +1253,23 @@ function tableCheckboxesListener(dataTable, custom_context){
// Updates a data_table, with a 2D array containing the new values
// Does a partial redraw, so the filter and pagination are kept
function updateView(item_list,dataTable){
var selected_row_id = $($('td.markrowselected',dataTable.fnGetNodes())[1]).html();
if (!selected_row_id) selected_row_id = $($('td.markrowselected',dataTable.fnGetNodes())[0]).html();
var selected_row_id = null;
var checked_row_ids = new Array();
var row_id_index = dataTable.attr("row_id");
if(row_id_index != undefined){
$.each($(dataTable.fnGetNodes()), function(){
if($('td.markrow',this).length!=0)
{
var aData = dataTable.fnGetData(this);
selected_row_id = aData[row_id_index];
}
});
}
$.each($(dataTable.fnGetNodes()), function(){
if($('td.markrowchecked',this).length!=0)
{
@@ -1293,12 +1305,15 @@ function updateView(item_list,dataTable){
dataTable.fnDraw(true);
};
if(selected_row_id)
if(selected_row_id != undefined)
{
$.each($(dataTable.fnGetNodes()),function(){
if($($('td',this)[1]).html()==selected_row_id)
var aData = dataTable.fnGetData(this);
if(aData[row_id_index] == selected_row_id)
{
$('td',this)[2].click();
$('td',this)[0].click();
}
});
}
@@ -4594,3 +4609,316 @@ function fillAccounting(div, req, response, no_table) {
$("#acct_placeholder", div).hide();
$("#acct_content", div).show();
}
function customTagsHtml(){
return '<div class="row">\
<div class="large-4 columns">\
<input type="text" id="KEY" name="key" />\
</div>\
<div class="large-6 columns">\
<input type="text" id="VALUE" name="value" />\
</div>\
<div class="large-2 columns">\
<button type="button" class="button secondary small radius" id="add_custom">'+tr("Add")+'</button>\
</div>\
</div>\
<div class="row">\
<div class="large-12 columns">\
<table id="custom_tags" class="dataTable policies_table">\
<thead>\
<tr>\
<th>'+tr("KEY")+'</th>\
<th>'+tr("VALUE")+'</th>\
<th></th>\
</tr>\
</thead>\
<tbody id="tbodyinput">\
<tr>\
</tr>\
<tr>\
</tr>\
</tbody>\
</table>\
</div>\
</div>';
}
// div is the container div of customTagsHtml(), eg
// setupCustomTags($("#vnetCreateContextTab", dialog));
function setupCustomTags(div){
$('#add_custom', div).click(function() {
var table = $('#custom_tags', div)[0];
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.id = "KEY";
element1.type = "text";
element1.value = $('input#KEY', div).val()
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.id = "VALUE";
element2.type = "text";
element2.value = $('input#VALUE', div).val()
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = "<i class='fa fa-times-circle fa fa-lg remove-tab'></i>";
});
div.on("click", "i.remove-tab", function() {
$(this).closest("tr").remove()
});
}
// div is the container div of customTagsHtml()
// template_json is where the key:values will be stored
// retrieveCustomTags($('#vnetCreateContextTab', $create_vn_dialog), network_json);
function retrieveCustomTags(div, template_json){
$('#custom_tags tr', div).each(function(){
if ($('#KEY', $(this)).val()) {
template_json[$('#KEY', $(this)).val()] = $('#VALUE', $(this)).val();
}
});
}
// div is the container div of customTagsHtml()
// template_json are the key:values that will be put into the table
function fillCustomTags(div, template_json){
$.each(template_json, function(key, value){
var table = $('#custom_tags', div)[0];
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.id = "KEY";
element1.type = "text";
element1.value = htmlDecode(key);
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.id = "VALUE";
element2.type = "text";
element2.value = htmlDecode(value);
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = "<i class='fa fa-times-circle fa fa-lg remove-tab'></i>";
});
}
// TODO: other types: radio, checkbox
function retrieveWizardFields(dialog, template_json){
var fields = $('[wizard_field]',dialog);
fields.each(function(){
var field = $(this);
if (field.prop('wizard_field_disabled') != true && field.val() != null && field.val().length){
var field_name = field.attr('wizard_field');
template_json[field_name] = field.val();
}
});
}
function generateVNetTableSelect(context_id){
var columns = [
"",
tr("ID"),
tr("Owner"),
tr("Group"),
tr("Name"),
tr("Reservation"),
tr("Cluster"),
tr("Bridge"),
tr("Leases")
];
var options = {
"id_index": 1,
"name_index": 4,
"select_resource": tr("Please select a network from the list"),
"you_selected": tr("You selected the following network:")
};
return generateResourceTableSelect(context_id, columns, options);
}
function setupVNetTableSelect(section, context_id, opts){
var bVisible = opts.bVisible;
if(opts == undefined){
opts = {};
}
if(opts.bVisible == undefined){
// Use the settings in the conf, but removing the checkbox
var config = Config.tabTableColumns('vnets-tab');
var i = config.indexOf(0);
if(i != -1){
config.splice(i,1);
}
opts.bVisible = config;
}
var options = {
"dataTable_options": {
"bAutoWidth":false,
"iDisplayLength": 4,
"sDom" : '<"H">t<"F"p>',
"bRetrieve": true,
"bSortClasses" : false,
"bDeferRender": true,
"aoColumnDefs": [
{ "sWidth": "35px", "aTargets": [0,1] },
{ "bVisible": true, "aTargets": opts.bVisible},
{ "bVisible": false, "aTargets": ['_all']}
]
},
"id_index": 1,
"name_index": 4,
"update_fn": function(datatable){
OpenNebula.Network.list({
timeout: true,
success: function (request, networks_list){
var network_list_array = [];
$.each(networks_list,function(){
var add = true;
if(opts.filter_fn){
add = opts.filter_fn(this.VNET);
}
if(add){
network_list_array.push(vNetworkElementArray(this));
}
});
updateView(network_list_array, datatable);
},
error: onError
});
}
};
return setupResourceTableSelect(section, context_id, options);
}
function generateResourceTableSelect(context_id, columns, options){
if (!options.select_resource){
options.select_resource = tr("Please select a resource from the list");
}
if (!options.you_selected){
options.you_selected = tr("You selected the following resource:");
}
if (options.id_index == undefined){
options.id_index = 0;
}
var thead = '<thead><tr>';
$.each(columns, function(){
thead += '<th>'+this+'</th>'
});
thead += '</tr></thead>';
var html =
'<div class="row">\
<div class="large-8 columns">\
<button id="refresh_button_'+context_id+'" type="button" class="button small radius secondary"><i class="fa fa-refresh" /></button>\
</div>\
<div class="large-4 columns">\
<input id="'+context_id+'_search" class="search" type="text" placeholder="'+tr("Search")+'"/>\
</div>\
</div>\
<div class="row">\
<div class="large-12 columns">\
<table id="datatable_'+context_id+'" class="datatable twelve" row_id="'+options.id_index+'">\
'+thead+'\
<tbody id="tbody_datatable_'+context_id+'">\
</tbody>\
</table>\
</div>\
</div>\
<div class="row">\
<div class="large-12 columns">\
<span id="select_resource_'+context_id+'" class="radius secondary label">'+options.select_resource+'</span>\
<span id="selected_resource_'+context_id+'" class="radius secondary label" style="display: none;">'+options.you_selected+'</span>\
<input id="selected_resource_id_'+context_id+'" type="text"/>\
<span id="selected_resource_name_'+context_id+'" class="radius label" type="text"></span>\
</div>\
</div>';
return html;
}
function setupResourceTableSelect(section, context_id, options) {
if (options.id_index == undefined){
options.id_index = 0;
}
if (options.name_index == undefined){
options.name_index = 1;
}
var dataTable_select = $('#datatable_'+context_id, section).dataTable(options.dataTable_options);
$('#refresh_button_'+context_id).die();
$('#refresh_button_'+context_id).live('click', function(){
options.update_fn($('table[id=datatable_'+context_id+']').dataTable());
});
$('#'+context_id+'_search', section).keyup(function(){
dataTable_select.fnFilter( $(this).val() );
})
dataTable_select.fnSort( [ [options.id_index, config['user_config']['table_order']] ] );
$('#selected_resource_id_'+context_id, section).hide();
$('#selected_resource_name_'+context_id, section).hide();
$('#datatable_'+context_id+' tbody', section).delegate("tr", "click", function(e){
dataTable_select.unbind("draw");
var aData = dataTable_select.fnGetData(this);
$("td.markrow", dataTable_select).removeClass('markrow');
$('tbody input.check_item', dataTable_select).removeAttr('checked');
$('#selected_resource_'+context_id, section).show();
$('#select_resource_'+context_id, section).hide();
$('.alert-box', section).hide();
$("td", this).addClass('markrow');
$('input.check_item', this).attr('checked','checked');
$('#selected_resource_id_'+context_id, section).val(aData[options.id_index]);
$('#selected_resource_id_'+context_id, section).hide();
$('#selected_resource_name_'+context_id, section).text(aData[options.name_index]);
$('#selected_resource_name_'+context_id, section).show();
return true;
});
setupTips(section);
}
+1 -1
View File
@@ -28,7 +28,7 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 37
#define YY_FLEX_SUBMINOR_VERSION 39
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+16
View File
@@ -413,5 +413,21 @@ int User::get_umask() const
return (umask & 0777);
}
int User::get_default_umask()
{
string umask_st;
int umask;
istringstream iss;
Nebula::instance().get_configuration_attribute("DEFAULT_UMASK",umask_st);
iss.str(umask_st);
iss >> oct >> umask;
return (umask & 0777);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
+28 -9
View File
@@ -419,7 +419,8 @@ bool UserPool::authenticate_internal(User * user,
int& group_id,
string& uname,
string& gname,
set<int>& group_ids)
set<int>& group_ids,
int& umask)
{
bool result = false;
@@ -440,13 +441,15 @@ bool UserPool::authenticate_internal(User * user,
group_ids = user->get_groups();
uname = user->name;
gname = user->gname;
uname = user->name;
gname = user->gname;
auth_driver = user->auth_driver;
result = user->valid_session(token);
umask = user->get_umask();
user->unlock();
if (result)
@@ -523,6 +526,8 @@ auth_failure:
uname = "";
gname = "";
umask = 0;
return false;
}
@@ -535,7 +540,8 @@ bool UserPool::authenticate_server(User * user,
int& group_id,
string& uname,
string& gname,
set<int>& group_ids)
set<int>& group_ids,
int& umask)
{
bool result = false;
@@ -585,6 +591,8 @@ bool UserPool::authenticate_server(User * user,
result = user->valid_session(second_token);
umask = user->get_umask();
user->unlock();
if (result)
@@ -654,6 +662,8 @@ auth_failure:
uname = "";
gname = "";
umask = 0;
return false;
}
@@ -666,7 +676,8 @@ bool UserPool::authenticate_external(const string& username,
int& group_id,
string& uname,
string& gname,
set<int>& group_ids)
set<int>& group_ids,
int& umask)
{
ostringstream oss;
istringstream is;
@@ -741,6 +752,8 @@ bool UserPool::authenticate_external(const string& username,
uname = mad_name;
gname = GroupPool::USERS_NAME;
umask = User::get_default_umask();
return true;
auth_failure_user:
@@ -770,6 +783,8 @@ auth_failure:
uname = "";
gname = "";
umask = 0;
return false;
}
@@ -781,7 +796,8 @@ bool UserPool::authenticate(const string& session,
int& group_id,
string& uname,
string& gname,
set<int>& group_ids)
set<int>& group_ids,
int& umask)
{
User * user = 0;
string username;
@@ -805,16 +821,19 @@ bool UserPool::authenticate(const string& session,
if ( fnmatch(UserPool::SERVER_AUTH, driver.c_str(), 0) == 0 )
{
ar = authenticate_server(user,token,user_id,group_id,uname,gname,group_ids);
ar = authenticate_server(user, token, user_id, group_id, uname,
gname, group_ids, umask);
}
else
{
ar = authenticate_internal(user,token,user_id,group_id,uname,gname,group_ids);
ar = authenticate_internal(user, token, user_id, group_id, uname,
gname, group_ids, umask);
}
}
else
{
ar = authenticate_external(username,token,user_id,group_id,uname,gname,group_ids);
ar = authenticate_external(username, token, user_id, group_id, uname,
gname, group_ids, umask);
}
return ar;
+9 -15
View File
@@ -716,12 +716,6 @@ int VirtualMachine::parse_context(string& error_str)
var.str(""); val.str("");
var << "ETH" << nic_id << "_GATEWAY";
val << "$NETWORK[GATEWAY, NETWORK=\"" << name << "\"]";
context->replace(var.str(), val.str());
var.str(""); val.str("");
var << "ETH" << nic_id << "_DNS";
val << "$NETWORK[DNS, NETWORK=\"" << name << "\"]";
context->replace(var.str(), val.str());
@@ -2601,21 +2595,23 @@ int VirtualMachine::release_network_leases(VectorAttribute const * nic, int vmid
VirtualNetwork* vn;
int vnid;
string ip;
int ar_id;
string mac;
if ( nic == 0 )
{
return -1;
}
if ( nic->vector_value("NETWORK_ID", vnid) != 0 )
if (nic->vector_value("NETWORK_ID", vnid) != 0 ||
nic->vector_value("AR_ID", ar_id) != 0)
{
return -1;
}
ip = nic->vector_value("IP");
mac = nic->vector_value("MAC");
if ( ip.empty() )
if (mac.empty())
{
return -1;
}
@@ -2627,11 +2623,9 @@ int VirtualMachine::release_network_leases(VectorAttribute const * nic, int vmid
return -1;
}
if (vn->is_owner(ip,vmid))
{
vn->release_lease(ip);
vnpool->update(vn);
}
vn->free_addr(ar_id, vmid, mac);
vnpool->update(vn);
vn->unlock();
+1 -1
View File
@@ -28,7 +28,7 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 37
#define YY_FLEX_SUBMINOR_VERSION 39
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+8 -8
View File
@@ -223,7 +223,7 @@ void get_network_attribute(VirtualMachine * vm,
VirtualNetworkPool * vnpool = nd.get_vnpool();
VirtualNetwork * vn;
int vnet_id = -1;
int ar_id, vnet_id = -1;
int num;
vector<const Attribute *> attrs;
@@ -253,12 +253,12 @@ void get_network_attribute(VirtualMachine * vm,
if ( net->vector_value(net_name.c_str()) == net_value )
{
string vnet_id_str = net->vector_value("NETWORK_ID");
istringstream iss(vnet_id_str);
if (net->vector_value("NETWORK_ID", vnet_id) != 0)
{
vnet_id = -1;
}
iss >> vnet_id;
if (iss.fail())
if (net->vector_value("AR_ID", ar_id) != 0)
{
vnet_id = -1;
}
@@ -288,7 +288,7 @@ void get_network_attribute(VirtualMachine * vm,
}
else
{
vn->get_template_attribute(attr_name.c_str(),attr_value);
vn->get_template_attribute(attr_name.c_str(), attr_value, ar_id);
}
vn->unlock();
@@ -361,7 +361,7 @@ void insert_single(VirtualMachine * vm,
parsed << vm->get_name();
}
else
else
{
vm->get_template_attribute(name.c_str(),value);
-1
View File
@@ -87,5 +87,4 @@ struct YYLTYPE
# define YYLTYPE_IS_DECLARED 1
# define YYLTYPE_IS_TRIVIAL 1
#endif
#endif /* !YY_VM_VAR_VM_VAR_SYNTAX_HH_INCLUDED */
+8 -8
View File
@@ -168,7 +168,7 @@ void get_network_attribute(VirtualMachine * vm,
VirtualNetworkPool * vnpool = nd.get_vnpool();
VirtualNetwork * vn;
int vnet_id = -1;
int ar_id, vnet_id = -1;
int num;
vector<const Attribute *> attrs;
@@ -198,12 +198,12 @@ void get_network_attribute(VirtualMachine * vm,
if ( net->vector_value(net_name.c_str()) == net_value )
{
string vnet_id_str = net->vector_value("NETWORK_ID");
istringstream iss(vnet_id_str);
if (net->vector_value("NETWORK_ID", vnet_id) != 0)
{
vnet_id = -1;
}
iss >> vnet_id;
if (iss.fail())
if (net->vector_value("AR_ID", ar_id) != 0)
{
vnet_id = -1;
}
@@ -233,7 +233,7 @@ void get_network_attribute(VirtualMachine * vm,
}
else
{
vn->get_template_attribute(attr_name.c_str(),attr_value);
vn->get_template_attribute(attr_name.c_str(), attr_value, ar_id);
}
vn->unlock();
@@ -306,7 +306,7 @@ void insert_single(VirtualMachine * vm,
parsed << vm->get_name();
}
else
else
{
vm->get_template_attribute(name.c_str(),value);
File diff suppressed because it is too large. Load diff
+672
View File
@@ -0,0 +1,672 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "AddressRangePool.h"
#include "AddressRange.h"
using namespace std;
AddressRangePool::AddressRangePool():ar_template(false,'=',"AR_POOL"),
next_ar(0), used_addr(0){};
AddressRangePool::~AddressRangePool()
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
delete it->second;
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::from_vattr(VectorAttribute* va, string& error_msg)
{
AddressRange * ar = new AddressRange(next_ar);
if (ar->from_vattr(va, error_msg) != 0)
{
delete ar;
return -1;
}
ar_pool.insert(make_pair(next_ar++, ar));
ar_template.set(va);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
AddressRange * AddressRangePool::allocate_ar()
{
return new AddressRange(next_ar++);
}
/* -------------------------------------------------------------------------- */
int AddressRangePool::add_ar(AddressRange * ar)
{
pair<map<unsigned int, AddressRange *>::iterator, bool> rc;
rc = ar_pool.insert(make_pair(ar->ar_id(), ar));
if (rc.second == false)
{
return -1;
}
ar_template.set(ar->attr);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::update_ar(vector<Attribute *> ars, string& error_msg)
{
vector<Attribute *>::iterator it;
map<unsigned int, AddressRange *>::iterator ar_it;
unsigned int arid;
for (it = ars.begin(); it != ars.end(); it++)
{
VectorAttribute * va = dynamic_cast<VectorAttribute *>(*it);
if (va == 0)
{
continue;
}
if (va->vector_value("AR_ID", arid) != 0)
{
error_msg = "AR/AR_ID attribute is missing.";
return -1;
}
ar_it = ar_pool.find(arid);
if (ar_it == ar_pool.end())
{
ostringstream oss;
oss << "Address Range with ID " << arid << " was not found.";
error_msg = oss.str();
return -1;
}
return ar_it->second->update_attributes(va, error_msg);
}
error_msg = "Wrong AR definition. AR vector attribute is missing.";
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::from_xml_node(const xmlNodePtr node)
{
int rc = ar_template.from_xml_node(node);
if (rc != 0)
{
return -1;
}
vector<Attribute*> var;
int num_ar = ar_template.get("AR", var);
for (int i = 0; i < num_ar; i++)
{
VectorAttribute * va = static_cast<VectorAttribute *>(var[i]);
AddressRange * ar = new AddressRange(0);
if (ar->from_vattr_db(va)!= 0)
{
return -1;
}
ar_pool.insert(make_pair(ar->ar_id(), ar));
if (ar->ar_id() >= next_ar)
{
next_ar = ar->ar_id() + 1;
}
used_addr += ar->get_used_addr();
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::rm_ar(unsigned int ar_id, string& error_msg)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(ar_id);
if (it == ar_pool.end())
{
error_msg = "Address Range does not exist";
return -1;
}
if (it->second->get_used_addr() > 0)
{
error_msg = "Address Range has leases in use";
return -1;
}
AddressRange * ar_ptr = it->second;
ar_pool.erase(it);
delete ar_ptr;
vector<Attribute*> ars;
vector<Attribute*>::iterator it_ar;
Attribute * the_ar = 0;
unsigned int ar_id_templ;
ar_template.get("AR", ars);
for (it_ar=ars.begin(); it_ar!=ars.end(); it_ar++)
{
VectorAttribute *ar = dynamic_cast<VectorAttribute *>(*it_ar);
if (ar == 0)
{
continue;
}
if ((ar->vector_value("AR_ID",ar_id_templ)==0) && (ar_id_templ==ar_id))
{
the_ar = ar;
break;
}
}
if (the_ar != 0)
{
delete ar_template.remove(the_ar);
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& AddressRangePool::to_xml(string& sstream, bool extended) const
{
if (extended)
{
ostringstream oss;
map<unsigned int, AddressRange *>::const_iterator it;
oss << "<AR_POOL>";
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
it->second->to_xml(oss);
}
oss << "</AR_POOL>";
sstream = oss.str();
return sstream;
}
return ar_template.to_xml(sstream);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::allocate_addr(PoolObjectSQL::ObjectType ot, int obid,
VectorAttribute * nic, const vector<string> &inherit)
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->allocate_addr(ot, obid, nic, inherit) == 0)
{
used_addr++;
return 0;
}
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::allocate_by_mac(const string &mac,
PoolObjectSQL::ObjectType ot, int obid, VectorAttribute * nic,
const vector<string> &inherit)
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->allocate_by_mac(mac, ot, obid, nic, inherit) == 0)
{
used_addr++;
return 0;
}
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::allocate_by_ip(const string &ip,
PoolObjectSQL::ObjectType ot, int obid, VectorAttribute * nic,
const vector<string> &inherit)
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->allocate_by_ip(ip, ot, obid, nic, inherit) == 0)
{
used_addr++;
return 0;
}
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AddressRangePool::free_addr(unsigned int arid, PoolObjectSQL::ObjectType ot,
int obid, const string& mac)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(arid);
if (it!=ar_pool.end())
{
if ( it->second->free_addr(ot, obid, mac) == 0 )
{
used_addr--;
}
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AddressRangePool::free_addr_by_ip(unsigned int arid,
PoolObjectSQL::ObjectType ot, int obid, const string& ip)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(arid);
if (it!=ar_pool.end())
{
if ( it->second->free_addr_by_ip(ot, obid, ip) == 0 )
{
used_addr--;
}
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AddressRangePool::free_addr(PoolObjectSQL::ObjectType ot, int obid,
const string& mac_s)
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->free_addr(ot, obid, mac_s) == 0)
{
used_addr--;
}
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AddressRangePool::free_addr_by_ip(PoolObjectSQL::ObjectType ot, int obid,
const string& ip_s)
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->free_addr_by_ip(ot, obid, ip_s) == 0)
{
used_addr--;
}
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::free_addr_by_owner(PoolObjectSQL::ObjectType ot, int oid)
{
map<unsigned int, AddressRange *>::iterator it;
unsigned int used_addr_ini = used_addr;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
used_addr -= it->second->free_addr_by_owner(ot, oid);
}
return used_addr_ini - used_addr;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::free_addr_by_range(unsigned int arid,
PoolObjectSQL::ObjectType ot, int obid, const string& mac, unsigned int rsize)
{
map<unsigned int, AddressRange *>::iterator it;
unsigned int freed = 0;
it = ar_pool.find(arid);
if (it!=ar_pool.end())
{
freed = it->second->free_addr_by_range(ot, obid, mac, rsize);
used_addr -= freed;
}
return freed;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void AddressRangePool::get_attribute(const char * name, string& value,
int ar_id) const
{
map<unsigned int, AddressRange *>::const_iterator it = ar_pool.find(ar_id);
value.clear();
if (it!=ar_pool.end())
{
value = it->second->get_attribute(name);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::get_attribute(const char * name, int& value,
int ar_id) const
{
map<unsigned int, AddressRange *>::const_iterator it = ar_pool.find(ar_id);
int rc = -1;
if (it!=ar_pool.end())
{
rc = it->second->get_attribute(name, value);
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::get_ar_parent(int ar_id) const
{
int rc;
if (get_attribute("PARENT_NETWORK_AR_ID", rc, ar_id) != 0)
{
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
unsigned int AddressRangePool::get_size() const
{
map<unsigned int, AddressRange *>::const_iterator it;
unsigned int total = 0;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
total += it->second->get_size();
}
return total;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::hold_by_ip(unsigned int ar_id, const string& ip_s)
{
map<unsigned int, AddressRange *>::const_iterator it;
it = ar_pool.find(ar_id);
if (it == ar_pool.end())
{
return -1;
}
int rc = it->second->hold_by_ip(ip_s);
if (rc == 0)
{
used_addr++;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::hold_by_ip(const string& ip_s)
{
map<unsigned int, AddressRange *>::iterator it;
int rc = -1;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->hold_by_ip(ip_s) == 0) //At least one AR hold the IP
{
used_addr++;
rc = 0;
}
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::hold_by_mac(unsigned int ar_id, const string& mac_s)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(ar_id);
if (it == ar_pool.end())
{
return -1;
}
int rc = it->second->hold_by_mac(mac_s);
if (rc == 0)
{
used_addr++;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::hold_by_mac(const string& mac_s)
{
map<unsigned int, AddressRange *>::iterator it;
int rc = -1;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if (it->second->hold_by_mac(mac_s) == 0) //At least one AR hold the IP
{
used_addr++;
rc = 0;
}
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::reserve_addr(int vid, unsigned int rsize,
AddressRange *rar)
{
map<unsigned int, AddressRange *>::iterator it;
for (it=ar_pool.begin(); it!=ar_pool.end(); it++)
{
if ((it->second->get_free_addr() >= rsize) &&
(it->second->reserve_addr(vid, rsize, rar) == 0))
{
used_addr += rsize;
return 0;
}
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::reserve_addr(int vid, unsigned int rsize,
unsigned int ar_id, AddressRange *rar)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(ar_id);
if (it == ar_pool.end())
{
return -1;
}
if ((it->second->get_free_addr() >= rsize) &&
(it->second->reserve_addr(vid, rsize, rar) == 0))
{
used_addr += rsize;
return 0;
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::reserve_addr_by_ip(int vid, unsigned int rsize,
unsigned int ar_id, const string& ip, AddressRange *rar)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(ar_id);
if (it == ar_pool.end())
{
return -1;
}
if (it->second->reserve_addr_by_ip(vid, rsize, ip, rar) == 0)
{
used_addr += rsize;
return 0;
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int AddressRangePool::reserve_addr_by_mac(int vid, unsigned int rsize,
unsigned int ar_id, const string& mac, AddressRange *rar)
{
map<unsigned int, AddressRange *>::iterator it;
it = ar_pool.find(ar_id);
if (it == ar_pool.end())
{
return -1;
}
if (it->second->reserve_addr_by_mac(vid, rsize, mac, rar) == 0)
{
used_addr += rsize;
return 0;
}
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
-469
View File
@@ -1,469 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "FixedLeases.h"
#include "NebulaLog.h"
#include <string.h>
FixedLeases::FixedLeases(
SqlDB * db,
int _oid,
unsigned int _mac_prefix,
unsigned int _global[],
unsigned int _site[],
vector<const Attribute*>& vector_leases):
Leases(db,_oid,0,_mac_prefix, _global, _site), current(leases.begin())
{
const VectorAttribute * single_attr_lease;
string _mac;
string _ip;
string error_msg;
for (unsigned long i=0; i < vector_leases.size() ;i++)
{
single_attr_lease = dynamic_cast<const VectorAttribute *>
(vector_leases[i]);
if( single_attr_lease )
{
_ip = single_attr_lease->vector_value("IP");
_mac = single_attr_lease->vector_value("MAC");
if( add(_ip,_mac,-1,error_msg,false) != 0 )
{
NebulaLog::log("VNM", Log::ERROR, error_msg);
}
}
}
size = leases.size();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::add(const string& ip, const string& mac, int vid,
string& error_msg, bool used)
{
ostringstream oss;
unsigned int _ip;
unsigned int _mac [2];
Lease * lease;
string xml_body;
char * sql_xml;
int rc;
if (ip.empty() && mac.empty())
{
goto error_no_ip_mac;
}
//Set IP & MAC addresses if provided
if (!ip.empty())
{
if ( Leases::Lease::ip_to_number(ip,_ip) )
{
goto error_ip;
}
}
if (!mac.empty())
{
if (Leases::Lease::mac_to_number(mac,_mac))
{
goto error_mac;
}
}
//Generate IP from MAC (or viceversa)
if (ip.empty())
{
_ip = _mac[0];
}
if (mac.empty())
{
_mac[1] = mac_prefix;
_mac[0] = _ip;
}
//Check for duplicates
if ( leases.count(_ip) > 0 )
{
goto error_duplicate;
}
lease = new Lease(_ip,_mac,vid,used);
sql_xml = db->escape_str(lease->to_xml_db(xml_body).c_str());
if ( sql_xml == 0 )
{
goto error_body;
}
oss << "INSERT INTO " << table << " ("<< db_names <<") VALUES ("
<< oid << ","
<< _ip << ","
<< "'" << sql_xml << "')";
db->free_str(sql_xml);
rc = db->exec(oss);
if ( rc != 0 )
{
goto error_db;
}
leases.insert( make_pair(_ip,lease) );
if(lease->used)
{
n_used++;
}
current = leases.begin();
return rc;
error_no_ip_mac:
oss << "Both IP and MAC cannot be empty";
goto error_common;
error_ip:
oss << "Error inserting lease, malformed IP = " << ip;
goto error_common;
error_mac:
oss << "Error inserting lease, malformed MAC = " << mac;
goto error_common;
error_duplicate:
oss << "Error inserting lease, IP " << ip << " already exists";
goto error_common;
error_body:
oss << "Error inserting lease, marshall error";
delete lease;
goto error_common;
error_db:
oss.str("");
oss << "Error inserting lease in database.";
delete lease;
error_common:
NebulaLog::log("VNM", Log::ERROR, oss);
error_msg = oss.str();
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::remove(const string& ip, string& error_msg)
{
map<unsigned int,Lease *>::iterator it;
ostringstream oss;
unsigned int _ip;
int rc;
if( Leases::Lease::ip_to_number(ip,_ip) )
{
goto error_ip;
}
it = leases.find(_ip);
if (it == leases.end()) //it does not exist in the net
{
goto error_notfound;
}
if (it->second->used && it->second->vid != -1) //it is in use by VM
{
goto error_used;
}
oss << "DELETE FROM " << table << " WHERE (oid=" << oid
<< " AND ip=" << _ip << ")";
rc = db->exec(oss);
if ( rc != 0 )
{
goto error_db;
}
delete it->second;
leases.erase(it);
current = leases.begin();
return rc;
error_ip:
oss.str("");
oss << "Error deleting lease, malformed IP = " << ip;
goto error_common;
error_notfound:
oss.str("");
oss << "Error deleting lease, IP " << ip << " is not part of NET " << oid;
goto error_common;
error_used:
oss.str("");
oss << "Error deleting lease, IP " << ip << " is currently in use";
goto error_common;
error_db:
oss.str("");
oss << "Error inserting lease in database.";
error_common:
NebulaLog::log("VNM", Log::ERROR, oss);
error_msg = oss.str();
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::unset(const string& ip)
{
unsigned int _ip;
map<unsigned int, Lease *>::iterator it_ip;
if ( Leases::Lease::ip_to_number(ip,_ip) )
{
return 0; //Wrong format, not leased
}
it_ip = leases.find(_ip);
if (it_ip == leases.end())
{
return 0; //Not in the map, not leased
}
// Flip used flag to false
it_ip->second->used = false;
it_ip->second->vid = -1;
// Update the lease
return update_lease(it_ip->second);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::get(int vid, string& ip, string& mac, unsigned int eui64[])
{
int rc = -1;
if (leases.empty())
{
return -1;
}
for(unsigned int i=0 ;i<size; i++,current++)
{
if (current == leases.end())
{
current = leases.begin();
}
if (current->second->used == false)
{
ostringstream oss;
current->second->used = true;
current->second->vid = vid;
rc = update_lease(current->second);
Leases::Lease::mac_to_string(current->second->mac, mac);
Leases::Lease::ip_to_string(current->second->ip, ip);
eui64[0] = current->second->eui64[0];
eui64[1] = current->second->eui64[1];
current++;
break;
}
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::set(int vid, const string& ip, string& mac, unsigned int eui64[])
{
map<unsigned int,Lease *>::iterator it;
unsigned int num_ip;
int rc;
rc = Leases::Lease::ip_to_number(ip,num_ip);
if (rc != 0)
{
return -1;
}
it=leases.find(num_ip);
if (it == leases.end()) //it does not exist in the net
{
return -1;
}
else if (it->second->used) //it is in use
{
return -1;
}
it->second->used = true;
it->second->vid = vid;
Leases::Lease::mac_to_string(it->second->mac,mac);
eui64[0] = it->second->eui64[0];
eui64[1] = it->second->eui64[1];
return update_lease(it->second);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::update_lease(Lease * lease)
{
ostringstream oss;
string xml_body;
char * sql_xml;
sql_xml = db->escape_str(lease->to_xml_db(xml_body).c_str());
if ( sql_xml == 0 )
{
return -1;
}
if( lease->used )
{
n_used++;
}
else
{
n_used--;
}
oss << "UPDATE " << table << " SET body='" << sql_xml << "'"
<< " WHERE oid=" << oid << " AND ip='" << lease->ip <<"'";
db->free_str(sql_xml);
return db->exec(oss);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::add_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
int rc = -1;
string _mac;
string _ip;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if( single_attr_lease != 0 )
{
_ip = single_attr_lease->vector_value("IP");
_mac = single_attr_lease->vector_value("MAC");
rc = add(_ip, _mac, -1, error_msg, false);
if( rc == 0 )
{
size = leases.size();
}
}
else
{
error_msg = "Empty lease description.";
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FixedLeases::remove_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
int rc = -1;
string _ip;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if( single_attr_lease != 0 )
{
_ip = single_attr_lease->vector_value("IP");
rc = remove(_ip, error_msg);
if( rc == 0 )
{
size = leases.size();
}
}
else
{
error_msg = "Empty lease description.";
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
-632
View File
@@ -1,632 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "Leases.h"
#include "NebulaLog.h"
#include <arpa/inet.h>
/* ************************************************************************** */
/* ************************************************************************** */
/* Lease class */
/* ************************************************************************** */
/* ************************************************************************** */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::ip_to_number(const string& _ip, unsigned int& i_ip)
{
istringstream iss;
size_t pos=0;
int count = 0;
unsigned int tmp;
string ip = _ip;
while ( (pos = ip.find('.')) != string::npos )
{
ip.replace(pos,1," ");
count++;
}
if (count != 3)
{
return -1;
}
iss.str(ip);
i_ip = 0;
for (int i=0;i<4;i++)
{
iss >> dec >> tmp >> ws;
if ( tmp > 255 )
{
return -1;
}
i_ip <<= 8;
i_ip += tmp;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::ip_to_string(const unsigned int i_ip, string& ip)
{
unsigned int temp_byte;
ostringstream oss;
// Convert the IP from unsigned int to string
for (int index=0;index<4;index++)
{
temp_byte = i_ip;
temp_byte >>= (24-index*8);
temp_byte &= 255;
oss << temp_byte;
if(index!=3)
{
oss << ".";
}
}
ip = oss.str();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::ip6_to_string(const unsigned int eui64[],
const unsigned int prefix[],
string& ip6s)
{
struct in6_addr ip6;
char dst[INET6_ADDRSTRLEN];
ip6.s6_addr32[2] = htonl(eui64[1]);
ip6.s6_addr32[3] = htonl(eui64[0]);
// global or site unicast address
if (prefix[1] != 0 || prefix[0] != 0 )
{
ip6.s6_addr32[0] = htonl(prefix[1]);
ip6.s6_addr32[1] = htonl(prefix[0]);
}
else // link local address
{
ip6.s6_addr32[0] = htonl(0xfe800000);
ip6.s6_addr32[1] = 0;
}
if ( inet_ntop(AF_INET6, &ip6, dst, INET6_ADDRSTRLEN) != 0 )
{
ip6s = dst;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::mac_to_number(const string& _mac, unsigned int i_mac[])
{
istringstream iss;
size_t pos=0;
int count = 0;
unsigned int tmp;
string mac = _mac;
while ( (pos = mac.find(':')) != string::npos )
{
mac.replace(pos,1," ");
count++;
}
if (count != 5)
{
return -1;
}
iss.str(mac);
i_mac[1] = 0;
i_mac[0] = 0;
iss >> hex >> i_mac[1] >> ws >> hex >> tmp >> ws;
i_mac[1] <<= 8;
i_mac[1] += tmp;
for (int i=0;i<4;i++)
{
iss >> hex >> tmp >> ws;
i_mac[0] <<= 8;
i_mac[0] += tmp;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::prefix6_to_number(const string& prefix, unsigned int ip[])
{
struct in6_addr s6;
if (prefix.empty())
{
ip[1] = ip[0] = 0;
return 0;
}
int rc = inet_pton(AF_INET6, prefix.c_str(), &s6);
if ( rc != 1 )
{
return -1;
}
ip[1] = ntohl(s6.s6_addr32[0]);
ip[0] = ntohl(s6.s6_addr32[1]);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::mac_to_eui64(const unsigned int i_mac[], unsigned int eui64[])
{
eui64[1] = ((i_mac[1]+512)<<16) + ((i_mac[0] & 0xFF000000)>>16) + 0x000000FF;
eui64[0] = 4261412864 + (i_mac[0] & 0x00FFFFFF);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::mac_to_string(const unsigned int i_mac[], string& mac)
{
ostringstream oss;
unsigned int temp_byte;
oss.str("");
for (int i=5;i>=0;i--)
{
if ( i < 4 )
{
temp_byte = i_mac[0];
temp_byte >>= i*8;
}
else
{
temp_byte = i_mac[1];
temp_byte >>= (i%4)*8;
}
temp_byte &= 255;
oss.width(2);
oss.fill('0');
oss << hex << temp_byte;
if(i!=0)
{
oss << ":";
}
}
mac = oss.str();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Leases::Lease::to_xml(string& str,
const unsigned int global[],
const unsigned int site[]) const
{
string ip_s;
string ipl_s, ips_s, ipg_s;
string mac_s;
unsigned int tmp_prefix[2] = {0, 0};
ostringstream os;
mac_to_string(mac, mac_s);
ip_to_string(ip, ip_s);
ip6_to_string(eui64, tmp_prefix, ipl_s);
os <<
"<LEASE>" <<
"<MAC>" << mac_s << "</MAC>" <<
"<IP>" << ip_s << "</IP>" <<
"<IP6_LINK>" << ipl_s << "</IP6_LINK>";
if (site[1] != 0 || site[0] != 0 )
{
ip6_to_string(eui64, site, ips_s);
os << "<IP6_SITE>" << ips_s << "</IP6_SITE>";
}
if (global[1] != 0 || global[0] != 0 )
{
ip6_to_string(eui64, global, ipg_s);
os << "<IP6_GLOBAL>" << ipg_s << "</IP6_GLOBAL>";
}
os << "<USED>"<< used << "</USED>"<<
"<VID>" << vid << "</VID>" <<
"</LEASE>";
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Leases::Lease::to_xml_db(string& str) const
{
ostringstream os;
os <<
"<LEASE>" <<
"<IP>" << ip << "</IP>" <<
"<MAC_PREFIX>" << mac[1] << "</MAC_PREFIX>" <<
"<MAC_SUFFIX>" << mac[0] << "</MAC_SUFFIX>" <<
"<USED>" << used << "</USED>"<<
"<VID>" << vid << "</VID>" <<
"</LEASE>";
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::from_xml(const string &xml_str)
{
int rc = 0;
int int_used;
// Initialize the internal XML object
update_from_str(xml_str);
rc += xpath(ip, "/LEASE/IP", 0);
rc += xpath(mac[1], "/LEASE/MAC_PREFIX", 0);
rc += xpath(mac[0], "/LEASE/MAC_SUFFIX", 0);
rc += xpath(int_used, "/LEASE/USED", 0);
rc += xpath(vid, "/LEASE/VID", 0);
used = static_cast<bool>(int_used);
if (rc != 0)
{
return -1;
}
mac_to_eui64(mac, eui64);
return 0;
}
/* ************************************************************************** */
/* ************************************************************************** */
/* Leases class */
/* ************************************************************************** */
/* ************************************************************************** */
const char * Leases::table = "leases";
const char * Leases::db_names = "oid, ip, body";
const char * Leases::db_bootstrap = "CREATE TABLE IF NOT EXISTS leases ("
"oid INTEGER, ip BIGINT, body MEDIUMTEXT, PRIMARY KEY(oid,ip))";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::select_cb(void *nil, int num, char **values, char **names)
{
Lease * lease;
int rc;
if ( (!values[0]) || (num != 1) )
{
return -1;
}
lease = new Lease();
rc = lease->from_xml(values[0]);
if (rc != 0)
{
return -1;
}
leases.insert(make_pair(lease->ip, lease));
if(lease->used)
{
n_used++;
}
return 0;
}
/* -------------------------------------------------------------------------- */
int Leases::select(SqlDB * db)
{
ostringstream oss;
int rc;
// Reset the used leases counter
n_used = 0;
set_callback(static_cast<Callbackable::Callback>(&Leases::select_cb));
oss << "SELECT body FROM " << table << " WHERE oid = " << oid;
rc = db->exec(oss,this);
unset_callback();
if (rc != 0)
{
goto error_id;
}
return 0;
error_id:
oss.str("");
oss << "Error getting leases for network nid: " << oid;
NebulaLog::log("VNM", Log::ERROR, oss);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::drop(SqlDB * db)
{
ostringstream oss;
// Drop all the leases
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
return db->exec(oss);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::insert(SqlDB * db, string& error_str)
{
error_str = "Should not access to Leases.insert().";
NebulaLog::log("VNM", Log::ERROR, error_str);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::update(SqlDB * db)
{
NebulaLog::log("VNM", Log::ERROR, "Should not access to Leases.update()");
return -1;
}
/* ************************************************************************** */
/* Leases :: Interface Methods */
/* ************************************************************************** */
bool Leases::check(const string& ip)
{
unsigned int _ip;
Leases::Lease::ip_to_number(ip,_ip);
return check(_ip);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Leases::check(unsigned int ip)
{
map<unsigned int,Lease *>::iterator it;
it=leases.find(ip);
if (it!=leases.end())
{
return it->second->used;
}
else
{
return false;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Leases::is_owner(const string& ip, int vid)
{
unsigned int _ip;
map<unsigned int,Lease *>::iterator it;
Leases::Lease::ip_to_number(ip,_ip);
it = leases.find(_ip);
if (it!=leases.end())
{
return (it->second->vid == vid);
}
else
{
return false;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::hold_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
int rc;
string ip;
string mac;
unsigned int tmp[2];
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if ( single_attr_lease == 0 )
{
error_msg = "Empty lease description.";
return -1;
}
ip = single_attr_lease->vector_value("IP");
if ( check(ip) )
{
error_msg = "Lease is in use.";
return -1;
}
rc = set(-1, ip, mac, tmp);
if ( rc != 0 )
{
error_msg = "Lease is not part of the NET.";
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::free_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
map<unsigned int,Lease *>::iterator it;
unsigned int i_ip;
string st_ip;
string mac;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if ( single_attr_lease == 0 )
{
error_msg = "Empty lease description.";
return -1;
}
st_ip = single_attr_lease->vector_value("IP");
if ( Leases::Lease::ip_to_number(st_ip,i_ip) != 0 )
{
error_msg = "Wrong Lease format.";
return -1;
}
it = leases.find(i_ip);
if ( it == leases.end() || !it->second->used || it->second->vid != -1 )
{
error_msg = "Lease is not on hold.";
return -1;
}
release(st_ip);
return 0;
}
/* ************************************************************************** */
/* Leases :: Misc */
/* ************************************************************************** */
string& Leases::to_xml(string& xml) const
{
map<unsigned int, Leases::Lease *>::const_iterator it;
ostringstream os;
string lease_xml;
for(it=leases.begin();it!=leases.end();it++)
{
os << it->second->to_xml(lease_xml, global, site);
}
xml = os.str();
return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator<<(ostream& os, Leases& _leases)
{
string xml;
os << _leases.to_xml(xml);
return os;
};
-556
View File
@@ -1,556 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "RangedLeases.h"
#include "Nebula.h"
#include <cmath>
/* ************************************************************************** */
/* Ranged Leases class */
/* ************************************************************************** */
RangedLeases::RangedLeases(
SqlDB * db,
int _oid,
unsigned int _mac_prefix,
unsigned int _global[],
unsigned int _site[],
unsigned int _ip_start,
unsigned int _ip_end):
Leases(db, _oid, 0, _mac_prefix, _global, _site),
ip_start(_ip_start),ip_end(_ip_end),current(0)
{
size = ip_end - ip_start + 1;
}
/* ************************************************************************** */
/* Ranged Leases :: Methods */
/* ************************************************************************** */
static int get_template_size(VirtualNetwork* vn,
unsigned int& host_bits,
unsigned int& size)
{
string st_size = "";
vn->erase_template_attribute("NETWORK_SIZE", st_size);
if ( st_size == "C" || st_size == "c" )
{
host_bits = 8;
size = 256;
}
else if ( st_size == "B" || st_size == "b" )
{
host_bits = 16;
size = 65536;
}
else if ( st_size == "A" || st_size == "a" )
{
host_bits = 24;
size = 16777216;
}
else
{
if (!st_size.empty())//Assume it's a number
{
istringstream iss(st_size);
iss >> size;
if (iss.fail())
{
return -1;
}
}
else
{
size = VirtualNetworkPool::default_size();
}
host_bits = (int) ceil(log(size+2)/log(2));
}
return 0;
}
/* -------------------------------------------------------------------------- */
int RangedLeases::process_template(VirtualNetwork* vn,
unsigned int& ip_start, unsigned int& ip_end, string& error_str)
{
ostringstream oss;
string st_addr = "";
string st_mask = "";
string st_ip_start = "";
string st_ip_end = "";
string st_mac_start = "";
unsigned int host_bits = 0;
unsigned int network_bits;
unsigned int size;
unsigned int net_addr;
unsigned int net_mask;
size_t pos;
unsigned int mac[2];
// -------------------------------------------------------------------------
// Pure IPv6 network definition based on MAC_START and NETWORK_SIZE
// -------------------------------------------------------------------------
vn->erase_template_attribute("MAC_START", st_mac_start);
if (!st_mac_start.empty())
{
if ( Leases::Lease::mac_to_number(st_mac_start, mac) != 0 )
{
goto error_mac_start;
}
ip_start = mac[0];
if (get_template_size(vn, host_bits, size) != 0)
{
goto error_size;
}
ip_end = ip_start + size;
if ( ip_end < ip_start )
{
goto error_greater_mac;
}
vn->remove_template_attribute("IP_START");
vn->remove_template_attribute("IP_END");
vn->remove_template_attribute("NETWORK_ADDRESS");
vn->remove_template_attribute("NETWORK_MASK");
vn->remove_template_attribute("NETWORK_SIZE");
return 0;
}
// -------------------------------------------------------------------------
// Initialize IP_START and IP_END to limit the IP range
// -------------------------------------------------------------------------
ip_start = 0;
ip_end = 0;
vn->erase_template_attribute("IP_START", st_ip_start);
vn->erase_template_attribute("IP_END", st_ip_end);
if ( !st_ip_start.empty() )
{
if ( Leases::Lease::ip_to_number(st_ip_start, ip_start) != 0 )
{
goto error_ip_start;
}
}
if ( !st_ip_end.empty() )
{
if ( Leases::Lease::ip_to_number(st_ip_end, ip_end) != 0 )
{
goto error_ip_end;
}
}
// -------------------------------------------------------------------------
// Check for NETWORK_ADDRESS
// -------------------------------------------------------------------------
vn->get_template_attribute("NETWORK_ADDRESS", st_addr);
if (st_addr.empty())
{
if ( ip_start != 0 && ip_end != 0 ) //Manually range, exit
{
if ( ip_end < ip_start )
{
goto error_greater;
}
return 0;
}
else
{
goto error_addr;
}
}
// -------------------------------------------------------------------------
// Check for NETWORK_SIZE or NETWORK_ADDRESS
// -------------------------------------------------------------------------
pos = st_addr.find("/");
if ( pos != string::npos ) // Check for CIDR network address
{
string st_network_bits;
st_network_bits = st_addr.substr(pos+1);
st_addr = st_addr.substr(0,pos);
istringstream iss(st_network_bits);
iss >> network_bits;
if ( network_bits > 32 )
{
goto error_prefix;
}
host_bits = 32 - network_bits;
}
else // Check for network mask in decimal-dot notation
{
vn->erase_template_attribute("NETWORK_MASK", st_mask);
if ( !st_mask.empty() )
{
// st_mask is in decimal format, e.g. 255.255.0.0
// The number of trailing 0s is needed
if ( Leases::Lease::ip_to_number(st_mask, net_mask) != 0 )
{
goto error_netmask;
}
host_bits = 0;
while ( host_bits < 32 &&
((net_mask >> host_bits) & 1) != 1 )
{
host_bits++;
}
}
else //No network mask, get NETWORK_SIZE
{
if (get_template_size(vn, host_bits, size) != 0)
{
goto error_size;
}
}
}
vn->remove_template_attribute("NETWORK_SIZE");
// -------------------------------------------------------------------------
// Generate NETWORK_MASK
// -------------------------------------------------------------------------
net_mask = 0xFFFFFFFF << host_bits;
Lease::ip_to_string(net_mask, st_mask);
vn->replace_template_attribute("NETWORK_MASK", st_mask);
// -------------------------------------------------------------------------
// Consistency Checks based on the network address, and range
// -------------------------------------------------------------------------
if ( Leases::Lease::ip_to_number(st_addr,net_addr) != 0 )
{
goto error_net_addr;
}
if (net_addr != (net_mask & net_addr) )
{
goto error_not_base_addr;
}
// Set IP start/end
if ( ip_start == 0 )
{
ip_start = net_addr + 1;
}
if ( ip_end == 0 )
{
ip_end = net_addr + (1 << host_bits) - 2;
}
// Check range restrictions
if ( (ip_start & net_mask) != net_addr )
{
goto error_range_ip_start;
}
if ( (ip_end & net_mask) != net_addr )
{
goto error_range_ip_end;
}
if ( ip_end < ip_start )
{
goto error_greater;
}
return 0;
error_mac_start:
oss << "MAC_START " << st_mac_start << " is not a valid MAC.";
goto error_common;
error_ip_start:
oss << "IP_START " << st_ip_start << " is not a valid IP.";
goto error_common;
error_ip_end:
oss << "IP_END " << st_ip_end << " is not a valid IP.";
goto error_common;
error_not_base_addr:
oss << "NETWORK_ADDRESS " << st_addr
<< " is not a base address for the network mask " << st_mask << ".";
goto error_common;
error_net_addr:
oss << "NETWORK_ADDRESS " << st_addr << " is not a valid IP.";
goto error_common;
error_netmask:
oss << "NETWORK_MASK " << st_mask << " is not a valid network mask.";
goto error_common;
error_prefix:
oss << "A CIDR prefix of " << network_bits << " bits is not valid.";
goto error_common;
error_addr:
oss << "No NETWORK_ADDRESS in template for Virtual Network.";
goto error_common;
error_range_ip_start:
oss << "IP_START " << st_ip_start << " is not part of the network "
<< st_addr << "/" << 32-host_bits << ".";
goto error_common;
error_size:
oss << "NETWORK_SIZE is not an integer number.";
goto error_common;
error_range_ip_end:
oss << "IP_END " << st_ip_end << " is not part of the network "
<< st_addr << "/" << 32-host_bits << ".";
goto error_common;
error_greater:
Leases::Lease::ip_to_string(ip_start, st_ip_start);
Leases::Lease::ip_to_string(ip_end, st_ip_end);
oss << "IP_START " << st_ip_start << " cannot be greater than the IP_END "
<< st_ip_end << ".";
goto error_common;
error_greater_mac:
oss << "Size too big, it will overflow MAC address space.";
goto error_common;
error_common:
error_str = oss.str();
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RangedLeases::get(int vid, string& ip, string& mac, unsigned int eui64[])
{
unsigned int num_ip;
int rc = -1;
for ( unsigned int i=0; i<size; i++, current = (current+1)%size )
{
num_ip = ip_start + current;
if (check(num_ip) == false)
{
unsigned int num_mac[2];
num_mac[1] = mac_prefix;
num_mac[0] = num_ip;
Leases::Lease::mac_to_eui64(num_mac, eui64);
rc = add(num_ip,num_mac,vid);
if (rc==0)
{
Leases::Lease::ip_to_string(num_ip,ip);
Leases::Lease::mac_to_string(num_mac,mac);
break;
}
}
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RangedLeases::set(int vid, const string& ip, string& mac, unsigned int eui64[])
{
unsigned int num_ip;
unsigned int num_mac[2];
int rc;
rc = Leases::Lease::ip_to_number(ip,num_ip);
if (rc != 0)
{
return -1;
}
if ( num_ip < ip_start || ip_end < num_ip )
{
return -1;
}
if (check(num_ip) == true)
{
return -1;
}
num_mac[1] = mac_prefix;
num_mac[0] = num_ip;
Leases::Lease::mac_to_eui64(num_mac, eui64);
rc = add(num_ip,num_mac,vid);
if (rc != 0)
{
return -1;
}
Leases::Lease::mac_to_string(num_mac,mac);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RangedLeases::add(
unsigned int ip,
unsigned int mac[],
int vid,
bool used)
{
ostringstream oss;
Lease * lease;
string xml_body;
char * sql_xml;
int rc;
lease = new Lease(ip,mac,vid,used);
sql_xml = db->escape_str(lease->to_xml_db(xml_body).c_str());
if ( sql_xml == 0 )
{
goto error_body;
}
oss << "INSERT INTO " << table << " ("<< db_names <<") VALUES ("
<< oid << ","
<< ip << ","
<< "'" << sql_xml << "')";
db->free_str(sql_xml);
rc = db->exec(oss);
if ( rc != 0 )
{
goto error_db;
}
leases.insert( make_pair(ip,lease) );
n_used++;
return rc;
error_body:
oss.str("");
oss << "Error inserting lease, marshall error";
goto error_common;
error_db:
oss.str("");
oss << "Error inserting lease in database.";
error_common:
NebulaLog::log("VNM", Log::ERROR, oss);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RangedLeases::del(const string& ip)
{
unsigned int _ip;
ostringstream oss;
int rc;
map<unsigned int, Lease *>::iterator it_ip;
// Remove lease from leases map
if ( Lease::ip_to_number(ip,_ip) )
{
return 0;
}
it_ip = leases.find(_ip);
if (it_ip == leases.end())
{
return 0; //Not in the map, not leased
}
// Erase it from DB
oss << "DELETE FROM " << table << " WHERE oid='" << oid
<< "' AND ip='" << _ip << "'";
rc = db->exec(oss);
if ( rc == 0 )
{
n_used--;
delete it_ip->second;
leases.erase(it_ip);
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
+2 -3
View File
@@ -22,11 +22,10 @@ lib_name='nebula_vnm'
# Sources to generate the library
source_files=[
'Leases.cc',
'FixedLeases.cc',
'RangedLeases.cc',
'VirtualNetwork.cc',
'VirtualNetworkPool.cc',
'AddressRange.cc',
'AddressRangePool.cc'
]
# Build library
+431 -394
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -92,6 +92,7 @@ int VirtualNetworkPool::allocate (
const string& uname,
const string& gname,
int umask,
int pvid,
VirtualNetworkTemplate * vn_template,
int * oid,
int cluster_id,
@@ -105,11 +106,11 @@ int VirtualNetworkPool::allocate (
ostringstream oss;
vn = new VirtualNetwork(uid, gid, uname, gname, umask,
vn = new VirtualNetwork(uid, gid, uname, gname, umask, pvid,
cluster_id, cluster_name, vn_template);
// Check name
vn->get_template_attribute("NAME", name);
vn->PoolObjectSQL::get_template_attribute("NAME", name);
if ( !PoolObjectSQL::name_is_valid(name, error_str) )
{
+1 -1
View File
@@ -28,7 +28,7 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 37
#define YY_FLEX_SUBMINOR_VERSION 39
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif