diff --git a/include/AddressRange.h b/include/AddressRange.h new file mode 100644 index 0000000000..2e6ad9308e --- /dev/null +++ b/include/AddressRange.h @@ -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 +#include +#include + +#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 &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 &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 &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 &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& 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 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 restricted_attributes; +}; + +#endif diff --git a/include/AddressRangePool.h b/include/AddressRangePool.h new file mode 100644 index 0000000000..448d28adc0 --- /dev/null +++ b/include/AddressRangePool.h @@ -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 +#include +#include + +#include + +#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 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 &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 &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 &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 ar_pool; + + /** + * Used addresses + */ + unsigned int used_addr; +}; + +#endif diff --git a/include/Attribute.h b/include/Attribute.h index 174612a6c4..23ad9af95d 100644 --- a/include/Attribute.h +++ b/include/Attribute.h @@ -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; diff --git a/include/Datastore.h b/include/Datastore.h index d18b404dd3..fe2cc717f7 100644 --- a/include/Datastore.h +++ b/include/Datastore.h @@ -265,7 +265,7 @@ private: int cluster_id, const string& cluster_name); - virtual ~Datastore(){}; + virtual ~Datastore(); // ************************************************************************* // DataBase implementation (Private) diff --git a/include/FixedLeases.h b/include/FixedLeases.h deleted file mode 100644 index dae1e947a0..0000000000 --- a/include/FixedLeases.h +++ /dev/null @@ -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 = "", 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& 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& 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& 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::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_*/ diff --git a/include/Leases.h b/include/Leases.h deleted file mode 100644 index d5760ad112..0000000000 --- a/include/Leases.h +++ /dev/null @@ -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 -#include -#include - -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::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& 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& 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& 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& 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 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_*/ - diff --git a/include/PoolObjectSQL.h b/include/PoolObjectSQL.h index 95df3c94fa..f51fd7e7d3 100644 --- a/include/PoolObjectSQL.h +++ b/include/PoolObjectSQL.h @@ -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& 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. diff --git a/include/RangedLeases.h b/include/RangedLeases.h deleted file mode 100644 index b71dd37770..0000000000 --- a/include/RangedLeases.h +++ /dev/null @@ -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& 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& 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_*/ - diff --git a/include/Request.h b/include/Request.h index faea23d7e0..c51ce85968 100644 --- a/include/Request.h +++ b/include/Request.h @@ -73,11 +73,13 @@ protected: string uname; /**< name of the user */ string gname; /**< name of the user's group */ - set group_ids; /**< set of user's group ids */ + set 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; }; diff --git a/include/RequestManagerAllocate.h b/include/RequestManagerAllocate.h index bd6d91878a..223dadc306 100644 --- a/include/RequestManagerAllocate.h +++ b/include/RequestManagerAllocate.h @@ -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); }; /* -------------------------------------------------------------------------- */ diff --git a/include/RequestManagerClone.h b/include/RequestManagerClone.h index 0cad867228..5107f65db0 100644 --- a/include/RequestManagerClone.h +++ b/include/RequestManagerClone.h @@ -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(pool); VirtualMachineTemplate * ttmpl = static_cast(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(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); }; }; diff --git a/include/RequestManagerUpdateTemplate.h b/include/RequestManagerUpdateTemplate.h index 669f20d266..650dac561f 100644 --- a/include/RequestManagerUpdateTemplate.h +++ b/include/RequestManagerUpdateTemplate.h @@ -144,6 +144,7 @@ public: Nebula& nd = Nebula::instance(); pool = nd.get_vnpool(); auth_object = PoolObjectSQL::NET; + auth_op = AuthRequest::ADMIN; }; ~VirtualNetworkUpdateTemplate(){}; diff --git a/include/RequestManagerVirtualNetwork.h b/include/RequestManagerVirtualNetwork.h index ad8c6a39d5..ce6996a018 100644 --- a/include/RequestManagerVirtualNetwork.h +++ b/include/RequestManagerVirtualNetwork.h @@ -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); +}; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ diff --git a/include/User.h b/include/User.h index 0d40bf23c0..6e7a1520a9 100644 --- a/include/User.h +++ b/include/User.h @@ -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 */ diff --git a/include/UserPool.h b/include/UserPool.h index 38a8fc5117..5f9cdde3ce 100644 --- a/include/UserPool.h +++ b/include/UserPool.h @@ -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& group_ids); + set& 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& group_ids); + set& 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& group_ids); + set& group_ids, + int& umask); /** @@ -246,7 +250,8 @@ private: int& group_id, string& uname, string& gname, - set& group_ids); + set& group_ids, + int& umask); /** * Factory method to produce User objects * @return a pointer to the new User diff --git a/include/VirtualNetwork.h b/include/VirtualNetwork.h index c1cd5e08c2..c6fd70f5c0 100644 --- a/include/VirtualNetwork.h +++ b/include/VirtualNetwork.h @@ -19,9 +19,9 @@ #include "PoolSQL.h" -#include "Leases.h" #include "VirtualNetworkTemplate.h" #include "Clusterable.h" +#include "AddressRangePool.h" #include #include @@ -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 &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& 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& 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& 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& 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& 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(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_*/ diff --git a/include/VirtualNetworkPool.h b/include/VirtualNetworkPool.h index 772e8ceae6..fcd908769c 100644 --- a/include/VirtualNetworkPool.h +++ b/include/VirtualNetworkPool.h @@ -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); }; /** diff --git a/src/cli/one_helper.rb b/src/cli/one_helper.rb index 0f7c1979c4..c9a2ffebe4 100644 --- a/src/cli/one_helper.rb +++ b/src/cli/one_helper.rb @@ -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) diff --git a/src/cli/one_helper/onevm_helper.rb b/src/cli/one_helper/onevm_helper.rb index 7755f6036c..f8086ae136 100644 --- a/src/cli/one_helper/onevm_helper.rb +++ b/src/cli/one_helper/onevm_helper.rb @@ -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) diff --git a/src/cli/one_helper/onevnet_helper.rb b/src/cli/one_helper/onevnet_helper.rb index 84c6b99931..79a0a702cb 100644 --- a/src/cli/one_helper/onevnet_helper.rb +++ b/src/cli/one_helper/onevnet_helper.rb @@ -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 diff --git a/src/cli/onevnet b/src/cli/onevnet index 4c5ee447e2..60200269c2 100755 --- a/src/cli/onevnet +++ b/src/cli/onevnet @@ -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 diff --git a/src/common/Attribute.cc b/src/common/Attribute.cc index edc4a0df87..ba26c33992 100644 --- a/src/common/Attribute.cc +++ b/src/common/Attribute.cc @@ -68,14 +68,28 @@ string * VectorAttribute::marshall(const char * _sep) const string * VectorAttribute::to_xml() const { - map::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::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 << ">second - << "]]>first << ">"; + oss << "<" << it->first << ">second + << "]]>first << ">"; } - } + } - oss << ""; - - xml = new string; - - *xml = oss.str(); - - return xml; + oss << ""; } - /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -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::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::const_iterator it; diff --git a/src/datastore/Datastore.cc b/src/datastore/Datastore.cc index ebcb869414..58018ef2eb 100644 --- a/src/datastore/Datastore.cc +++ b/src/datastore/Datastore.cc @@ -68,6 +68,11 @@ Datastore::Datastore( group_u = 1; } +Datastore::~Datastore() +{ + delete obj_template; +}; + /* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */ diff --git a/src/nebula/NebulaTemplate.cc b/src/nebula/NebulaTemplate.cc index a3a9617730..7d966dd98c 100644 --- a/src/nebula/NebulaTemplate.cc +++ b/src/nebula/NebulaTemplate.cc @@ -29,7 +29,7 @@ int NebulaTemplate::load_configuration() string aname; Attribute * attr; - map::iterator iter, j; + map::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); } } diff --git a/src/oca/ruby/opennebula/virtual_network.rb b/src/oca/ruby/opennebula/virtual_network.rb index 11ac90feb8..b4372843be 100644 --- a/src/oca/ruby/opennebula/virtual_network.rb +++ b/src/oca/ruby/opennebula/virtual_network.rb @@ -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 diff --git a/src/rm/Request.cc b/src/rm/Request.cc index 40ce02572a..f0f5d4c0f8 100644 --- a/src/rm/Request.cc +++ b/src/rm/Request.cc @@ -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); diff --git a/src/rm/RequestManager.cc b/src/rm/RequestManager.cc index 1fd4ab040e..84f61dd78b 100644 --- a/src/rm/RequestManager.cc +++ b/src/rm/RequestManager.cc @@ -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); diff --git a/src/rm/RequestManagerAllocate.cc b/src/rm/RequestManagerAllocate.cc index f4188c8aa0..4ad98a59a0 100644 --- a/src/rm/RequestManagerAllocate.cc +++ b/src/rm/RequestManagerAllocate.cc @@ -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(pool); VirtualNetworkTemplate * vtmpl=static_cast(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(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(pool); VirtualMachineTemplate * ttmpl=static_cast(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(pool); DatastoreTemplate * ds_tmpl = static_cast(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(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)); diff --git a/src/rm/RequestManagerChown.cc b/src/rm/RequestManagerChown.cc index f199242861..6363e20057 100644 --- a/src/rm/RequestManagerChown.cc +++ b/src/rm/RequestManagerChown.cc @@ -49,12 +49,12 @@ PoolObjectSQL * RequestManagerChown::get_and_quota( return 0; } - if ( auth_object == PoolObjectSQL::VM ) + if (auth_object == PoolObjectSQL::VM) { tmpl = (static_cast(object))->clone_template(); qtype = Quotas::VIRTUALMACHINE; } - else + else if (auth_object == PoolObjectSQL::IMAGE) { Image * img = static_cast(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(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); } diff --git a/src/rm/RequestManagerClone.cc b/src/rm/RequestManagerClone.cc index 20d1ea6747..2de7c4d24e 100644 --- a/src/rm/RequestManagerClone.cc +++ b/src/rm/RequestManagerClone.cc @@ -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 ) { diff --git a/src/rm/RequestManagerDelete.cc b/src/rm/RequestManagerDelete.cc index 5e727455c3..152a5d1de0 100644 --- a/src/rm/RequestManagerDelete.cc +++ b/src/rm/RequestManagerDelete.cc @@ -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(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; } diff --git a/src/rm/RequestManagerImage.cc b/src/rm/RequestManagerImage.cc index 69467d987f..5cd8076015 100644 --- a/src/rm/RequestManagerImage.cc +++ b/src/rm/RequestManagerImage.cc @@ -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(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, diff --git a/src/rm/RequestManagerVMTemplate.cc b/src/rm/RequestManagerVMTemplate.cc index ce22fbebcc..8569c487c5 100644 --- a/src/rm/RequestManagerVMTemplate.cc +++ b/src/rm/RequestManagerVMTemplate.cc @@ -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(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 ) diff --git a/src/rm/RequestManagerVirtualMachine.cc b/src/rm/RequestManagerVirtualMachine.cc index 3878b1a3e7..191303e817 100644 --- a/src/rm/RequestManagerVirtualMachine.cc +++ b/src/rm/RequestManagerVirtualMachine.cc @@ -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) diff --git a/src/rm/RequestManagerVirtualNetwork.cc b/src/rm/RequestManagerVirtualNetwork.cc index 971d18d6dd..7493c2eccf 100644 --- a/src/rm/RequestManagerVirtualNetwork.cc +++ b/src/rm/RequestManagerVirtualNetwork.cc @@ -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(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(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(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); +} diff --git a/src/sunstone/etc/sunstone-views/admin.yaml b/src/sunstone/etc/sunstone-views/admin.yaml index c4bd59e27d..df48160b48 100644 --- a/src/sunstone/etc/sunstone-views/admin.yaml +++ b/src/sunstone/etc/sunstone-views/admin.yaml @@ -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 diff --git a/src/sunstone/etc/sunstone-views/cloud.yaml b/src/sunstone/etc/sunstone-views/cloud.yaml index 41e9887f90..c6588fc968 100644 --- a/src/sunstone/etc/sunstone-views/cloud.yaml +++ b/src/sunstone/etc/sunstone-views/cloud.yaml @@ -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 diff --git a/src/sunstone/etc/sunstone-views/user.yaml b/src/sunstone/etc/sunstone-views/user.yaml index 727b203022..0f6e3626a3 100644 --- a/src/sunstone/etc/sunstone-views/user.yaml +++ b/src/sunstone/etc/sunstone-views/user.yaml @@ -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 diff --git a/src/sunstone/etc/sunstone-views/vdcadmin.yaml b/src/sunstone/etc/sunstone-views/vdcadmin.yaml index 6175facd39..757fd6803f 100644 --- a/src/sunstone/etc/sunstone-views/vdcadmin.yaml +++ b/src/sunstone/etc/sunstone-views/vdcadmin.yaml @@ -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 diff --git a/src/sunstone/etc/sunstone-views/vdcadmin46.yaml b/src/sunstone/etc/sunstone-views/vdcadmin46.yaml index c095c08ca3..118d63cdab 100644 --- a/src/sunstone/etc/sunstone-views/vdcadmin46.yaml +++ b/src/sunstone/etc/sunstone-views/vdcadmin46.yaml @@ -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 diff --git a/src/sunstone/models/OpenNebulaJSON/VirtualNetworkJSON.rb b/src/sunstone/models/OpenNebulaJSON/VirtualNetworkJSON.rb index bba1722c73..14fd22ee25 100644 --- a/src/sunstone/models/OpenNebulaJSON/VirtualNetworkJSON.rb +++ b/src/sunstone/models/OpenNebulaJSON/VirtualNetworkJSON.rb @@ -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 diff --git a/src/sunstone/public/js/opennebula.js b/src/sunstone/public/js/opennebula.js index 7ef8c6ceba..f46591d6fd 100644 --- a/src/sunstone/public/js/opennebula.js +++ b/src/sunstone/public/js/opennebula.js @@ -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, diff --git a/src/sunstone/public/js/plugins/clusters-tab.js b/src/sunstone/public/js/plugins/clusters-tab.js index 622dffd430..2e1ce55a49 100644 --- a/src/sunstone/public/js/plugins/clusters-tab.js +++ b/src/sunstone/public/js/plugins/clusters-tab.js @@ -45,8 +45,8 @@ var vnet_datatable_table_tmpl='\ '+tr("Owner")+'\ '+tr("Group")+'\ '+tr("Name")+'\ + '+tr("Reservation")+'\ '+tr("Cluster")+'\ - '+tr("Type")+'\ '+tr("Bridge")+'\ '+tr("Leases")+'\ \ diff --git a/src/sunstone/public/js/plugins/oneflow-services.js b/src/sunstone/public/js/plugins/oneflow-services.js index 4496d138b1..5e45b8ac21 100644 --- a/src/sunstone/public/js/plugins/oneflow-services.js +++ b/src/sunstone/public/js/plugins/oneflow-services.js @@ -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'); }); } }); diff --git a/src/sunstone/public/js/plugins/oneflow-templates.js b/src/sunstone/public/js/plugins/oneflow-templates.js index e3debfbe57..b1fcd723c2 100644 --- a/src/sunstone/public/js/plugins/oneflow-templates.js +++ b/src/sunstone/public/js/plugins/oneflow-templates.js @@ -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'); }); }); }); diff --git a/src/sunstone/public/js/plugins/templates-tab.js b/src/sunstone/public/js/plugins/templates-tab.js index edbee9cf27..61254fda12 100644 --- a/src/sunstone/public/js/plugins/templates-tab.js +++ b/src/sunstone/public/js/plugins/templates-tab.js @@ -1559,8 +1559,8 @@ function generate_nic_tab_content(str_nic_tab_id, str_datatable_id){ ''+tr("Owner")+''+ ''+tr("Group")+''+ ''+tr("Name")+''+ + ''+tr("Reservation")+''+ ''+tr("Cluster")+''+ - ''+tr("Type")+''+ ''+tr("Bridge")+''+ ''+tr("Leases")+''+ ''+ diff --git a/src/sunstone/public/js/plugins/vms-tab.js b/src/sunstone/public/js/plugins/vms-tab.js index 74930a8f17..506967d0f6 100644 --- a/src/sunstone/public/js/plugins/vms-tab.js +++ b/src/sunstone/public/js/plugins/vms-tab.js @@ -2320,7 +2320,7 @@ function printNics(vm_info){ \ ' + nic.NIC_ID + '\ ' + nic.NETWORK + '\ - ' + nic.IP + '\ + ' + (nic.IP ? nic.IP : "--") + '\ ' + nic.MAC + '\ ' + (nic.IP6_SITE ? nic.IP6_SITE : "--") +'\ ' + (nic.IP6_GLOBAL ? nic.IP6_GLOBAL : "--") +'\ diff --git a/src/sunstone/public/js/plugins/vnets-tab.js b/src/sunstone/public/js/plugins/vnets-tab.js index 34c76a35a9..d000d97b1e 100644 --- a/src/sunstone/public/js/plugins/vnets-tab.js +++ b/src/sunstone/public/js/plugins/vnets-tab.js @@ -15,6 +15,7 @@ /* -------------------------------------------------------------------------- */ var addresses_vnets = 0; +var last_selected_row_ar; var create_vn_tmpl = '
'+ @@ -28,141 +29,86 @@ var create_vn_tmpl = \
\ \ -
\ -
\ -
\ +
\ +
\ + \ +
\ +
\ +

'+tr("General")+'
\ +

'+tr("Configuration")+'
\ +

'+tr("Addresses")+'
\ +

'+tr("Other")+'
\ +
\ +
\ +
\
\ -
\ - \ - \ +
\ + \ + \
\
\
\ -
\ - \ - \ -
\ -
\ -
\ - \ - \ -
\ - \ +
\ + \ + \
\ -
\ - ×'; + \ +
\ +
\ +
\ +
\ +
\ +

'+tr("Write the Virtual Network template here")+'

\ +
\ +
\ +
\ +
\ + \ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +×'; var update_vnet_tmpl = '
\ @@ -401,24 +349,6 @@ var vnet_actions = { error: onError }, - "Network.addleases" : { - type: "single", - call: OpenNebula.Network.addleases, - callback: function(req) { - Sunstone.runAction("Network.show",req.request.data[0][0]); - }, - error: onError - }, - - "Network.rmleases" : { - type: "single", - call: OpenNebula.Network.rmleases, - callback: function(req) { - Sunstone.runAction("Network.show",req.request.data[0][0]); - }, - error: onError - }, - "Network.hold" : { type: "single", call: OpenNebula.Network.hold, @@ -437,6 +367,62 @@ var vnet_actions = { error: onError }, + "Network.add_ar" : { + type: "single", + call: OpenNebula.Network.add_ar, + callback: function(req) { + // Reset the wizard + $add_ar_dialog.foundation('reveal', 'close'); + $add_ar_dialog.empty(); + setupAddARDialog(); + + Sunstone.runAction("Network.show",req.request.data[0][0]); + }, + error: onError + }, + + "Network.rm_ar" : { + type: "single", + call: OpenNebula.Network.rm_ar, + callback: function(req) { + Sunstone.runAction("Network.show",req.request.data[0][0]); + }, + error: onError + }, + + "Network.update_ar" : { + type: "single", + call: OpenNebula.Network.update_ar, + callback: function(req) { + // Reset the wizard + $update_ar_dialog.foundation('reveal', 'close'); + $update_ar_dialog.empty(); + setupUpdateARDialog(); + + Sunstone.runAction("Network.show",req.request.data[0][0]); + }, + error: onError + }, + + "Network.reserve_dialog" : { + type: "custom", + call: popUpReserveDialog + }, + + "Network.reserve" : { + type: "single", + call: OpenNebula.Network.reserve, + callback: function(req) { + // Reset the wizard + $reserve_dialog.foundation('reveal', 'close'); + $reserve_dialog.empty(); + setupReserveDialog(); + + Sunstone.runAction("Network.show",req.request.data[0][0]); + }, + error: onError + }, + "Network.chown" : { type: "multiple", call: OpenNebula.Network.chown, @@ -528,6 +514,12 @@ var vnet_buttons = { layout: "create" }, + "Network.reserve_dialog" : { + type: "action", + layout: "main", + text: tr("Reserve"), + custom_classes: "only-right-info reserve-right-info", + }, "Network.addtocluster" : { type: "confirm_with_select", text: tr("Select cluster"), @@ -566,6 +558,10 @@ var vnet_info_panel = { title: tr("Virtual network information"), content: "" }, + "vnet_ar_list_tab" : { + title: tr("Address Range management"), + content: "" + }, "vnet_leases_tab" : { title: tr("Lease management"), content: "" @@ -591,8 +587,8 @@ var vnets_tab = { '+tr("Owner")+'\ '+tr("Group")+'\ '+tr("Name")+'\ + '+tr("Reservation")+'\ '+tr("Cluster")+'\ - '+tr("Type")+'\ '+tr("Bridge")+'\ '+tr("Leases")+'\ \ @@ -615,7 +611,15 @@ function vnElements(){ function vNetworkElementArray(vn_json){ var network = vn_json.VNET; - addresses_vnets = addresses_vnets + parseInt(network.TOTAL_LEASES); + addresses_vnets = addresses_vnets + parseInt(network.USED_LEASES); + + var total_size = 0; + + var ar_list = get_ar_list(network); + + $.each(ar_list, function(){ + total_size += parseInt(this.SIZE); + }); return [ '', @@ -623,10 +627,10 @@ function vNetworkElementArray(vn_json){ network.UNAME, network.GNAME, network.NAME, + network.PARENT_NETWORK_ID.length ? tr("Yes") : tr("No"), network.CLUSTER.length ? network.CLUSTER : "-", - parseInt(network.TYPE) ? "FIXED" : "RANGED", network.BRIDGE, - network.TOTAL_LEASES ]; + quotaBarHtml(network.USED_LEASES, total_size) ]; } //Callback to update a vnet element after an action on it @@ -634,9 +638,6 @@ function updateVNetworkElement(request, vn_json){ id = vn_json.VNET.ID; element = vNetworkElementArray(vn_json); updateSingleElement(element,dataTable_vNetworks,'#vnetwork_'+id); - - //we update this too, even if it is not shown. - $('#leases_form').replaceWith(printLeases(vn_json.VNET)); } //Callback to delete a vnet element from the table @@ -648,8 +649,6 @@ function deleteVNetworkElement(req){ function addVNetworkElement(request,vn_json){ var element = vNetworkElementArray(vn_json); addElement(element,dataTable_vNetworks); - //we update this too, even if it is not shown. - $('#leases_form').replaceWith(printLeases(vn_json.VNET)); } //updates the list of virtual networks @@ -671,6 +670,26 @@ function updateVNetworksView(request, network_list){ //updates the information panel tabs and pops the panel up function updateVNetworkInfo(request,vn){ var vn_info = vn.VNET; + + var reservation_row = ''; + + if(vn_info.PARENT_NETWORK_ID.length > 0){ + reservation_row = + '\ + '+tr("Reservation parent")+'\ + '+vn_info.PARENT_NETWORK_ID+'\ + \ + '; + + $(".reserve-right-info").prop("disabled", true); + $(".reserve-right-info").addClass("has-tip"); + $(".reserve-right-info").attr("title", tr("This Network is already a reservation")); + } else{ + $(".reserve-right-info").prop("disabled", false); + $(".reserve-right-info").removeClass("has-tip"); + $(".reserve-right-info").removeAttr("title"); + } + var info_tab_content = '
\
\ @@ -690,8 +709,9 @@ function updateVNetworkInfo(request,vn){ vn_info.NAME)+ '' + insert_cluster_dropdown("Network",vn_info.ID,vn_info.CLUSTER,vn_info.CLUSTER_ID,"#info_vn_table") + - '\ - \ + ''+ + reservation_row+ + '\
\
' + insert_permissions_table('vnets-tab', @@ -718,6 +738,12 @@ function updateVNetworkInfo(request,vn){ content: info_tab_content }; + var ar_tab = { + title : tr("Addresses"), + icon: "fa-align-justify", + content: ar_list_tab_content(vn_info) + }; + var leases_tab = { title: tr("Leases"), icon: "fa-list-ul", @@ -726,178 +752,384 @@ function updateVNetworkInfo(request,vn){ Sunstone.updateInfoPanelTab("vnet_info_panel","vnet_info_tab",info_tab); + Sunstone.updateInfoPanelTab("vnet_info_panel","vnet_ar_list_tab",ar_tab); Sunstone.updateInfoPanelTab("vnet_info_panel","vnet_leases_tab",leases_tab); Sunstone.popUpInfoPanel("vnet_info_panel", "vnets-tab"); + + var ar_list_dataTable = $("#ar_list_datatable",$("#vnet_info_panel")).dataTable({ + "bSortClasses" : false, + "bDeferRender": true, + "aoColumnDefs": [ +// { "bSortable": false, "aTargets": [3,4] }, + ] + }); + + ar_list_dataTable.fnSort( [ [0,config['user_config']['table_order']] ] ); + + $('tbody tr',ar_list_dataTable).die("click"); + $('tbody tr',ar_list_dataTable).live("click",function(e){ + var aData = ar_list_dataTable.fnGetData(this); + if (!aData) return true; + var id = aData[0]; + if (!id) return true; + + if(last_selected_row_ar) { + last_selected_row_ar.children().each(function(){ + $(this).removeClass('markrowchecked'); + }); + } + + last_selected_row_ar = $(this); + $(this).children().each(function(){ + $(this).addClass('markrowchecked'); + }); + + if (get_ar(vn_info, id).PARENT_NETWORK_AR_ID != undefined && + get_ar(vn_info, id).PARENT_NETWORK_AR_ID.length > 0){ + + $("#update_ar_button", $("#vnet_info_panel")).prop("disabled", true); + $("#update_ar_button", $("#vnet_info_panel")).addClass("has-tip"); + $("#update_ar_button", $("#vnet_info_panel")).attr("title", tr("This address range is a reservation")); + } else{ + $("#update_ar_button", $("#vnet_info_panel")).attr("ar_id", id); + $("#update_ar_button", $("#vnet_info_panel")).prop("disabled", false); + $("#update_ar_button", $("#vnet_info_panel")).removeClass("has-tip"); + $("#update_ar_button", $("#vnet_info_panel")).removeAttr("title"); + } + + $("#rm_ar_button", $("#vnet_info_panel")).attr("ar_id", id).removeAttr('disabled'); + + $("#ar_show_info", $("#vnet_info_panel")).html(ar_show_info(vn_info, id)); + + return false; + }); + + var leases_dataTable = $("#leases_datatable",$("#vnet_info_panel")).dataTable({ + "bSortClasses" : false, + "bDeferRender": true, +// "sScrollX": "100%", + "aoColumnDefs": [ + { "bSortable": false, "aTargets": [0,1] }, + ] + }); + setPermissionsTable(vn_info,''); } +function get_ar_list(vn_info){ + var ar_list = vn_info.AR_POOL.AR; + + if (!ar_list) //empty + { + ar_list = []; + } + else if (ar_list.constructor != Array) //>1 lease + { + ar_list = [ar_list]; + } + + return ar_list; +} + +function get_ar(vn_info, ar_id){ + var ar_list = get_ar_list(vn_info); + var ar = undefined; + + for (var i=0; i'; + + html += + '
\ +
'; + + if (Config.isTabActionEnabled("vnets-tab", "Network.add_ar")) { + html += + ''; + } + + html += ''; + + if (Config.isTabActionEnabled("vnets-tab", "Network.update_ar")) { + html += + ''; + } + + if (Config.isTabActionEnabled("vnets-tab", "Network.remove_ar")) { + html += + ''; + } + + html += '
'; + + html += + '
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + '; + + for (var i=0; i'; + + html += ''; + html += ''; + + if(ar.TYPE == "IP4" || ar.TYPE == "IP4_6"){ + html += ''; + } else { + html += ''; + } + + var prefix = ""; + + if(ar.GLOBAL_PREFIX && ar.ULA_PREFIX){ + prefix += ar.GLOBAL_PREFIX + "
" + ar.ULA_PREFIX; + } else if (ar.GLOBAL_PREFIX){ + prefix += ar.GLOBAL_PREFIX; + } else if (ar.ULA_PREFIX){ + prefix += ar.ULA_PREFIX; + } else { + prefix = "--"; + } + + html += ''; + + html += ''; + + html += ''; + } + + html += '
'+tr("Address Range")+''+tr("Type")+''+tr("Start")+''+tr("IPv6 Prefix")+''+tr("Leases")+'
'+ id +''+ (ar.TYPE ? ar.TYPE : "--") +''+ (ar.IP ? ar.IP : "--") +''+ (ar.MAC ? ar.MAC : "--") +''+ prefix +''+ quotaBarHtml(ar.USED_LEASES, ar.SIZE) +'
'; + + html += + '
'; + + if(ar_list.length > 0){ + html += + '
\ + \ + \ + \ + \ +
\ +
\ + '+ + tr("Select an Address Range to see more information")+ + '\ +
'; + } + + html += + '
\ + '; + + return html; +} + +function ar_show_info(vn_info, ar_id){ + + var ar = get_ar(vn_info, ar_id); + + if(ar == undefined){ + return ""; + } + + function ar_attr(txt, val){ + if(val){ + return '\ + '+htmlDecode(txt)+'\ + '+htmlDecode(val)+'\ + ' + } + + return ''; + } + + var html = ""; + + html += + '
\ +
\ + \ + \ + \ + \ + '; + + // TODO: translate ar.TYPE values? + html += ar_attr(tr("Type"), ar.TYPE); + html += ar_attr(tr("MAC Start"), ar.MAC); + html += ar_attr(tr("IP Start"), ar.IP); + html += ar_attr(tr("Global prefix"),ar.GLOBAL_PREFIX); + html += ar_attr(tr("ULA prefix"), ar.ULA_PREFIX); + html += ar_attr(tr("Size"), ar.SIZE); + html += ar_attr(tr("Used leases"), ar.USED_LEASES); + html += ar_attr(tr("Reservation parent AR"), ar.PARENT_NETWORK_AR_ID); + + delete ar["AR_ID"]; + delete ar["TYPE"]; + delete ar["MAC"]; + delete ar["IP"]; + delete ar["GLOBAL_PREFIX"]; + delete ar["ULA_PREFIX"]; + delete ar["SIZE"]; + delete ar["USED_LEASES"]; + delete ar["LEASES"]; + delete ar["PARENT_NETWORK_AR_ID"]; + + html += + '\ +
'+tr("Address Range")+' '+ar_id+'
'; + + html += + '
\ +
\ + \ + \ + \ + \ + '; + + $.each(ar, function(key, value){ + html += ar_attr(key, value); + }); + + html += + '\ + '; + + return html; +} + // Prints the lis of leases depending on the Vnet TYPE // It adds the "add lease", "hold lease" fields, and each lease comes with // hold, release buttons etc. Listeners in setupLeasesOps() function printLeases(vn_info){ - var html ='
'; - html +=''; + var ar_list = get_ar_list(vn_info); - html += '
 
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
'+tr("Network information")+'
'+tr("Network mask")+''+( vn_info.TEMPLATE.NETWORK_MASK ? vn_info.TEMPLATE.NETWORK_MASK : "--" )+'
'+tr("IPv6 Global prefix")+''+ (typeof(vn_info.GLOBAL_PREFIX) == "object" ? "--": vn_info.GLOBAL_PREFIX) +'
'+tr("IPv6 Site prefix")+''+ (typeof(vn_info.SITE_PREFIX) == "object" ? "--": vn_info.SITE_PREFIX) +'
'; + var html = + ''; - html += '
\ - \ - \ - \ - '; - - if (vn_info.TYPE == "0"){ - html += '\ - \ - \ - \ - \ - \ - \ - '; - - if (Config.isTabActionEnabled("vnets-tab", "Network.hold_lease")) { - html += - '\ - \ - \ - '; - } - } else { - if (Config.isTabActionEnabled("vnets-tab", "Network.addleases")) { + if (Config.isTabActionEnabled("vnets-tab", "Network.hold_lease")) { html += - '\ - \ - \ - '; - } - }; - - html +='\ -
'+tr("Leases information")+'
'+tr("IP Start")+''+vn_info.RANGE.IP_START+'
'+tr("IP End")+''+vn_info.RANGE.IP_END+'
\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - '; - - var leases = vn_info.LEASES.LEASE; - - if (!leases) //empty - { - html+=''; - html += '
'+tr("IP")+''+tr("MAC")+''+tr("IPv6 Site")+''+tr("IPv6 Global")+'
\ - '+tr("No leases to show")+'\ -
'; - return html; + '
\ +
\ + \ +
\ +
\ + \ +
\ +
'; } - else if (leases.constructor != Array) //>1 lease - { - leases = [leases]; - }; - var lease; - var state=null; + html += + '
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + '; - for (var i=0; i'; + if (!leases) //empty + { + continue; + } + else if (leases.constructor != Array) //>1 lease + { + leases = [leases]; + } - html += '' + var lease; - switch (state){ - case 0: - html += ''; + + html += ''; + } else if (lease.VM != undefined) { //used by a VM + html += '\ + '; + } else if (lease.VNET != undefined) { //used by a VNET + html += '\ + '; + } else { + html += '\ + '; } - html += '' - html += '' - html += '' - html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; - html += ''; + html += ''; + } + } - html += ''; - html += ''; - - html += ''; - }; - - html += '
'+tr("IP")+''+tr("MAC")+''+tr("IPv6 Link")+''+tr("IPv6 ULA")+''+tr("IPv6 Global")+''+tr("Address Range")+'
'; - switch (state){ - case 0: //free - html += ' ' - break; - case 1: //used - html += ' ' - break; - case 2: //hold - html += ' ' - break; - }; - html += ''; - if (Config.isTabActionEnabled("vnets-tab", "Network.hold_lease")) { - html += ''; + for (var j=0; j'; + + html += ''; + + if (lease.VM == "-1") { //hold + html += ''; + if (Config.isTabActionEnabled("vnets-tab", "Network.release_lease")) { + html += ''; + } + html += '' + tr("VM:") + lease.VM+'' + tr("NET:") + lease.VNET+'--' - if (Config.isTabActionEnabled("vnets-tab", "Network.remove_lease")) { - html += ''; - } - break; - case 1: - html += '' + tr("VM:") + lease.VID+'' - break; - case 2: - html += ''; - if (Config.isTabActionEnabled("vnets-tab", "Network.release_lease")) { - html += ''; - } - html += '' - if (Config.isTabActionEnabled("vnets-tab", "Network.remove_lease")) { - html += ''; - } - break; - }; - html += ''+ lease.IP + ''+ (lease.IP ? lease.IP : "--") +''+ (lease.MAC ? lease.MAC : "--") +''+ (lease.IP6_LINK ? lease.IP6_LINK : "--") +''+ (lease.IP6_ULA ? lease.IP6_ULA : "--") +''+ (lease.IP6_GLOBAL ? lease.IP6_GLOBAL : "--") +''+ id +'\ - '+lease.MAC+'
'+ (lease.IP6_SITE ? lease.IP6_SITE : "--") +''+ (lease.IP6_GLOBAL ? lease.IP6_GLOBAL : "--") +'
'; + html += '
'; return html; } @@ -911,61 +1143,30 @@ function setupCreateVNetDialog() { dialog.addClass("reveal-modal medium").attr("data-reveal", ""); - //Make the tabs look nice for the creation mode - //$('#vn_tabs',dialog).tabs(); - $('div#ranged',dialog).hide(); - $('div#ranged_ipv6',dialog).hide(); + var number_of_ar = 0; - $('input#site_prefix,label[for="site_prefix"]',$create_vn_dialog).hide(); - $('input#global_prefix,label[for="global_prefix"]',$create_vn_dialog).hide(); + // close icon: removing the tab on click + $("#vnetCreateARTab", dialog).on("click", "i.remove-tab", function() { + var target = $(this).parent().attr("href"); + var dd = $(this).closest('dd'); + var dl = $(this).closest('dl'); + var content = $(target); - $('input[name="ip_version"]',dialog).change(function(){ - var fixed_ranged = $('input[name="fixed_ranged"]:checked',dialog).val(); + dd.remove(); + content.remove(); - if (this.id == 'ipv4_check') { - $('input#net_mask,label[for="net_mask"]',$create_vn_dialog).show(); - $('input#net_address,label[for="net_address"]',$create_vn_dialog).show(); - - $('input#site_prefix,label[for="site_prefix"]',$create_vn_dialog).hide(); - $('input#global_prefix,label[for="global_prefix"]',$create_vn_dialog).hide(); - - if ( fixed_ranged == "fixed" ){ - $('input#leaseip,label[for="leaseip"]',$create_vn_dialog).show(); - } else { - $('div#ranged',$create_vn_dialog).show(); - $('div#ranged_ipv6',$create_vn_dialog).hide(); + if (dd.attr("class") == 'active') { + $('a', dl.children('dd').last()).click(); } - } else { - $('input#net_mask,label[for="net_mask"]',$create_vn_dialog).hide(); - $('input#net_address,label[for="net_address"]',$create_vn_dialog).hide(); - $('input#site_prefix,label[for="site_prefix"]',$create_vn_dialog).show(); - $('input#global_prefix,label[for="global_prefix"]',$create_vn_dialog).show(); - - if ( fixed_ranged == "fixed" ){ - $('input#leaseip,label[for="leaseip"]',$create_vn_dialog).hide(); - } else { - $('div#ranged',$create_vn_dialog).hide(); - $('div#ranged_ipv6',$create_vn_dialog).show(); - } - } + return false; }); - $('input[name="fixed_ranged"]',dialog).change(function(){ - if (this.id == 'fixed_check') { - $('div#fixed',$create_vn_dialog).show(); - $('div#ranged',$create_vn_dialog).hide(); - $('div#ranged_ipv6',$create_vn_dialog).hide(); - } - else { - $('div#fixed',$create_vn_dialog).hide(); + $("#vnet_wizard_ar_btn", dialog).bind("click", function(){ + add_ar_tab(number_of_ar, dialog); + number_of_ar++; - if ( $('input[name="ip_version"]:checked',dialog).val() == "ipv4" ){ - $('div#ranged',$create_vn_dialog).show(); - } else { - $('div#ranged_ipv6',$create_vn_dialog).show(); - } - } + return false; }); $('#network_mode',dialog).change(function(){ @@ -973,276 +1174,83 @@ function setupCreateVNetDialog() { $('input', $(this).parent()).val(""); switch ($(this).val()) { case "default": - $('input#bridge,label[for="bridge"]',$create_vn_dialog).show(); - $('input#phydev,label[for="phydev"]',$create_vn_dialog).hide(); - $('select#vlan,label[for="vlan"]',$create_vn_dialog).hide(); - $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).hide(); + $('input#bridge,label[for="bridge"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#phydev,label[for="phydev"]',$create_vn_dialog).hide().prop('wizard_field_disabled', true); + $('select#vlan,label[for="vlan"]',$create_vn_dialog).hide().prop('wizard_field_disabled', true); + $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).hide().prop('wizard_field_disabled', true); + + $('input#phydev',$create_vn_dialog).removeAttr('required'); + $('input#bridge',$create_vn_dialog).attr('required', ''); break; case "802.1Q": - // TODO add warning use PHY_DEV unless... BRIDGE - $('input#bridge,label[for="bridge"]',$create_vn_dialog).show(); - $('input#phydev,label[for="phydev"]',$create_vn_dialog).show(); - $('select#vlan,label[for="vlan"]',$create_vn_dialog).show(); - $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).show(); + $('input#bridge,label[for="bridge"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#phydev,label[for="phydev"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('select#vlan,label[for="vlan"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + + $('input#phydev',$create_vn_dialog).attr('required', ''); + $('input#bridge',$create_vn_dialog).removeAttr('required'); break; case "ebtables": - $('input#bridge,label[for="bridge"]',$create_vn_dialog).show(); - $('input#phydev,label[for="phydev"]',$create_vn_dialog).show(); - $('select#vlan,label[for="vlan"]',$create_vn_dialog).show(); - $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).hide(); + $('input#bridge,label[for="bridge"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#phydev,label[for="phydev"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('select#vlan,label[for="vlan"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).hide().prop('wizard_field_disabled', true); + + $('input#phydev',$create_vn_dialog).removeAttr('required'); + $('input#bridge',$create_vn_dialog).attr('required', ''); break; case "openvswitch": - $('input#bridge,label[for="bridge"]',$create_vn_dialog).show(); - $('input#phydev,label[for="phydev"]',$create_vn_dialog).hide(); - $('select#vlan,label[for="vlan"]',$create_vn_dialog).show(); - $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).show(); + $('input#bridge,label[for="bridge"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#phydev,label[for="phydev"]',$create_vn_dialog).hide().prop('wizard_field_disabled', true); + $('select#vlan,label[for="vlan"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).show().prop('wizard_field_disabled', false); + + $('input#phydev',$create_vn_dialog).removeAttr('required'); + $('input#bridge',$create_vn_dialog).attr('required', ''); break; case "vmware": $('input#bridge,label[for="bridge"]',$create_vn_dialog).show(); $('input#phydev,label[for="phydev"]',$create_vn_dialog).hide(); $('select#vlan,label[for="vlan"]',$create_vn_dialog).show(); $('input#vlan_id,label[for="vlan_id"]',$create_vn_dialog).show(); + + $('input#phydev',$create_vn_dialog).removeAttr('required'); + $('input#bridge',$create_vn_dialog).attr('required', ''); break; }; + + $("div.network_mode_description").hide(); + $('div.network_mode_description[value="'+$(this).val()+'"]').show(); }); //Initialize shown options $('#network_mode',dialog).trigger("change"); - //$('button',dialog).button(); - - - //When we hit the add lease button... - $('#add_lease',dialog).click(function(){ - var create_form = $('#create_vn_form_easy',$create_vn_dialog); //this is our scope - - //Fetch the interesting values - var lease_ip = ""; - - if ( $('input[name="ip_version"]:checked',dialog).val() == "ipv4" ) { - lease_ip = $('#leaseip',create_form).val(); - } - - var lease_mac = $('#leasemac',create_form).val(); - - //We do not add anything to the list if there is nothing to add - if (!lease_ip.length && !lease_mac.length) { - notifyError(tr("Please provide a lease IP or MAC")); - return false; - }; - - //contains the HTML to be included in the select box. - // The space is used later to parse ip and mac - var lease = ''; - - //We append the HTML into the select box. - $('select#leases',$create_vn_dialog).append(lease); - return false; - }); - - $('#remove_lease', dialog).click(function(){ - $('select#leases :selected',$create_vn_dialog).remove(); - return false; - }); - - $('#custom_pool', dialog).change(function(){ - if ($(this).is(':checked')){ - $('#ip_start', $create_vn_dialog).removeAttr('disabled'); - $('#ip_end', $create_vn_dialog).removeAttr('disabled'); - } - else { - $('#ip_start', $create_vn_dialog).attr('disabled','disabled'); - $('#ip_end', $create_vn_dialog).attr('disabled','disabled'); - }; - }); - - - $('#add_custom_var_vnet_button', dialog).click( - function(){ - var name = $('#custom_var_vnet_name',$create_vn_dialog).val(); - var value = $('#custom_var_vnet_value',$create_vn_dialog).val(); - if (!name.length || !value.length) { - notifyError("Custom attribute name and value must be filled in"); - return false; - } - option= ''; - $('select#custom_var_vnet_box',$create_vn_dialog).append(option); - return false; - } - ); - - $('#remove_custom_var_vnet_button', dialog).click( - function(){ - $('select#custom_var_vnet_box :selected',$create_vn_dialog).remove(); - return false; - } - ); - + setupCustomTags($("#vnetCreateContextTab", dialog)); //Handle submission of the easy mode - $('#create_vn_submit_easy',dialog).click(function(){ + $('#create_vn_form_easy',dialog).on('invalid', function () { + notifyError(tr("One or more required fields are missing.")); + }).on('valid', function () { //Fetch values - var name = $('#name',dialog).val(); - if (!name.length){ - notifyError(tr("Virtual Network name missing!")); - return false; - } + var network_json = {}; - var description = $('#DESCRIPTION',dialog).val(); - var network_json = {"name" : name, "description" : description}; + retrieveWizardFields($("#vnetCreateGeneralTab", dialog), network_json); + retrieveWizardFields($("#vnetCreateBridgeTab", dialog), network_json); + retrieveWizardFields($("#vnetCreateGeneralTab", dialog), network_json); - var network_mode = $('select#network_mode',dialog).val(); - var bridge = $('#bridge',dialog).val(); - var phydev = $('#phydev',dialog).val(); - var vlan = $('#vlan',dialog).val(); - var vlan_id = $('#vlan_id',dialog).val(); + retrieveCustomTags($("#vnetCreateContextTab", dialog), network_json); - //Depending on network mode we include certain params in the - //template - switch (network_mode) { - case "default": - if (!bridge && !phydev){ - notifyError("Bridge or physical device must be specified"); - return false; - }; - if (bridge) network_json['bridge']=bridge; - if (phydev) network_json['phydev']=phydev; - break; - case "802.1Q": - if (!phydev){ - notifyError("Physical device must be specified"); - return false; - }; - network_json['phydev']=phydev; - if (bridge) network_json['bridge']=bridge; - network_json['vlan']=vlan; - if (vlan_id) { - network_json['vlan_id']=vlan_id; - }; - break; - case "ebtables": - if (!bridge){ - notifyError("Bridge must be specified"); - return false; - }; - network_json['bridge']=bridge; - network_json['vlan']=vlan; - break; - case "openvswitch": - case "vmware": - if (!bridge){ - notifyError("Bridge must be specified"); - return false; - }; - network_json['bridge']=bridge; - network_json['vlan']=vlan; - if (vlan_id) { - network_json['vlan_id']=vlan_id; - }; - break; - }; + $('.ar_tab',dialog).each(function(){ + hash = retrieve_ar_tab_data(this); - var ip_version = $('input[name="ip_version"]:checked',dialog).val(); + if (!$.isEmptyObject(hash)) { + if(!network_json["AR"]) + network_json["AR"] = []; - var type = $('input[name="fixed_ranged"]:checked',dialog).val(); - network_json['type']=type; - //TODO: Name and bridge provided?! - - var network_addr = $('#net_address',dialog).val(); - var network_mask = $('#net_mask',dialog).val(); - var network_dns = $('#net_dns',dialog).val(); - var network_gateway = $('#net_gateway',dialog).val(); - - if (network_dns.length) - network_json["dns"] = network_dns; - - if (ip_version == "ipv6") { - var site_prefix = $('#site_prefix',dialog).val(); - var global_prefix = $('#global_prefix',dialog).val(); - - if (site_prefix.length) - network_json["site_prefix"] = site_prefix; - - if (global_prefix.length) - network_json["global_prefix"] = global_prefix; - - if (network_gateway.length) - network_json["gateway6"] = network_gateway; - - } else { - if (network_addr.length) - network_json["network_address"]=network_addr; - - if (network_mask.length) - network_json["network_mask"]=network_mask; - - if (network_gateway.length) - network_json["gateway"] = network_gateway; - } - - if (type == "fixed") { - var leases = $('#leases option', dialog); - var leases_obj=[]; - - //for each specified lease we prepare the JSON object - $.each(leases,function(){ - var lease_str = $(this).val().split(" "); - - if (lease_str[0].length && lease_str[1].length) { - leases_obj.push({"ip": lease_str[0], - "mac": lease_str[1]}); - } else if (lease_str[0].length) { - leases_obj.push({"ip": lease_str[0] }); - } else { - leases_obj.push({"mac": lease_str[1] }); - } - }); - - //and construct the final data for the request - network_json["leases"] = leases_obj; - } - else { //type ranged - - if (ip_version == "ipv4") { - var custom = $('#custom_pool',dialog).is(':checked'); - var ip_start = $('#ip_start',dialog).val(); - var ip_end = $('#ip_end',dialog).val(); - - if (!(ip_start.length && ip_end.length) && !network_addr.length){ - notifyError(tr("There are missing network parameters")); - return false; - }; - - if (custom){ - if (ip_start.length) - network_json["ip_start"] = ip_start; - if (ip_end.length) - network_json["ip_end"] = ip_end; - }; - } else { - var mac_start = $('#mac_start',dialog).val(); - var network_size = $('#net_size',dialog).val(); - - if (! mac_start.length){ - notifyError(tr("MAC Start must be specified")); - return false; - }; - - network_json["mac_start"] = mac_start; - - if (network_size.length) - network_json["network_size"] = network_size; + network_json["AR"].push(hash); } - }; - - //Time to add custom attributes - $('#custom_var_vnet_box option',$create_vn_dialog).each(function(){ - var attr_name = $(this).attr('name'); - var attr_value = $(this).val(); - network_json[attr_name] = attr_value; }); //Create the VNetwork. @@ -1276,30 +1284,225 @@ function setupCreateVNetDialog() { popUpCreateVnetDialog(); $("a[href='#vnet_advanced']").click(); }); + + setupTips(dialog); } function popUpCreateVnetDialog() { $create_vn_dialog.foundation().foundation('reveal', 'open'); + + // Add first AR + $("#vnet_wizard_ar_btn", $create_vn_dialog).trigger("click"); + $("input#name",$create_vn_dialog).focus(); } +function add_ar_tab(ar_id, dialog) { + var str_ar_tab_id = 'ar' + ar_id; + + var html_tab_content = '
'+ + generate_ar_tab_content(str_ar_tab_id) + + '
' + + // Append the new div containing the tab and add the tab to the list + var a = $("
"+ + tr("Address Range")+"
" + ).appendTo($("dl#vnet_wizard_ar_tabs", dialog)); + + $(html_tab_content).appendTo($("#vnet_wizard_ar_tabs_content", dialog)); + + $("a", a).trigger("click"); + + var ar_section = $('#' + str_ar_tab_id + 'Tab', dialog); + setup_ar_tab_content(ar_section, str_ar_tab_id); +} + +function generate_ar_tab_content(str_ar_tab_id){ + var html = + '
\ +
\ + \ + \ + \ + \ +
\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ + \ + \ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ + ' + tr("Custom attributes") + '\ +
\ +
\ +
\ +
\ +
\ +
'+ + customTagsHtml()+ + '
\ +
'; + + return html; +} + +function setup_ar_tab_content(ar_section, str_ar_tab_id) { + + $('input[name$="ar_type"]',ar_section).change(function(){ + $('div.ar_input', ar_section).hide(); + + switch($(this).val()){ + case "IP4": + $('div.type_ip4', ar_section).show(); + break; + case "IP4_6": + $('div.type_ip4_6', ar_section).show(); + break; + case "IP6": + $('div.type_ip6', ar_section).show(); + break; + case "ETHER": + $('div.type_ether', ar_section).show(); + break; + } + }); + + $('input#'+str_ar_tab_id+'_ar_type_ip4',ar_section).prop('checked', true); + $('input#'+str_ar_tab_id+'_ar_type_ip4',ar_section).change(); + + setupCustomTags($('#'+str_ar_tab_id+'_custom_tags',ar_section)); + + setupTips(ar_section); +} + +function retrieve_ar_tab_data(ar_section){ + var data = {}; + + var ar_type = $('input[name$="ar_type"]:checked',ar_section).val(); + + var fields = []; + + switch(ar_type){ + case "IP4": + fields = $('div.type_ip4', ar_section).children("input"); + break; + case "IP4_6": + fields = $('div.type_ip4_6', ar_section).children("input"); + break; + case "IP6": + fields = $('div.type_ip6', ar_section).children("input"); + break; + case "ETHER": + fields = $('div.type_ether', ar_section).children("input"); + break; + } + + fields.each(function(){ + var field=$(this); + + if (field.val() != null && field.val().length){ //if has a length + data[field.attr('name')] = field.val(); + } + + }); + + if (!$.isEmptyObject(data)) { + data["TYPE"] = ar_type; + } + + retrieveCustomTags(ar_section, data); + + // TODO MANDATORY INPUTS + /* + if (!(ip_start.length && ip_end.length) && !network_addr.length){ + notifyError(tr("There are missing network parameters")); + return false; + }; + */ + + return data +} + +function fill_ar_tab_data(ar_json, ar_section){ + var fields = $('[wizard_field]',ar_section); + + fields.each(function(){ + var field = $(this); + var field_name = field.attr('wizard_field'); + if (ar_json[field_name]){ + switch(field.attr("type")){ + case "radio": + var checked = (field.val() == ar_json[field_name]); + + field.prop("checked", checked ); + + if(checked){ + field.change(); + } + break; + default: + field.val(escapeDoubleQuotes(htmlDecode(ar_json[field_name]))); + field.change(); + } + } + }); + + fields.each(function(){ + var field = $(this); + var field_name = field.attr('wizard_field'); + + // Delete so these attributes don't end in the custom tags table also + delete ar_json[field_name]; + }); + + delete ar_json["AR_ID"]; + delete ar_json["USED_LEASES"]; + delete ar_json["LEASES"]; + + fillCustomTags(ar_section, ar_json); + + $('input[name$="ar_type"]',ar_section).prop("disabled", true); + $('input[wizard_field="IP"]',ar_section).prop("disabled", true); + $('input[wizard_field="MAC"]',ar_section).prop("disabled", true); +}; // Listeners to the add, hold, release, delete leases operations in the // extended information panel. function setupLeasesOps(){ - if (Config.isTabActionEnabled("vnets-tab", "Network.addleases")) { - $('button#panel_add_lease_button').live("click",function(){ - var lease = $('input#panel_add_lease').val(); - //var mac = $(this).previous().val(); - var id = $(this).parents('form').attr('vnid'); - if (lease.length){ - var obj = {ip: lease}; - Sunstone.runAction('Network.addleases',id,obj); - } - return false; - }); - } - if (Config.isTabActionEnabled("vnets-tab", "Network.hold_lease")) { //ranged networks hold lease $('button#panel_hold_lease_button').live("click",function(){ @@ -1313,7 +1516,6 @@ function setupLeasesOps(){ return false; }); - //fixed networks hold lease $('a.hold_lease').live("click",function(){ var lease = $(this).parents('tr').attr('ip'); var id = $(this).parents('form').attr('vnid'); @@ -1325,20 +1527,6 @@ function setupLeasesOps(){ }); } - if (Config.isTabActionEnabled("vnets-tab", "Network.remove_lease")) { - $('form#leases_form a.delete_lease').live("click",function(){ - var lease = $(this).parents('tr').attr('ip'); - var id = $(this).parents('form').attr('vnid'); - var obj = { ip: lease}; - Sunstone.runAction('Network.rmleases',id,obj); - //Set spinner - $(this).parents('tr').html(''+spinner+''); - return false; - }); - } - - - if (Config.isTabActionEnabled("vnets-tab", "Network.release_lease")) { $('a.release_lease').live("click",function(){ var lease = $(this).parents('tr').attr('ip'); @@ -1350,6 +1538,420 @@ function setupLeasesOps(){ return false; }); } + + if (Config.isTabActionEnabled("vnets-tab", "Network.remove_ar")) { + $('button#rm_ar_button').live("click",function(){ + // TODO: confirm? + var id = $(this).parents('form').attr('vnid'); + var ar_id = $(this).attr('ar_id'); + + var obj = {ar_id: ar_id}; + Sunstone.runAction('Network.rm_ar',id,obj); + + return false; + }); + } + + if (Config.isTabActionEnabled("vnets-tab", "Network.add_ar")) { + $('button#add_ar_button').live("click",function(){ + var id = $(this).parents('form').attr('vnid'); + + popUpAddAR(id); + + return false; + }); + } + + if (Config.isTabActionEnabled("vnets-tab", "Network.update_ar")) { + $('button#update_ar_button').live("click",function(){ + + var id = $(this).parents('form').attr('vnid'); + var ar_id = $(this).attr('ar_id'); + + OpenNebula.Network.show({ + data : { + id: id + }, + timeout: true, + success: function (request, vn){ + var vn_info = vn.VNET; + + var ar = get_ar(vn_info, ar_id); + + if(ar != undefined){ + popUpUpdateAR(id, ar); + } else { + notifyError(tr("The Adress Range was not found")); + Sunstone.runAction("Network.show", id); + } + }, + error: onError + }); + + return false; + }); + } +} + +function popUpAddAR(id){ + $('#vnet_id',$add_ar_dialog).text(id); + $add_ar_dialog.foundation().foundation('reveal', 'open'); +} + +function setupAddARDialog(){ + dialogs_context.append('
'); + $add_ar_dialog = $('#add_ar_dialog',dialogs_context); + var dialog = $add_ar_dialog; + + dialog.html( + '
\ +
\ +
\ +
\ +

\ + '+tr("Virtual Network")+' \ +
'+tr("New Address Range")+'\ +

\ +
\ +
'+ + generate_ar_tab_content("add_ar") + + '\ + ×\ +
\ +
') + + // TODO: max-height? + + dialog.addClass("reveal-modal large max-height").attr("data-reveal", ""); + setupTips(dialog); + + setup_ar_tab_content(dialog, "add_ar") + + $('#submit_ar_reset_button').click(function(){ + $add_ar_dialog.html(""); + setupAddARDialog(); + + popUpAddAR(); + }); + + $('#add_ar_form',dialog).submit(function(){ + var vnet_id = $('#vnet_id', this).text(); + var data = retrieve_ar_tab_data(this); + + var obj = {AR: data} + Sunstone.runAction('Network.add_ar', vnet_id, obj); + + return false; + }); +}; + +function popUpUpdateAR(id, ar){ + $('#vnet_id',$update_ar_dialog).text(id); + $('#ar_id',$update_ar_dialog).text(ar.AR_ID); + + fill_ar_tab_data($.extend({}, ar), $update_ar_dialog); + + $update_ar_dialog.foundation().foundation('reveal', 'open'); +} + +function setupUpdateARDialog(){ + dialogs_context.append('
'); + $update_ar_dialog = $('#update_ar_dialog',dialogs_context); + var dialog = $update_ar_dialog; + + dialog.html( + '
\ +
\ +
\ +
\ +

\ + '+tr("Virtual Network")+' \ +
'+tr("Edit Address Range")+' \ +

\ +
\ +
'+ + generate_ar_tab_content("update_ar") + + '\ + ×\ +
\ +
'); + + // TODO: max-height? + + dialog.addClass("reveal-modal large max-height").attr("data-reveal", ""); + setupTips(dialog); + + setup_ar_tab_content(dialog, "update_ar") + + dialog.die(); + dialog.live('closed', function () { + $update_ar_dialog.html(""); + setupUpdateARDialog(); + }); + + $('#update_ar_form',dialog).submit(function(){ + var vnet_id = $('#vnet_id', this).text(); + var ar_id = $('#ar_id', this).text(); + var data = retrieve_ar_tab_data(this); + + data['AR_ID'] = ar_id; + + var obj = {AR: data} + Sunstone.runAction('Network.update_ar', vnet_id, obj); + + return false; + }); +} + +function popUpReserveDialog(id){ + var selected_nodes = getSelectedNodes(dataTable_vNetworks); + + if ( selected_nodes.length != 1 ) + { + notifyMessage("Please select one (and just one) Virtual Network."); + return false; + } + + // Get proper id + var id = ""+selected_nodes[0]; + + $('#vnet_id',$reserve_dialog).text(id); + + $('#refresh_button_reserve').click(); + $('#refresh_button_ar_reserve').click(); + + $reserve_dialog.foundation().foundation('reveal', 'open'); +} + +function setupReserveDialog(){ + dialogs_context.append('
'); + $reserve_dialog = $('#reserve_dialog',dialogs_context); + var dialog = $reserve_dialog; + + dialog.html( + '
\ +
\ +
\ +
\ +

\ + '+tr("Virtual Network")+' \ +

\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ + '+generateVNetTableSelect("reserve")+'\ +
\ +
\ + \ +
\ +
\ +
\ +
\ +
\ + '+generateARTableSelect("ar_reserve")+'\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ + \ +
\ + \ +
\ +
\ + ×\ +
\ +
'); + + // TODO: max-height? + + + $('input[name="reserve_target"]',dialog).change(function(){ + $('div#reserve_new_body', dialog).hide(); + $('div#reserve_add_body', dialog).hide(); + + $('input', $('div#reserve_new_body', dialog)).prop('wizard_field_disabled', true); + $('input', $('div#reserve_add_body', dialog)).prop('wizard_field_disabled', true); + + switch($(this).val()){ + case "NEW": + $('div#reserve_new_body', dialog).show(); + $('input', $('div#reserve_new_body', dialog)).prop('wizard_field_disabled', false); + break; + case "ADD": + $('div#reserve_add_body', dialog).show(); + $('input', $('div#reserve_add_body', dialog)).prop('wizard_field_disabled', false); + break; + } + }); + + $('input#reserve_new', dialog).prop('checked', true); + $('input#reserve_new', dialog).change(); + + var options = { + filter_fn: function(vnet){ + return (vnet['PARENT_NETWORK_ID'] == $('#vnet_id',dialog).text()); + } + }; + + setupVNetTableSelect(dialog, "reserve", options); + + $("input#selected_resource_id_reserve", dialog).attr("wizard_field", "vnet"); + + setupARTableSelect(dialog, "ar_reserve", function(section){ + return $('#vnet_id',section).text(); + }); + + $("input#selected_resource_id_ar_reserve", dialog).attr("wizard_field", "ar_id"); + + dialog.addClass("reveal-modal large max-height").attr("data-reveal", ""); + setupTips(dialog); + + dialog.die(); + dialog.live('closed', function () { + $reserve_dialog.html(""); + setupReserveDialog(); + }); + + $('#reserve_form',dialog).submit(function(){ + var vnet_id = $('#vnet_id', this).text(); + var data = {}; + + retrieveWizardFields(dialog, data); + + Sunstone.runAction('Network.reserve', vnet_id, data); + + return false; + }); +} + +function generateARTableSelect(context_id){ + var columns = [ + tr("Address Range"), + tr("Type"), + tr("Start"), + tr("IPv6 Prefix"), + tr("Leases") + ]; + + var options = { + "id_index": 0, + "name_index": 0, + "select_resource": tr("Please select an Address Range from the list"), + "you_selected": tr("You selected the following Address Range:") + } + + return generateResourceTableSelect(context_id, columns, options); +} + +function setupARTableSelect(section, context_id, vnet_id_fn){ + + var options = { + "dataTable_options": { + "bSortClasses" : false, + "bDeferRender": true, + "aoColumnDefs": [ + //{ "bSortable": false, "aTargets": [3,4] }, + ] + }, + + "id_index": 0, + "name_index": 0, + + "update_fn": function(datatable){ + + var vn_id = vnet_id_fn(section); + + OpenNebula.Network.show({ + data : { + id: vn_id + }, + timeout: true, + success: function (request, vn){ + var ar_list_array = []; + + var ar_list = get_ar_list(vn.VNET); + + $.each(ar_list, function(){ + var ar = this; + var id = ar.AR_ID; + + var start; + + if(ar.TYPE == "IP4" || ar.TYPE == "IP4_6"){ + start = (ar.IP ? ar.IP : "--"); + } else { + start = (ar.MAC ? ar.MAC : "--"); + } + + var prefix = ""; + + if(ar.GLOBAL_PREFIX && ar.ULA_PREFIX){ + prefix += ar.GLOBAL_PREFIX + "
" + ar.ULA_PREFIX; + } else if (ar.GLOBAL_PREFIX){ + prefix += ar.GLOBAL_PREFIX; + } else if (ar.ULA_PREFIX){ + prefix += ar.ULA_PREFIX; + } else { + prefix = "--"; + } + + ar_list_array.push([ + id, + (ar.TYPE ? ar.TYPE : "--"), + start, + prefix, + quotaBarHtml(ar.USED_LEASES, ar.SIZE) + ]); + }); + + + updateView(ar_list_array, datatable); + }, + error: onError + }); + } + }; + + return setupResourceTableSelect(section, context_id, options); } //The DOM is ready and the ready() from sunstone.js @@ -1382,6 +1984,10 @@ $(document).ready(function(){ setupCreateVNetDialog(); setupLeasesOps(); + setupAddARDialog(); + setupUpdateARDialog(); + setupReserveDialog(); + initCheckAllBoxes(dataTable_vNetworks); tableCheckboxesListener(dataTable_vNetworks); infoListener(dataTable_vNetworks,'Network.show'); diff --git a/src/sunstone/public/js/sunstone.js b/src/sunstone/public/js/sunstone.js index 6819e3ffff..5165c7bfa3 100644 --- a/src/sunstone/public/js/sunstone.js +++ b/src/sunstone/public/js/sunstone.js @@ -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 '
\ +
\ + \ +
\ +
\ + \ +
\ +
\ + \ +
\ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
'+tr("KEY")+''+tr("VALUE")+'
\ +
\ +
'; +} + +// 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 = ""; + }); + + 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 = ""; + }); +} + +// 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 = ''; + + $.each(columns, function(){ + thead += ''+this+'' + }); + + thead += ''; + + var html = + '
\ +
\ + \ +
\ +
\ + \ +
\ +
\ +
\ +
\ + \ + '+thead+'\ + \ + \ +
\ +
\ +
\ +
\ +
\ + '+options.select_resource+'\ + \ + \ + \ +
\ +
'; + + 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); +} diff --git a/src/template/template_parser.c b/src/template/template_parser.c index 9faace2fe3..1836c734f1 100644 --- a/src/template/template_parser.c +++ b/src/template/template_parser.c @@ -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 diff --git a/src/um/User.cc b/src/um/User.cc index 2677be0b15..30a4196e9c 100644 --- a/src/um/User.cc +++ b/src/um/User.cc @@ -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); +} + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ diff --git a/src/um/UserPool.cc b/src/um/UserPool.cc index 923b2b3b3d..8375f7d143 100644 --- a/src/um/UserPool.cc +++ b/src/um/UserPool.cc @@ -419,7 +419,8 @@ bool UserPool::authenticate_internal(User * user, int& group_id, string& uname, string& gname, - set& group_ids) + set& 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& group_ids) + set& 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& group_ids) + set& 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& group_ids) + set& 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; diff --git a/src/vm/VirtualMachine.cc b/src/vm/VirtualMachine.cc index ba388fdd9a..830092e199 100644 --- a/src/vm/VirtualMachine.cc +++ b/src/vm/VirtualMachine.cc @@ -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(); diff --git a/src/vm/vm_var_parser.c b/src/vm/vm_var_parser.c index f40f383298..a0df65025d 100644 --- a/src/vm/vm_var_parser.c +++ b/src/vm/vm_var_parser.c @@ -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 diff --git a/src/vm/vm_var_syntax.cc b/src/vm/vm_var_syntax.cc index ecba1a1971..2f46a8b51d 100644 --- a/src/vm/vm_var_syntax.cc +++ b/src/vm/vm_var_syntax.cc @@ -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 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); diff --git a/src/vm/vm_var_syntax.h b/src/vm/vm_var_syntax.h index 7b449b9c17..7558dd0e9e 100644 --- a/src/vm/vm_var_syntax.h +++ b/src/vm/vm_var_syntax.h @@ -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 */ diff --git a/src/vm/vm_var_syntax.y b/src/vm/vm_var_syntax.y index d3c924160b..1a6bd4ee82 100644 --- a/src/vm/vm_var_syntax.y +++ b/src/vm/vm_var_syntax.y @@ -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 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); diff --git a/src/vnm/AddressRange.cc b/src/vnm/AddressRange.cc new file mode 100644 index 0000000000..f420fe60d4 --- /dev/null +++ b/src/vnm/AddressRange.cc @@ -0,0 +1,1320 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "AddressRange.h" +#include "Attribute.h" +#include "VirtualNetworkPool.h" +#include "NebulaUtil.h" + +#include + +using namespace std; + +/* ************************************************************************** */ +/* ************************************************************************** */ + +string AddressRange::type_to_str(AddressType ob) +{ + switch (ob) + { + case ETHER: return "ETHER"; break; + case IP4: return "IP4" ; break; + case IP6: return "IP6" ; break; + case IP4_6: return "IP4_6"; break; + default: return ""; + } +}; + +/* -------------------------------------------------------------------------- */ + +AddressRange::AddressType AddressRange::str_to_type(string& str_type) +{ + one_util::toupper(str_type); + + if (str_type == "ETHER") + { + return ETHER; + } + else if (str_type == "IP4") + { + return IP4; + } + else if (str_type == "IP6") + { + return IP6; + } + else if (str_type == "IP4_6") + { + return IP4_6; + } + else + { + return NONE; + } +} + +/* ************************************************************************** */ +/* ************************************************************************** */ + +int AddressRange::from_vattr(VectorAttribute *vattr, string& error_msg) +{ + string value; + + attr = vattr; + + /* ------------------------- AR Type & Size ---------------------------- */ + + value = vattr->vector_value("TYPE"); + type = str_to_type(value); + + if (type == NONE) + { + error_msg = "Unknown or missing address range TYPE."; + return -1; + } + + if ( vattr->vector_value("SIZE", size) != 0 || size <= 0 ) + { + error_msg = "Wrong SIZE for address range"; + return -1; + } + + /* -------------------- MAC & IPv4 start addresses ---------------------- */ + + bool do_mac = false; + + value = vattr->vector_value("MAC"); + + if (value.empty()) + { + do_mac = true; + mac[1] = VirtualNetworkPool::mac_prefix(); + } + else + { + if (mac_to_i(value, mac) == -1) + { + error_msg = "Wrong format for MAC attribute"; + return -1; + }; + } + + switch(type) + { + case ETHER: + case IP6: + vattr->remove("IP"); + + if (do_mac) + { + srand(time(0)); + + mac[0] = rand() & 0x0000FFFF; + mac[0]+= (rand()<<16) & 0xFFFF0000; + } + break; + + case IP4: + case IP4_6: + value = vattr->vector_value("IP"); + + if (value.empty() || ip_to_i(value, ip) == -1) + { + error_msg = "Wrong or empty IP attribute"; + return -1; + } + + if (do_mac) + { + mac[0] = ip; + } + break; + + default: + return -1; + } + + /* -------------------------- IP6 prefixes ------------------------------ */ + + value = vattr->vector_value("GLOBAL_PREFIX"); + + if (prefix6_to_i(value, global6) != 0 ) + { + error_msg = "Wrong format for IP6 global address prefix"; + return -1; + } + + value = vattr->vector_value("ULA_PREFIX"); + + if (prefix6_to_i(value, ula6) != 0 ) + { + error_msg = "Wrong format for IP6 unique local address prefix"; + return -1; + } + + /* ------------------------- VNET Attributes ---------------------------- */ + + bool b_vlan; + + if ((vattr->vector_value("VLAN", b_vlan) == 0) && b_vlan) + { + vattr->replace("VLAN", "YES"); + } + + /* ------------------------ AR Internal Data ---------------------------- */ + + vattr->replace("AR_ID", id); + + vattr->remove("ALLOCATED"); + + vattr->remove("USED_LEASES"); + + vattr->remove("LEASES"); + + vattr->remove("PARENT_NETWORK_AR_ID"); + + vattr->remove("PARENT_NETWORK"); + + if (do_mac) //Need to add MAC to the attribute + { + set_mac(0, attr); + } + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::update_attributes(VectorAttribute *vup, string& error_msg) +{ + /* --------------- Do not allow to modify a reservation ------- */ + + int pid; + bool is_reservation = (get_attribute("PARENT_NETWORK_AR_ID", pid) == 0); + + /* --------------- Copy non-update attributes ----------------- */ + + vup->replace("TYPE", attr->vector_value("TYPE")); + + vup->replace("MAC", attr->vector_value("MAC")); + + vup->remove("IP"); + + if (type & 0x00000002) + { + vup->replace("IP", attr->vector_value("IP")); + } + + /* ----------------- Remove internal attributes ----------------- */ + + vup->replace("AR_ID", attr->vector_value("AR_ID")); + + vup->replace("ALLOCATED", attr->vector_value("ALLOCATED")); + + vup->remove("USED_LEASES"); + + vup->remove("LEASES"); + + vup->remove("PARENT_NETWORK_AR_ID"); + + if (is_reservation) + { + vup->replace("PARENT_NETWORK_AR_ID", + attr->vector_value("PARENT_NETWORK_AR_ID")); + } + + + /* ----------------- update known attributes ----------------- */ + + unsigned int new_size; + + if (vup->vector_value("SIZE", new_size) == 0) + { + map itup; + + if (is_reservation && new_size != size) + { + error_msg = "The SIZE of a reservation cannot be changed."; + return -1; + } + + if (allocated.upper_bound(new_size-1) != allocated.end()) + { + error_msg = "New SIZE cannot be applied. There are used leases" + " that would fall outside the range."; + + return -1; + } + } + else + { + new_size = size; + } + + string new_global = vup->vector_value("GLOBAL_PREFIX"); + + if (prefix6_to_i(new_global, global6) != 0 ) + { + error_msg = "Wrong format for IP6 global address prefix"; + return -1; + } + + string new_ula = vup->vector_value("ULA_PREFIX"); + + if (prefix6_to_i(new_ula, ula6) != 0 ) + { + error_msg = "Wrong format for IP6 unique local address prefix"; + return -1; + } + + size = new_size; + + vup->replace("SIZE", size); + + vup->replace("GLOBAL_PREFIX", new_global); + vup->replace("ULA_PREFIX", new_ula); + + /* Replace with the new attributes */ + + attr->replace(vup->value()); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::from_vattr_db(VectorAttribute *vattr) +{ + string value; + int rc = 0; + + this->attr = vattr; + + rc += vattr->vector_value("AR_ID", id); + + value = vattr->vector_value("TYPE"); + type = str_to_type(value); + + rc += vattr->vector_value("SIZE", size); + + rc += mac_to_i(vattr->vector_value("MAC"), mac); + + if (type & 0x00000002) + { + rc += ip_to_i(vattr->vector_value("IP"), ip); + } + + rc += prefix6_to_i(vattr->vector_value("GLOBAL_PREFIX"), global6); + + rc += prefix6_to_i(vattr->vector_value("ULA_PREFIX"), ula6); + + rc += attr_to_allocated(vattr->vector_value("ALLOCATED")); + + if (type == NONE) + { + rc = -1; + } + + return rc; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AddressRange::to_xml(ostringstream &oss) const +{ + const map& ar_attrs = attr->value(); + map::const_iterator it; + + oss << ""; + + for (it=ar_attrs.begin(); it != ar_attrs.end(); it++) + { + if ( it->first == "ALLOCATED" ) + { + continue; + } + + oss << "<" << it->first << ">second + << "]]>first << ">"; + } + + oss << "" << used_addr << ""; + + if (allocated.empty()) + { + oss << ""; + } + else + { + map::const_iterator it; + VectorAttribute lease("LEASE"); + + oss << ""; + + for (it = allocated.begin(); it != allocated.end(); it++) + { + lease.clear(); + + set_mac(it->first, &lease); + + if (type & 0x00000002 ) + { + set_ip(it->first, &lease); + } + + if (type & 0x00000004) + { + set_ip6(it->first, &lease); + } + + if (it->second & PoolObjectSQL::VM) + { + int vmid = it->second & 0x00000000FFFFFFFFLL; + + lease.replace("VM", vmid); + } + else if (it->second & PoolObjectSQL::NET) + { + int vnid = it->second & 0x00000000FFFFFFFFLL; + + lease.replace("VNET", vnid); + } + + lease.to_xml(oss); + } + + oss << ""; + } + + oss << ""; +} + +/* ************************************************************************** */ +/* ************************************************************************** */ + +int AddressRange::mac_to_i(string mac, unsigned int i_mac[]) const +{ + istringstream iss; + + size_t pos = 0; + int count = 0; + + unsigned int tmp; + + 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 AddressRange::ip_to_i(const string& _ip, unsigned int& i_ip) const +{ + 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; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::prefix6_to_i(const string& prefix, unsigned int ip[]) const +{ + 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 AddressRange::set_mac(unsigned int addr_index, VectorAttribute * nic) const +{ + ostringstream oss; + unsigned int temp_byte; + + for (int i=5;i>=0;i--) + { + if ( i < 4 ) + { + temp_byte = mac[0] + addr_index; + temp_byte >>= i*8; + } + else + { + temp_byte = mac[1]; + temp_byte >>= (i%4)*8; + } + + temp_byte &= 255; + + oss.width(2); + oss.fill('0'); + oss << hex << temp_byte; + + if(i!=0) + { + oss << ":"; + } + } + + nic->replace("MAC", oss.str()); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AddressRange::set_ip(unsigned int addr_index, VectorAttribute * nic) const +{ + ostringstream oss; + unsigned int temp_byte; + + for (int index=0;index<4;index++) + { + temp_byte = ip + addr_index; + temp_byte >>= (24-index*8); + temp_byte &= 255; + + oss << temp_byte; + + if(index!=3) + { + oss << "."; + } + } + + nic->replace("IP", oss.str()); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AddressRange::set_ip6(unsigned int addr_index, VectorAttribute * nic) const +{ + unsigned int eui64[2]; + unsigned int mlow = mac[0] + addr_index; + + struct in6_addr ip6; + char dst[INET6_ADDRSTRLEN]; + + eui64[1] = ((mac[1]+512)<<16) + ((mlow & 0xFF000000)>>16) + 0x000000FF; + eui64[0] = 4261412864 + (mlow & 0x00FFFFFF); + + ip6.s6_addr32[2] = htonl(eui64[1]); + ip6.s6_addr32[3] = htonl(eui64[0]); + + /* Link Local */ + ip6.s6_addr32[0] = htonl(0xfe800000); + ip6.s6_addr32[1] = 0; + + if ( inet_ntop(AF_INET6, &ip6, dst, INET6_ADDRSTRLEN) != 0 ) + { + nic->replace("IP6_LINK", dst); + } + + if (ula6[1] != 0 || ula6[0] != 0 ) /* Unique Local Address */ + { + ip6.s6_addr32[0] = htonl(ula6[1]); + ip6.s6_addr32[1] = htonl(ula6[0]); + + if ( inet_ntop(AF_INET6, &ip6, dst, INET6_ADDRSTRLEN) != 0 ) + { + nic->replace("IP6_ULA", dst); + } + } + + if (global6[1] != 0 || global6[0] != 0 ) /* Glocal Unicast */ + { + ip6.s6_addr32[0] = htonl(global6[1]); + ip6.s6_addr32[1] = htonl(global6[0]); + + if ( inet_ntop(AF_INET6, &ip6, dst, INET6_ADDRSTRLEN) != 0 ) + { + nic->replace("IP6_GLOBAL", dst); + } + } +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AddressRange::set_vnet(VectorAttribute *nic, const vector &inherit) const +{ + nic->replace("AR_ID", id); + + string bridge = attr->vector_value("BRIDGE"); + string vlan = attr->vector_value("VLAN"); + string vlanid = attr->vector_value("VLAN_ID"); + string phydev = attr->vector_value("PHYDEV"); + + if (!bridge.empty()) + { + nic->replace("BRIDGE", bridge); + } + + if (!vlan.empty()) + { + nic->replace("VLAN", vlan); + } + + if (!phydev.empty()) + { + nic->replace("PHYDEV", phydev); + } + + if (!vlanid.empty()) + { + nic->replace("VLAN_ID", vlanid); + } + + vector::const_iterator it; + + for (it = inherit.begin(); it != inherit.end(); it++) + { + string inherit_val = attr->vector_value((*it).c_str()); + + if (!inherit_val.empty()) + { + nic->replace((*it).c_str(), inherit_val); + } + } +} + +/* ************************************************************************** */ +/* ************************************************************************** */ + +void AddressRange::allocated_to_attr() +{ + if (allocated.empty()) + { + attr->replace("ALLOCATED", ""); + return; + } + + map::const_iterator it; + + ostringstream oss; + + for (it = allocated.begin(); it != allocated.end(); it++) + { + oss << " " << it->first << " " << it->second; + } + + attr->replace("ALLOCATED", oss.str()); +} + +/* -------------------------------------------------------------------------- */ + +int AddressRange::attr_to_allocated(const string& allocated_s) +{ + if (allocated_s.empty()) + { + allocated.clear(); + return 0; + } + + istringstream iss(allocated_s); + unsigned int addr_index; + long long object_pack; + + while (!iss.eof()) + { + iss >> ws >> addr_index >> ws >> object_pack; + + if (iss.fail()) + { + return -1; + } + + allocated.insert(make_pair(addr_index,object_pack)); + + used_addr++; + } + + return 0; +} + +/* -------------------------------------------------------------------------- */ + +void AddressRange::allocate_addr(PoolObjectSQL::ObjectType ot, int obid, + unsigned int addr_index) +{ + long long lobid = obid & 0x00000000FFFFFFFFLL; + + allocated.insert(make_pair(addr_index,ot|lobid)); + + used_addr++; + + allocated_to_attr(); +} + +/* -------------------------------------------------------------------------- */ + +int AddressRange::free_addr(PoolObjectSQL::ObjectType ot, int obid, + unsigned int addr_index) +{ + long long lobid = obid & 0x00000000FFFFFFFFLL; + + map::iterator it; + + it = allocated.find(addr_index); + + if (it != allocated.end() && it->second == (ot|lobid)) + { + allocated.erase(it); + allocated_to_attr(); + + used_addr--; + + return 0; + } + + return -1; +} + +/* ************************************************************************** */ +/* ************************************************************************** */ + +int AddressRange::allocate_addr( + PoolObjectSQL::ObjectType ot, + int obid, + VectorAttribute* nic, + const vector& inherit) +{ + for ( unsigned int i=0; i& inherit) +{ + unsigned int mac_i[2]; + + if (mac_to_i(mac_s, mac_i) == -1) + { + return -1; + } + + if ((mac_i[1] != mac[1]) || (mac_i[0] < mac[0])) + { + return -1; + } + + unsigned int index = mac_i[0] - mac[0]; + + if ((allocated.count(index) != 0) || (index >= size)) + { + return -1; + } + + set_mac(index, nic); + + if (type & 0x00000002 ) + { + set_ip(index, nic); + } + + if (type & 0x00000004) + { + set_ip6(index, nic); + } + + set_vnet(nic, inherit); + + allocate_addr(ot, obid, index); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::allocate_by_ip( + const string& ip_s, + PoolObjectSQL::ObjectType ot, + int obid, + VectorAttribute* nic, + const vector& inherit) +{ + if (!(type & 0x00000002))//Not of type IP4 or IP4_6 + { + return -1; + } + + unsigned int ip_i; + + if (ip_to_i(ip_s, ip_i) == -1) + { + return -1; + } + + if (ip_i < ip) + { + return -1; + } + + unsigned int index = ip_i - ip; + + if (allocated.count(index) != 0 || index >= size ) + { + return -1; + } + + set_mac(index, nic); + + if (type & 0x00000002 ) + { + set_ip(index, nic); + } + + if (type & 0x00000004) + { + set_ip6(index, nic); + } + + set_vnet(nic, inherit); + + allocate_addr(ot, obid, index); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::free_addr(PoolObjectSQL::ObjectType ot, int obid, + const string& mac_s) +{ + unsigned int mac_i[2]; + + mac_to_i(mac_s, mac_i); + + unsigned int index = mac_i[0] - mac[0]; + + if ((0 <= index) && (index < size)) + { + return free_addr(ot, obid, index); + } + + return -1; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::free_addr_by_ip(PoolObjectSQL::ObjectType ot, int obid, + const string& ip_s) +{ + if (!(type & 0x00000002))//Not of type IP4 or IP4_6 + { + return -1; + } + + unsigned int ip_i; + + if (ip_to_i(ip_s, ip_i) == -1) + { + return -1; + } + + unsigned int index = ip_i - ip; + + if ((0 <= index ) && (index < size)) + { + return free_addr(ot, obid, index); + } + + return -1; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::free_addr_by_owner(PoolObjectSQL::ObjectType ot, int obid) +{ + map::iterator it = allocated.begin(); + + long long obj_pack = ot | (obid & 0x00000000FFFFFFFFLL); + + int freed = 0; + + while (it != allocated.end()) + { + if (it->second == obj_pack) + { + map::iterator prev_it = it++; + + allocated.erase(prev_it); + + used_addr--; + + freed++; + } + else + { + it++; + } + } + + allocated_to_attr(); + + return freed; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::free_addr_by_range(PoolObjectSQL::ObjectType ot, int obid, + const string& mac_s, unsigned int rsize) +{ + int freed = 0; + + unsigned int mac_i[2]; + + mac_to_i(mac_s, mac_i); + + unsigned int index = mac_i[0] - mac[0]; + + if ((0 <= index) && (index < size)) + { + map::iterator it = allocated.find(index); + + if (it == allocated.end()) + { + return freed; + } + + long long obj_pack = ot | (obid & 0x00000000FFFFFFFFLL); + + for (unsigned int i=0; isecond == obj_pack) + { + map::iterator prev_it = it++; + + allocated.erase(prev_it); + + used_addr--; + + freed++; + } + else + { + it++; + } + } + + allocated_to_attr(); + } + + return freed; +} + + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::hold_by_ip(const string& ip_s) +{ + if (!(type & 0x00000002))//Not of type IP4 or IP4_6 + { + return -1; + } + + unsigned int ip_i; + + if (ip_to_i(ip_s, ip_i) == -1) + { + return -1; + } + + if (ip_i < ip) + { + return -1; + } + + unsigned int index = ip_i - ip; + + if (allocated.count(index) != 0 || index >= size ) + { + return -1; + } + + allocate_addr(PoolObjectSQL::VM, -1, index); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::hold_by_mac(const string& mac_s) +{ + unsigned int mac_i[2]; + + if (mac_to_i(mac_s, mac_i) == -1) + { + return -1; + } + + if ((mac_i[1] != mac[1]) || (mac_i[0] < mac[0])) + { + return -1; + } + + unsigned int index = mac_i[0] - mac[0]; + + if ((allocated.count(index) != 0) || (index >= size)) + { + return -1; + } + + allocate_addr(PoolObjectSQL::VM, -1, index); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::reserve_addr(int vid, unsigned int rsize, AddressRange *rar) +{ + unsigned int first_index; + + if (rsize > (size - used_addr)) + { + return -1; //reservation dosen't fit + } + + // --------------- Look for a continuos range of addresses ----------------- + + bool valid = true; + + for (unsigned int i=0; iclone(); + string errmsg; + + set_mac(first_index, new_ar); + + if (type & 0x00000002 ) + { + set_ip(first_index, new_ar); + } + + new_ar->replace("SIZE",rsize); + + rar->from_vattr(new_ar, errmsg); + + new_ar->replace("PARENT_NETWORK_AR_ID",id); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::reserve_addr_by_index(int vid, unsigned int rsize, + unsigned int sindex, AddressRange *rar) +{ + /* ----------------- Allocate the new AR from sindex -------------------- */ + + for (unsigned int j=sindex; j< (sindex+rsize) ; j++) + { + if (allocated.count(j) != 0) + { + return -1; + } + } + + for (unsigned int j=sindex; j< (sindex+rsize); j++) + { + allocate_addr(PoolObjectSQL::NET, vid, j); + } + + /* ------------------------- Initialize the new AR ---------------------- */ + + VectorAttribute * new_ar = attr->clone(); + string errmsg; + + set_mac(sindex, new_ar); + + if (type & 0x00000002 ) + { + set_ip(sindex, new_ar); + } + + new_ar->replace("SIZE",rsize); + + rar->from_vattr(new_ar, errmsg); + + new_ar->replace("PARENT_NETWORK_AR_ID",id); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::reserve_addr_by_ip(int vid, unsigned int rsize, + const string& ip_s, AddressRange *rar) +{ + if (!(type & 0x00000002))//Not of type IP4 or IP4_6 + { + return -1; + } + + unsigned int ip_i; + + if (ip_to_i(ip_s, ip_i) == -1) + { + return -1; + } + + if (ip_i < ip) + { + return -1; + } + + unsigned int sindex = ip_i - ip; + + if (sindex >= size ) + { + return -1; + } + + return reserve_addr_by_index(vid, rsize, sindex, rar); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRange::reserve_addr_by_mac(int vid, unsigned int rsize, + const string& mac_s, AddressRange *rar) +{ + unsigned int mac_i[2]; + + if (mac_to_i(mac_s, mac_i) == -1) + { + return -1; + } + + if ((mac_i[1] != mac[1]) || (mac_i[0] < mac[0])) + { + return -1; + } + + unsigned int sindex = mac_i[0] - mac[0]; + + if (sindex >= size) + { + return -1; + } + + return reserve_addr_by_index(vid, rsize, sindex, rar); +} + +/* ************************************************************************** */ +/* ************************************************************************** */ + +bool AddressRange::restricted_set = false; + +set AddressRange::restricted_attributes; + +bool AddressRange::check(string& rs_attr) const +{ + if (!restricted_set) + { + return false; + } + + const map& ar_attrs = attr->value(); + map::const_iterator it; + + for (it=ar_attrs.begin(); it != ar_attrs.end(); it++) + { + if (restricted_attributes.count(it->first) > 0) + { + rs_attr = it->first; + return true; + } + } + + return false; +}; + +void AddressRange::set_restricted_attributes( + vector& rattrs) +{ + if (restricted_set) + { + return; + } + + restricted_set = true; + + for (unsigned int i = 0 ; i < rattrs.size() ; i++ ) + { + const SingleAttribute * sattr = static_cast(rattrs[i]); + string attr_s = sattr->value(); + + restricted_attributes.insert(one_util::toupper(attr_s)); + } +}; diff --git a/src/vnm/AddressRangePool.cc b/src/vnm/AddressRangePool.cc new file mode 100644 index 0000000000..47c7966c72 --- /dev/null +++ b/src/vnm/AddressRangePool.cc @@ -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::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::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 ars, string& error_msg) +{ + vector::iterator it; + map::iterator ar_it; + + unsigned int arid; + + for (it = ars.begin(); it != ars.end(); it++) + { + VectorAttribute * va = dynamic_cast(*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 var; + + int num_ar = ar_template.get("AR", var); + + for (int i = 0; i < num_ar; i++) + { + VectorAttribute * va = static_cast(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::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 ars; + vector::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(*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::const_iterator it; + + oss << ""; + + for (it=ar_pool.begin(); it!=ar_pool.end(); it++) + { + it->second->to_xml(oss); + } + + oss << ""; + + sstream = oss.str(); + + return sstream; + } + + return ar_template.to_xml(sstream); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AddressRangePool::allocate_addr(PoolObjectSQL::ObjectType ot, int obid, + VectorAttribute * nic, const vector &inherit) +{ + map::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 &inherit) +{ + map::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 &inherit) +{ + map::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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::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; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ diff --git a/src/vnm/FixedLeases.cc b/src/vnm/FixedLeases.cc deleted file mode 100644 index bdb01f6f4e..0000000000 --- a/src/vnm/FixedLeases.cc +++ /dev/null @@ -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 - -FixedLeases::FixedLeases( - SqlDB * db, - int _oid, - unsigned int _mac_prefix, - unsigned int _global[], - unsigned int _site[], - vector& 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 - (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::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::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 ;isecond->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::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& 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(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& 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(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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/vnm/Leases.cc b/src/vnm/Leases.cc deleted file mode 100644 index e000c69599..0000000000 --- a/src/vnm/Leases.cc +++ /dev/null @@ -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 - -/* ************************************************************************** */ -/* ************************************************************************** */ -/* 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 << - "" << - "" << mac_s << "" << - "" << ip_s << "" << - "" << ipl_s << ""; - - if (site[1] != 0 || site[0] != 0 ) - { - ip6_to_string(eui64, site, ips_s); - os << "" << ips_s << ""; - } - - if (global[1] != 0 || global[0] != 0 ) - { - ip6_to_string(eui64, global, ipg_s); - os << "" << ipg_s << ""; - } - - os << ""<< used << ""<< - "" << vid << "" << - ""; - - str = os.str(); - - return str; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -string& Leases::Lease::to_xml_db(string& str) const -{ - ostringstream os; - - os << - "" << - "" << ip << "" << - "" << mac[1] << "" << - "" << mac[0] << "" << - "" << used << ""<< - "" << vid << "" << - ""; - - 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(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(&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::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::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& 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(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& vector_leases, - string& error_msg) -{ - const VectorAttribute * single_attr_lease = 0; - map::iterator it; - - unsigned int i_ip; - string st_ip; - string mac; - - if ( vector_leases.size() > 0 ) - { - single_attr_lease = - dynamic_cast(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::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; -}; - diff --git a/src/vnm/RangedLeases.cc b/src/vnm/RangedLeases.cc deleted file mode 100644 index 548d734ff6..0000000000 --- a/src/vnm/RangedLeases.cc +++ /dev/null @@ -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 - -/* ************************************************************************** */ -/* 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; iescape_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::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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/vnm/SConstruct b/src/vnm/SConstruct index 17ecc14a63..dd7233c8b2 100644 --- a/src/vnm/SConstruct +++ b/src/vnm/SConstruct @@ -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 diff --git a/src/vnm/VirtualNetwork.cc b/src/vnm/VirtualNetwork.cc index 90f61e3d24..f2d2316afd 100644 --- a/src/vnm/VirtualNetwork.cc +++ b/src/vnm/VirtualNetwork.cc @@ -18,10 +18,9 @@ #include "VirtualNetwork.h" #include "VirtualNetworkPool.h" #include "VirtualNetworkTemplate.h" +#include "AddressRange.h" #include "NebulaLog.h" -#include "RangedLeases.h" -#include "FixedLeases.h" #include "AuthManager.h" #include "ClusterPool.h" @@ -39,14 +38,14 @@ VirtualNetwork::VirtualNetwork(int _uid, const string& _uname, const string& _gname, int _umask, + int _pvid, int _cluster_id, const string& _cluster_name, VirtualNetworkTemplate * _vn_template): PoolObjectSQL(-1,NET,"",_uid,_gid,_uname,_gname,table), Clusterable(_cluster_id, _cluster_name), bridge(""), - type(UNINITIALIZED), - leases(0) + parent_vid(_pvid) { if (_vn_template != 0) { @@ -58,9 +57,6 @@ VirtualNetwork::VirtualNetwork(int _uid, } set_umask(_umask); - - global_bin[0] = global_bin[1] = 0; - site_bin[0] = site_bin[1] = 0; }; /* -------------------------------------------------------------------------- */ @@ -68,7 +64,6 @@ VirtualNetwork::VirtualNetwork(int _uid, VirtualNetwork::~VirtualNetwork() { - delete leases; delete obj_template; } @@ -76,7 +71,7 @@ VirtualNetwork::~VirtualNetwork() /* Virtual Network :: Database Access Functions */ /* ************************************************************************** */ -const char * VirtualNetwork::table = "network_pool"; +const char * VirtualNetwork::table = "network_pool"; const char * VirtualNetwork::db_names = "oid, name, body, uid, gid, owner_u, group_u, other_u, cid"; @@ -90,132 +85,17 @@ const char * VirtualNetwork::db_bootstrap = "CREATE TABLE IF NOT EXISTS" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int VirtualNetwork::select(SqlDB * db) -{ - int rc; - - rc = PoolObjectSQL::select(db); - - if ( rc != 0 ) - { - return rc; - } - - return select_leases(db); -} - -/* -------------------------------------------------------------------------- */ - -int VirtualNetwork::select(SqlDB * db, const string& name, int uid) -{ - int rc; - - rc = PoolObjectSQL::select(db,name,uid); - - if ( rc != 0 ) - { - return rc; - } - - return select_leases(db); -} - -/* -------------------------------------------------------------------------- */ - -int VirtualNetwork::select_leases(SqlDB * db) -{ - ostringstream oss; - ostringstream ose; - - string network_address; - - unsigned int mac_prefix = VirtualNetworkPool::mac_prefix(); - - //Get the leases - if (type == RANGED) - { - leases = new RangedLeases(db, - oid, - mac_prefix, - global_bin, - site_bin, - ip_start, - ip_end); - } - else if(type == FIXED) - { - leases = new FixedLeases(db, - oid, - mac_prefix, - global_bin, - site_bin); - } - else - { - goto error_type; - } - - if (leases == 0) - { - goto error_leases; - } - - return leases->select(db); - - -error_leases: - ose << "Error getting Virtual Network leases nid: " << oid; - goto error_common; - -error_type: - ose << "Wrong type of Virtual Network: " << type; - goto error_common; - -error_common: - NebulaLog::log("VNM", Log::ERROR, ose); - return -1; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - int VirtualNetwork::insert(SqlDB * db, string& error_str) { - ostringstream ose; - int rc; + vector ars; + ostringstream ose; bool b_vlan; - string s_type; - string ranged_error_str; - - unsigned int mac_prefix = VirtualNetworkPool::mac_prefix(); //-------------------------------------------------------------------------- // VirtualNetwork Attributes from the template //-------------------------------------------------------------------------- - // ------------ TYPE ---------------------- - erase_template_attribute("TYPE",s_type); - - TO_UPPER(s_type); - - if (s_type == "RANGED") - { - type = VirtualNetwork::RANGED; - } - else if ( s_type == "FIXED") - { - type = VirtualNetwork::FIXED; - } - else if ( s_type.empty() ) - { - goto error_type_defined; - } - else - { - goto error_wrong_type; - } - // ------------ NAME ---------------------- erase_template_attribute("NAME",name); @@ -283,87 +163,28 @@ int VirtualNetwork::insert(SqlDB * db, string& error_str) add_template_attribute("BRIDGE", bridge); - // ------------ IP6 PREFIX --------------- - - erase_template_attribute("GLOBAL_PREFIX", global); - - if (Leases::Lease::prefix6_to_number(global, global_bin) != 0) - { - goto error_global; - } - - erase_template_attribute("SITE_PREFIX", site); - - if (Leases::Lease::prefix6_to_number(site, site_bin) != 0) - { - goto error_site; - } - //-------------------------------------------------------------------------- - // Get the leases + // Get the Address Ranges //-------------------------------------------------------------------------- - if (type == VirtualNetwork::RANGED) + + remove_template_attribute("AR", ars); + + if (add_var(ars, error_str) != 0) { - - int rc; - - rc = RangedLeases::process_template(this, ip_start, ip_end, - ranged_error_str); - - if ( rc != 0 ) - { - goto error_ranged; - } - - leases = new RangedLeases(db, - oid, - mac_prefix, - global_bin, - site_bin, - ip_start, - ip_end); - } - else // VirtualNetwork::FIXED - { - vector vector_leases; - - get_template_attribute("LEASES",vector_leases); - - leases = new FixedLeases(db, - oid, - mac_prefix, - global_bin, - site_bin, - vector_leases); - - remove_template_attribute("LEASES"); - } - - if (leases == 0) - { - goto error_null_leases; + goto error_ar; } //-------------------------------------------------------------------------- // Insert the Virtual Network //-------------------------------------------------------------------------- - rc = insert_replace(db, false, error_str); - if ( rc != 0 ) + if ( insert_replace(db, false, error_str) != 0 ) { - goto error_update; + goto error_db; } return 0; -error_type_defined: - ose << "No TYPE in template for Virtual Network."; - goto error_common; - -error_wrong_type: - ose << "Wrong type \""<< s_type <<"\" in template for Virtual Network."; - goto error_common; - error_name: ose << "No NAME in template for Virtual Network."; goto error_common; @@ -372,26 +193,9 @@ error_bridge: ose << "No BRIDGE in template for Virtual Network."; goto error_common; -error_update: +error_db: +error_ar: ose << error_str; - goto error_common; - -error_ranged: - ose << ranged_error_str; - goto error_common; - -error_global: - ose << global - << " does not contain a character string representing a valid prefix"; - goto error_common; - -error_site: - ose << site - << " does not contain a character string representing a valid prefix"; - goto error_common; - -error_null_leases: - ose << "Error getting Virtual Network leases."; error_common: error_str = ose.str(); @@ -477,7 +281,6 @@ int VirtualNetwork::insert_replace(SqlDB *db, bool replace, string& error_str) ostringstream oss; int rc; - string xml_body; char * sql_name; @@ -552,23 +355,6 @@ error_common: return -1; } -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -int VirtualNetwork::drop(SqlDB * db) -{ - int rc; - - rc = PoolObjectSQL::drop(db); - - if ( rc == 0 && leases != 0 ) - { - rc += leases->drop(db); - } - - return rc; -} - /* ************************************************************************** */ /* Virtual Network :: Misc */ /* ************************************************************************** */ @@ -617,18 +403,26 @@ string& VirtualNetwork::to_xml_extended(string& xml, bool extended) const os << "" << - "" << oid << "" << - "" << uid << "" << - "" << gid << "" << - "" << uname << "" << - "" << gname << "" << - "" << name << "" << - perms_to_xml(perm_str) << - "" << cluster_id << "" << - "" << cluster << "" << - "" << type << "" << - "" << bridge << ""<< - "" << vlan << ""; + "" << oid << "" << + "" << uid << "" << + "" << gid << "" << + "" << uname << "" << + "" << gname << "" << + "" << name << "" << + perms_to_xml(perm_str) << + ""<< cluster_id<< ""<< + "" << cluster << "" << + "" << bridge << "" << + "" << vlan << ""; + + if (parent_vid != -1) + { + os << "" << parent_vid << ""; + } + else + { + os << ""; + } if (!phydev.empty()) { @@ -647,47 +441,11 @@ string& VirtualNetwork::to_xml_extended(string& xml, bool extended) const { os << ""; } + os << ""<< ar_pool.get_used_addr() << ""; - if (!global.empty()) - { - os << "" << global << ""; - } - else - { - os << ""; - } + os << obj_template->to_xml(template_xml); - if (!site.empty()) - { - os << "" << site << ""; - } - else - { - os << ""; - } - - if ( type == RANGED ) - { - string st_ip_start; - string st_ip_end; - - Leases::Lease::ip_to_string(ip_start, st_ip_start); - Leases::Lease::ip_to_string(ip_end, st_ip_end); - - os << - "" << - "" << st_ip_start << "" << - "" << st_ip_end << "" << - ""; - } - - os << ""<< leases->n_used << ""<< - obj_template->to_xml(template_xml); - - if (extended) - { - os << "" << leases->to_xml(leases_xml) << ""; - } + os << ar_pool.to_xml(leases_xml, extended); os << ""; @@ -704,40 +462,30 @@ int VirtualNetwork::from_xml(const string &xml_str) vector content; int rc = 0; - int int_type; // Initialize the internal XML object update_from_str(xml_str); // Get class base attributes - rc += xpath(oid, "/VNET/ID", -1); - rc += xpath(uid, "/VNET/UID", -1); - rc += xpath(gid, "/VNET/GID", -1); - rc += xpath(uname, "/VNET/UNAME", "not_found"); - rc += xpath(gname, "/VNET/GNAME", "not_found"); - rc += xpath(name, "/VNET/NAME", "not_found"); - rc += xpath(int_type, "/VNET/TYPE", -1); - rc += xpath(bridge, "/VNET/BRIDGE", "not_found"); - rc += xpath(vlan, "/VNET/VLAN", 0); - - rc += xpath(cluster_id, "/VNET/CLUSTER_ID", -1); - rc += xpath(cluster, "/VNET/CLUSTER", "not_found"); + rc += xpath(oid, "/VNET/ID", -1); + rc += xpath(uid, "/VNET/UID", -1); + rc += xpath(gid, "/VNET/GID", -1); + rc += xpath(uname, "/VNET/UNAME", "not_found"); + rc += xpath(gname, "/VNET/GNAME", "not_found"); + rc += xpath(name, "/VNET/NAME", "not_found"); + rc += xpath(bridge, "/VNET/BRIDGE", "not_found"); + rc += xpath(vlan, "/VNET/VLAN", 0); + rc += xpath(cluster_id,"/VNET/CLUSTER_ID", -1); + rc += xpath(cluster, "/VNET/CLUSTER", "not_found"); // Permissions rc += perms_from_xml(); - xpath(phydev, "/VNET/PHYDEV", ""); - xpath(vlan_id, "/VNET/VLAN_ID",""); + xpath(phydev, "/VNET/PHYDEV", ""); + xpath(vlan_id,"/VNET/VLAN_ID",""); + xpath(parent_vid,"/VNET/PARENT_NETWORK_ID",-1); - xpath(global, "/VNET/GLOBAL_PREFIX", ""); - xpath(site, "/VNET/SITE_PREFIX",""); - - Leases::Lease::prefix6_to_number(site, site_bin); - Leases::Lease::prefix6_to_number(global, global_bin); - - type = static_cast(int_type); - - // Get associated classes + // Virtual Network template ObjectXML::get_nodes("/VNET/TEMPLATE", content); if (content.empty()) @@ -745,24 +493,24 @@ int VirtualNetwork::from_xml(const string &xml_str) return -1; } - // Virtual Network template rc += obj_template->from_xml_node(content[0]); ObjectXML::free_nodes(content); + content.clear(); - // Ranged Leases - if (type == RANGED) + // Address Range Pool + ObjectXML::get_nodes("/VNET/AR_POOL", content); + + if (content.empty()) { - string st_ip_start; - string st_ip_end; - - rc += xpath(st_ip_start, "/VNET/RANGE/IP_START", "0"); - rc += xpath(st_ip_end, "/VNET/RANGE/IP_END", "0"); - - Leases::Lease::ip_to_number(st_ip_start, ip_start); - Leases::Lease::ip_to_number(st_ip_end, ip_end); + return -1; } + // Virtual Network template + rc += ar_pool.from_xml_node(content[0]); + + ObjectXML::free_nodes(content); + if (rc != 0) { return -1; @@ -779,65 +527,16 @@ int VirtualNetwork::nic_attribute( int vid, const vector& inherit_attrs) { - int rc; - - string ip; - string mac; - string inherit_val; - - unsigned int eui64[2]; - unsigned int prefix[2] = {0, 0}; - - ostringstream oss; - + string inherit_val; vector::const_iterator it; - ip = nic->vector_value("IP"); - oss << oid; - //-------------------------------------------------------------------------- - // GET NETWORK LEASE - //-------------------------------------------------------------------------- - - if (ip.empty()) - { - rc = leases->get(vid, ip, mac, eui64); - } - else - { - rc = leases->set(vid,ip,mac, eui64); - } - - if ( rc != 0 ) - { - return -1; - } - - //-------------------------------------------------------------------------- - // NEW NIC ATTRIBUTES + // Set default values from the Virtual Network //-------------------------------------------------------------------------- nic->replace("NETWORK", name); - nic->replace("NETWORK_ID",oss.str()); + nic->replace("NETWORK_ID", oid); nic->replace("BRIDGE", bridge); - nic->replace("MAC", mac); - nic->replace("IP", ip); - - Leases::Lease::ip6_to_string(eui64, prefix, ip); - nic->replace("IP6_LINK", ip); - - if (!global.empty()) - { - Leases::Lease::ip6_to_string(eui64, global_bin, ip); - nic->replace("IP6_GLOBAL", ip); - } - - if (!site.empty()) - { - Leases::Lease::ip6_to_string(eui64, site_bin, ip); - nic->replace("IP6_SITE", ip); - } - if ( vlan == 1 ) { @@ -860,15 +559,12 @@ int VirtualNetwork::nic_attribute( if ( get_cluster_id() != ClusterPool::NONE_CLUSTER_ID ) { - oss.str(""); - oss << get_cluster_id(); - - nic->replace("CLUSTER_ID", oss.str()); + nic->replace("CLUSTER_ID", get_cluster_id()); } for (it = inherit_attrs.begin(); it != inherit_attrs.end(); it++) { - get_template_attribute((*it).c_str(), inherit_val); + PoolObjectSQL::get_template_attribute((*it).c_str(), inherit_val); if (!inherit_val.empty()) { @@ -876,60 +572,401 @@ int VirtualNetwork::nic_attribute( } } + //-------------------------------------------------------------------------- + // Get the lease from the Virtual Network + //-------------------------------------------------------------------------- + int rc; + + string ip = nic->vector_value("IP"); + string mac = nic->vector_value("MAC"); + + if (!ip.empty()) + { + rc = allocate_by_ip(vid, ip, nic, inherit_attrs); + } + else if (!mac.empty()) + { + rc = allocate_by_mac(vid, mac, nic, inherit_attrs); + } + else + { + rc = allocate_addr(vid, nic, inherit_attrs); + } + + return rc; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::add_var(vector &var, string& error_msg) +{ + for (vector::iterator it=var.begin(); it!=var.end(); it++) + { + VectorAttribute * oar = dynamic_cast(*it); + + if (oar == 0) + { + error_msg = "Invalid format for address range"; + return -1; + } + + VectorAttribute * ar = oar->clone(); + + if (ar_pool.from_vattr(ar, error_msg) != 0) + { + delete ar; + return -1; + } + } + + return 0; +} + +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::add_ar(VirtualNetworkTemplate * ars_tmpl, string& error_msg) +{ + vector var; + + if (ars_tmpl->get("AR", var) <= 0) + { + return 0; + } + + const VectorAttribute * ar = dynamic_cast(var[0]); + + if (ar == 0) + { + error_msg = "Wrong AR definition"; + return -1; + } + + VectorAttribute * nar = ar->clone(); + + if (ar_pool.from_vattr(nar, error_msg) != 0) + { + delete nar; + return -1; + } + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::update_ar(VirtualNetworkTemplate * ars_tmpl, string& error_msg) +{ + vector tmp_ars; + + if(ars_tmpl->get("AR", tmp_ars) == 0) + { + error_msg = "Wrong AR definition. AR vector attribute is missing."; + + return -1; + } + + return ar_pool.update_ar(tmp_ars, error_msg); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::rm_ar(unsigned int ar_id, string& error_msg) +{ + return ar_pool.rm_ar(ar_id, error_msg); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::hold_leases(VirtualNetworkTemplate * leases_template, + string& error_msg) +{ + vector vleases; + const VectorAttribute * lease = 0; + + if (leases_template->get("LEASES", vleases) <= 0) + { + error_msg = "Empty lease description."; + return -1; + } + + lease = dynamic_cast(vleases[0]); + + if ( lease == 0 ) + { + error_msg = "Empty lease description."; + return -1; + } + + int rc = -1; + + unsigned int ar_id; + + string ip = lease->vector_value("IP"); + string mac = lease->vector_value("MAC"); + + if (ip.empty() && mac.empty()) + { + error_msg = "Missing MAC or IP."; + return -1; + } + + if (lease->vector_value("AR_ID", ar_id) != 0) //No AR_ID hold all addresses + { + if (!mac.empty()) + { + rc = ar_pool.hold_by_mac(mac); + } + else if (!ip.empty()) + { + rc = ar_pool.hold_by_ip(ip); + } + } + else + { + if (!mac.empty()) + { + rc = ar_pool.hold_by_mac(ar_id, mac); + } + else if (!ip.empty()) + { + rc = ar_pool.hold_by_ip(ar_id, ip); + } + } + + if (rc!=0) + { + error_msg = "Address is not part of the address range or in use."; + } + + return rc; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::free_leases(VirtualNetworkTemplate * leases_template, + string& error_msg) +{ + + vector vleases; + const VectorAttribute * lease = 0; + + if (leases_template->get("LEASES", vleases) <= 0) + { + error_msg = "Empty lease description."; + return -1; + } + + lease = dynamic_cast(vleases[0]); + + if ( lease == 0 ) + { + error_msg = "Empty lease description."; + return -1; + } + + unsigned int ar_id; + + string ip = lease->vector_value("IP"); + string mac = lease->vector_value("MAC"); + + + if (ip.empty() && mac.empty()) + { + error_msg = "Missing MAC or IP."; + return -1; + } + + if (lease->vector_value("AR_ID", ar_id) != 0) //No AR_ID free all addresses + { + if (!mac.empty()) + { + ar_pool.free_addr(PoolObjectSQL::VM, -1, mac); + } + else if (!ip.empty()) + { + ar_pool.free_addr_by_ip(PoolObjectSQL::VM, -1, ip); + } + } + else + { + if (!mac.empty()) + { + ar_pool.free_addr(ar_id, PoolObjectSQL::VM, -1, mac); + } + else if (!ip.empty()) + { + ar_pool.free_addr_by_ip(ar_id, PoolObjectSQL::VM, -1, ip); + } + } + return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int VirtualNetwork::add_leases(VirtualNetworkTemplate * leases_template, - string& error_msg) +void VirtualNetwork::get_template_attribute(const char * name, + string& value, int ar_id) const { - vector vector_leases; + ar_pool.get_attribute(name, value, ar_id); - leases_template->get("LEASES", vector_leases); - - return leases->add_leases(vector_leases, error_msg); + if (value.empty()) + { + PoolObjectSQL::get_template_attribute(name, value); + } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int VirtualNetwork::remove_leases(VirtualNetworkTemplate * leases_template, - string& error_msg) +int VirtualNetwork::get_template_attribute(const char * name, int& value, + int ar_id) const { - vector vector_leases; + int rc = ar_pool.get_attribute(name, value, ar_id); - leases_template->get("LEASES", vector_leases); + if (rc != 0) + { + if (PoolObjectSQL::get_template_attribute(name, value) == false) + { + rc = -1; + } + } - return leases->remove_leases(vector_leases, error_msg); + return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int VirtualNetwork::hold_leases(VirtualNetworkTemplate * leases_template, - string& error_msg) +int VirtualNetwork::reserve_addr(VirtualNetwork *rvnet, + unsigned int rsize, string& error_str) { - vector vector_leases; + AddressRange *rar = rvnet->allocate_ar(); - leases_template->get("LEASES", vector_leases); + if (ar_pool.reserve_addr(rvnet->get_oid(), rsize, rar) != 0) + { + error_str = "Not enough free addresses in an address range"; - return leases->hold_leases(vector_leases, error_msg); + delete rar; + + return -1; + } + + if (rvnet->add_ar(rar) != 0) + { + error_str = "Could not add the address range to the netwok"; + + delete rar; + + return -1; + } + + return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int VirtualNetwork::free_leases(VirtualNetworkTemplate * leases_template, - string& error_msg) +int VirtualNetwork::reserve_addr(VirtualNetwork *rvnet, + unsigned int rsize, unsigned int ar_id, string& error_str) { - vector vector_leases; + AddressRange *rar = rvnet->allocate_ar(); - leases_template->get("LEASES", vector_leases); + if (ar_pool.reserve_addr(rvnet->get_oid(), rsize, ar_id, rar) != 0) + { + ostringstream oss; - return leases->free_leases(vector_leases, error_msg); + oss << "Not enough free addresses in address range " << ar_id + << ", or it does not exist"; + + error_str = oss.str(); + + delete rar; + + return -1; + } + + if (rvnet->add_ar(rar) != 0) + { + error_str = "Could not add the address range to the netwok"; + + delete rar; + + return -1; + } + + return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ + +int VirtualNetwork::reserve_addr_by_ip(VirtualNetwork *rvnet, + unsigned int rsize, unsigned int ar_id, const string& ip, string& error_str) +{ + AddressRange *rar = rvnet->allocate_ar(); + + if (ar_pool.reserve_addr_by_ip(rvnet->get_oid(),rsize,ar_id,ip,rar)!=0) + { + ostringstream oss; + + oss << "Not enough free addresses in address range " << ar_id + << ", or it does not exist"; + + error_str = oss.str(); + + delete rar; + + return -1; + } + + if (rvnet->add_ar(rar) != 0) + { + error_str = "Could not add the address range to the netwok"; + + delete rar; + + return -1; + } + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetwork::reserve_addr_by_mac(VirtualNetwork *rvnet, + unsigned int rsize, unsigned int ar_id, const string& mac, string& error_str) +{ + AddressRange *rar = rvnet->allocate_ar(); + + if (ar_pool.reserve_addr_by_mac(rvnet->get_oid(),rsize,ar_id,mac,rar)!=0) + { + ostringstream oss; + + oss << "Not enough free addresses in address range " << ar_id + << ", or it does not exist"; + + error_str = oss.str(); + + delete rar; + + return -1; + } + + if (rvnet->add_ar(rar) != 0) + { + error_str = "Could not add the address range to the netwok"; + + delete rar; + + return -1; + } + + return 0; +} diff --git a/src/vnm/VirtualNetworkPool.cc b/src/vnm/VirtualNetworkPool.cc index 8d2666386d..96cb899d60 100644 --- a/src/vnm/VirtualNetworkPool.cc +++ b/src/vnm/VirtualNetworkPool.cc @@ -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) ) { diff --git a/src/xml/expr_parser.c b/src/xml/expr_parser.c index f1326e9a84..3c7a6f6642 100644 --- a/src/xml/expr_parser.c +++ b/src/xml/expr_parser.c @@ -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