From e3a2a9ee71bc63190d2ec1886851a4ca45fd478f Mon Sep 17 00:00:00 2001 From: Angel Luis Moya Gonzalez Date: Thu, 7 May 2020 15:05:20 +0200 Subject: [PATCH] F #3930: NSX Security Groups (#4255) * DFW - Initial function definition * Section functions working on NSX-T * Add revision to create rules * Add check error to create_rule * Fix error on delete_rule method * Added NSX-V support * Clear OpenNebula rules function Co-authored-by: Tino Vazquez --- install.sh | 14 +- src/vmm_mad/exec/one_vmm_sh | 4 +- .../lib/nsx_driver/distributed_firewall.rb | 285 ++++++++++++++++++ .../remotes/lib/nsx_driver/logical_port.rb | 56 ++++ .../remotes/lib/nsx_driver/logical_switch.rb | 29 +- .../remotes/lib/nsx_driver/nsx_client.rb | 39 ++- .../remotes/lib/nsx_driver/nsx_constants.rb | 39 +++ .../remotes/lib/nsx_driver/nsx_error.rb | 10 + .../remotes/lib/nsx_driver/nsx_rule.rb | 191 ++++++++++++ .../remotes/lib/nsx_driver/nsxt_client.rb | 177 +++++------ .../remotes/lib/nsx_driver/nsxt_dfw.rb | 200 ++++++++++++ .../lib/nsx_driver/nsxt_logical_port.rb | 94 ++++++ .../remotes/lib/nsx_driver/nsxt_rule.rb | 188 ++++++++++++ src/vmm_mad/remotes/lib/nsx_driver/nsxt_tz.rb | 4 +- .../remotes/lib/nsx_driver/nsxv_client.rb | 176 +++++------ .../remotes/lib/nsx_driver/nsxv_dfw.rb | 204 +++++++++++++ .../lib/nsx_driver/nsxv_logical_port.rb | 106 +++++++ .../remotes/lib/nsx_driver/nsxv_rule.rb | 172 +++++++++++ src/vmm_mad/remotes/lib/nsx_driver/nsxv_tz.rb | 6 +- .../remotes/lib/nsx_driver/opaque_network.rb | 20 +- .../remotes/lib/nsx_driver/transport_zone.rb | 12 +- .../remotes/lib/nsx_driver/virtual_wire.rb | 32 +- src/vmm_mad/remotes/nsx/nsx_driver.rb | 9 + src/vnm_mad/remotes/vcenter/clean | 92 +++++- src/vnm_mad/remotes/vcenter/post | 104 ++++++- src/vnm_mad/remotes/vcenter/pre | 72 ++++- src/vnm_mad/remotes/vcenter/update_sg | 97 ++++++ 27 files changed, 2188 insertions(+), 244 deletions(-) create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/distributed_firewall.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/logical_port.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsx_rule.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsxt_dfw.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsxt_logical_port.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsxt_rule.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsxv_dfw.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsxv_logical_port.rb create mode 100644 src/vmm_mad/remotes/lib/nsx_driver/nsxv_rule.rb mode change 120000 => 100755 src/vnm_mad/remotes/vcenter/clean mode change 120000 => 100755 src/vnm_mad/remotes/vcenter/post mode change 120000 => 100755 src/vnm_mad/remotes/vcenter/pre create mode 100755 src/vnm_mad/remotes/vcenter/update_sg diff --git a/install.sh b/install.sh index 323805c494..fbadd3f143 100755 --- a/install.sh +++ b/install.sh @@ -991,7 +991,16 @@ VMM_EXEC_LIB_NSX_FILES="src/vmm_mad/remotes/lib/nsx_driver/logical_switch.rb \ src/vmm_mad/remotes/lib/nsx_driver/transport_zone.rb \ src/vmm_mad/remotes/lib/nsx_driver/nsxt_tz.rb \ src/vmm_mad/remotes/lib/nsx_driver/nsxv_tz.rb \ - src/vmm_mad/remotes/lib/nsx_driver/virtual_wire.rb" + src/vmm_mad/remotes/lib/nsx_driver/virtual_wire.rb \ + src/vmm_mad/remotes/lib/nsx_driver/distributed_firewall.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsxt_dfw.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsxv_dfw.rb \ + src/vmm_mad/remotes/lib/nsx_driver/logical_port.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsxt_logical_port.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsxv_logical_port.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsx_rule.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsxt_rule.rb \ + src/vmm_mad/remotes/lib/nsx_driver/nsxv_rule.rb" #------------------------------------------------------------------------------- # VMM SH Driver LXD scripts, to be installed under $REMOTES_LOCATION/vmm/lxd @@ -1531,7 +1540,8 @@ NETWORK_OVSWITCH_VXLAN_FILES="src/vnm_mad/remotes/ovswitch_vxlan/clean \ NETWORK_VCENTER_FILES="src/vnm_mad/remotes/vcenter/pre \ src/vnm_mad/remotes/vcenter/post \ - src/vnm_mad/remotes/vcenter/clean" + src/vnm_mad/remotes/vcenter/clean \ + src/vnm_mad/remotes/vcenter/update_sg" NETWORK_ALIAS_SDNAT_FILES="src/vnm_mad/remotes/alias_sdnat/AliasSDNAT.rb \ src/vnm_mad/remotes/alias_sdnat/clean \ diff --git a/src/vmm_mad/exec/one_vmm_sh b/src/vmm_mad/exec/one_vmm_sh index 050d09125f..52b3fdc0ee 100755 --- a/src/vmm_mad/exec/one_vmm_sh +++ b/src/vmm_mad/exec/one_vmm_sh @@ -22,8 +22,8 @@ else MAD_LOCATION=$ONE_LOCATION/lib/mads fi -LOCAL_ACTIONS="deploy,shutdown,reboot,cancel,save,restore,migrate,poll,pre" -LOCAL_ACTIONS="${LOCAL_ACTIONS},post,clean" +LOCAL_ACTIONS="deploy,shutdown,reboot,cancel,save,restore,migrate,poll" +LOCAL_ACTIONS="${LOCAL_ACTIONS},pre,post,clean,update_sg" LOCAL_ACTIONS="${LOCAL_ACTIONS},snapshotcreate,snapshotrevert,snapshotdelete" LOCAL_ACTIONS="${LOCAL_ACTIONS},attach_nic,detach_nic,reset" LOCAL_ACTIONS="${LOCAL_ACTIONS},prereconfigure,reconfigure" diff --git a/src/vmm_mad/remotes/lib/nsx_driver/distributed_firewall.rb b/src/vmm_mad/remotes/lib/nsx_driver/distributed_firewall.rb new file mode 100644 index 0000000000..fd2ce1c49a --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/distributed_firewall.rb @@ -0,0 +1,285 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + ONE_LOCATION = ENV['ONE_LOCATION'] unless defined?(ONE_LOCATION) + + if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' \ + unless defined?(RUBY_LIB_LOCATION) + GEMS_LOCATION = '/usr/share/one/gems' \ + unless defined?(GEMS_LOCATION) + else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' \ + unless defined?(RUBY_LIB_LOCATION) + GEMS_LOCATION = ONE_LOCATION + '/share/gems' \ + unless defined?(GEMS_LOCATION) + end + + if File.directory?(GEMS_LOCATION) + Gem.use_paths(GEMS_LOCATION) + end + + $LOAD_PATH << RUBY_LIB_LOCATION + + require 'nsx_rule' + + # Class DistributedFirewall + # Naming convention for rules names: + # "----" + # : Security Group ID + # : Security Group name + # : Virtual Machine ID + # : Vmware virtual machine reference ( vm-XXX ) + # : NIC ID in the virtual machine + class DistributedFirewall < NSXComponent + + include NSXDriver::NSXRule + + # ATTRIBUTES + attr_reader :one_section_name + + # CONSTRUCTOR + def initialize(nsx_client) + super(nsx_client) + end + + def self.new_child(nsx_client) + case nsx_client + when NSXTClient + NSXTdfw.new(nsx_client) + when NSXVClient + NSXVdfw.new(nsx_client) + else + error_msg = "Unknown object type: #{nsx_client}" + error = NSXError::UnknownObject.new(error_msg) + raise error + end + end + + # Sections + # Creates OpenNebula section if not exists and returns + # its section_id. Returns its section_id if OpenNebula + # section already exists + def init_section; end + + # Get all sections + def sections; end + + # Get section by id + def section_by_id(section_id); end + + # Get section by name + def section_by_name(section_name); end + + # Create new section + def create_section(section_name); end + + # Delete section + def delete_section(section_id); end + + # Rules + # Get all rules + def rules; end + + # Get rule by id + def rule_by_id; end + + # Get rule by name + def rules_by_name; end + + # Create new rule + def create_rule; end + + # Update rule + def update_rule; end + + # Delete rule + def delete_rule; end + + def extract_nic_data(nic, nsx_client, vm) + # Network attributes + nic_id = nic.xpath('NIC_ID').text + nic_name = nil + nic_lp = nil + network_id = nic.xpath('NETWORK_ID').text + network_name = nic.xpath('NETWORK').text + network_vcref = nic.xpath('VCENTER_NET_REF').text + network_pgtype = nic.xpath('VCENTER_PORTGROUP_TYPE').text + network_mac = nic.xpath('MAC').text + + # Virtual Machine devices + vm_devices = vm.item.config.hardware.device + vm_devices.each do |device| + next unless vm.is_nic?(device) + + next if device.macAddress != network_mac + + device_label = device.deviceInfo.label + nic_name = "#{vm.item.name}-#{nic_id}-#{device_label}" + + case network_pgtype + when NSXConstants::NSXT_LS_TYPE + lpid = device.externalId + nic_lp = LogicalPort.new_child(nsx_client, lpid) + raise "Logical port id: #{lpid} not found" unless nic_lp + when NSXConstants::NSXV_LS_TYPE + # lpid is vm instanceUuid.sufix + # sufix is device number but removing first number + suffix = device.key.to_s[1..-1] + lpid = "#{vm.item.config.instanceUuid}.#{suffix}" + nic_lp = lpid + else + error_msg = "Network type is: #{network_pgtype} \ + and should be \ + #{NSXConstants::NSXT_LS_TYPE} \ + or #{NSXConstants::NSXV_LS_TYPE}" + error = NSXError::UnknownObject.new(error_msg) + raise error + end + break + end + + nic_data = { + :id => nic_id, + :name => nic_name, + :network_name => network_name, + :network_id => network_id, + :network_vcref => network_vcref, + :lp => nic_lp + } + + nic_data + end + + # Create OpenNebula fw rules for an instance (given a template) + def create_rules(deploy_id, template, only_attached) + template_xml = Nokogiri::XML(template) + + # OpenNebula host + host_name = template_xml + .xpath('//HISTORY_RECORDS/HISTORY[last()]/HOSTNAME') + .text + one_host = VCenterDriver::VIHelper + .find_by_name(OpenNebula::HostPool, host_name) + rc = one_host.info + if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg + end + host_id = one_host['ID'] + + # OpenNebula VM + one_vm = VCenterDriver::VIHelper + .one_item(OpenNebula::VirtualMachine, deploy_id) + + vm_data = { + :id => template_xml.xpath('/VM/ID').text, + :deploy_id => deploy_id + } + + # vCenter VirtualMachine + vi_client = VCenterDriver::VIClient.new_from_host(host_id) + vm = VCenterDriver::VirtualMachine + .new_one(vi_client, deploy_id, one_vm) + + # NSX Objects needed + ls = LogicalSwitch.new(@nsx_client) + + # Search NSX Nics + # First try to search only new attached NSX Nics + nsx_nics = ls.nsx_nics(template_xml, only_attached) + # If there is no NSX Nics + return if nsx_nics.empty? + + # Create rules for each NSX Nic + nsx_nics.each do |nic| + # Extract NIC data + nic_data = extract_nic_data(nic, @nsx_client, vm) + # Get all Security Groups belonging to each NIC. + sec_groups = nic.xpath('SECURITY_GROUPS').text.split(',') + sec_groups.each do |sec_group| + sg_rules_array = [] + # Get all rules belonging to this Security Group. + xp = "//SECURITY_GROUP_RULE[SECURITY_GROUP_ID=#{sec_group}]" + sg_rules = template_xml.xpath(xp) + sg_rules.each do |sg_rule| + # Create rules spec + rule_data = extract_rule_data(sg_rule) + rule_spec = rule_spec(rule_data, + vm_data, + nic_data, + @nsx_client) + sg_rules_array.push(rule_spec) + end + # Create NSX rules + sg_rules_array.each do |sg_spec| + create_rule(sg_spec) + end + end + end + end + + def clear_all_rules(template) + template_xml = Nokogiri::XML(template) + vm_id = template_xml.xpath('/VM/ID').text + vm_deploy_id = template_xml.xpath('/VM/DEPLOY_ID').text + regex = "-#{vm_id}-#{vm_deploy_id}-" + rules = rules_by_regex(regex, @one_section_id) + rules.each do |rule| + delete_rule(rule['id'], @one_section_id) if rule + end + end + + # Remove OpenNebula created fw rules for an instance (given a template) + def clear_rules(template, only_detached) + template_xml = Nokogiri::XML(template) + # OpenNebula Instance IDs + vm_id = template_xml.xpath('/VM/ID').text + vm_deploy_id = template_xml.xpath('/VM/DEPLOY_ID').text + + # Search NSX Nics + ls = LogicalSwitch.new(@nsx_client) + # First try to search only new attached NSX Nics + nsx_nics = ls.nsx_nics(template_xml, only_detached) + + # If there is no NSX Nics + return if nsx_nics.empty? + + nsx_nics.each do |nic| + nic_id = nic.xpath('NIC_ID').text + # network_id = nic.xpath('NETWORK_ID').text + sec_groups = nic.xpath('SECURITY_GROUPS').text.split(',') + sec_groups.each do |sec_group| + # Get Security Group ID and NAME + xp = "//SECURITY_GROUP_RULE[SECURITY_GROUP_ID=#{sec_group}]" + sg_id = template_xml.xpath(xp)[0] + .xpath('SECURITY_GROUP_ID').text + sg_name = template_xml.xpath(xp)[0] + .xpath('SECURITY_GROUP_NAME').text + rule_name = "#{sg_id}-#{sg_name}-#{vm_id}" + rule_name << "-#{vm_deploy_id}-#{nic_id}" + rules = rules_by_name(rule_name, @one_section_id) + rules.each do |rule| + delete_rule(rule['id'], @one_section_id) if rule + end + end + end + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/logical_port.rb b/src/vmm_mad/remotes/lib/nsx_driver/logical_port.rb new file mode 100644 index 0000000000..2c27f7c33c --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/logical_port.rb @@ -0,0 +1,56 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + # Class Logical Switch + class LogicalPort < NSXComponent + + # ATTRIBUTES + + # CONSTRUCTOR + + def initialize(nsx_client) + super(nsx_client) + end + + def self.new_child(nsx_client, id = nil) + case nsx_client.nsx_type.upcase + when NSXConstants::NSXT + NSXTLogicalPort.new(nsx_client, id) + when NSXConstants::NSXV + NSXVLogicalPort.new(nsx_client, id) + else + error_msg = "Unknown object type: #{type}" + error = NSXError::UnknownObject.new(error_msg) + raise error + end + end + + # Check if logical port exists + def lp?; end + + # Get logical port id + def lp_id; end + + # Get logical port display name + def lp_name; end + + # Get resource type + def lp_type; end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/logical_switch.rb b/src/vmm_mad/remotes/lib/nsx_driver/logical_switch.rb index 5d00e671ce..a02dfd3036 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/logical_switch.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/logical_switch.rb @@ -16,7 +16,7 @@ module NSXDriver # Class Logical Switch - class LogicalSwitch < NSXDriver::NSXComponent + class LogicalSwitch < NSXComponent # ATTRIBUTES attr_reader :ls_id @@ -51,6 +51,33 @@ module NSXDriver # Update a logical switch def update_logical_switch; end + # Return nsx nics of type NSX-V and NSX-T + # If only_new_attached = true --> Only returns new attached nsx nics + def nsx_nics(template_xml, only_new_attached = true) + if only_new_attached == true + nics = template_xml.xpath('//TEMPLATE/NIC[ATTACH="YES"]') + else + nics = template_xml.xpath('//TEMPLATE/NIC') + end + nics_array = [] + nics.each do |nic| + network_id = nic.xpath('NETWORK_ID').text + # Check Networks exists + one_vnet = VCenterDriver::VIHelper + .one_item(OpenNebula::VirtualNetwork, network_id) + rc = one_vnet.info + if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg + end + pg_type = one_vnet['TEMPLATE/VCENTER_PORTGROUP_TYPE'] + nics_array << nic if [NSXConstants::NSXV_LS_TYPE, + NSXConstants::NSXT_LS_TYPE] + .include?(pg_type) + end + nics_array + end + end end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsx_client.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsx_client.rb index 9d36ed4d3d..591fa06388 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsx_client.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsx_client.rb @@ -60,13 +60,13 @@ module NSXDriver def self.new_child(nsxmgr, nsx_user, nsx_password, type) case type.upcase - when NSXDriver::NSXConstants::NSXT - NSXDriver::NSXTClient.new(nsxmgr, nsx_user, nsx_password) - when NSXDriver::NSXConstants::NSXV - NSXDriver::NSXVClient.new(nsxmgr, nsx_user, nsx_password) + when NSXConstants::NSXT + NSXTClient.new(nsxmgr, nsx_user, nsx_password) + when NSXConstants::NSXV + NSXVClient.new(nsxmgr, nsx_user, nsx_password) else error_msg = "Unknown object type: #{type}" - error = NSXDriver::NSXError::UnknownObject.new(error_msg) + error = NSXError::UnknownObject.new(error_msg) raise error end end @@ -83,7 +83,7 @@ module NSXDriver nsxmgr = host['TEMPLATE/NSX_MANAGER'] nsx_user = host['TEMPLATE/NSX_USER'] - nsx_password = NSXDriver::NSXClient + nsx_password = NSXClient .nsx_pass(host['TEMPLATE/NSX_PASSWORD']) nsx_type = host['TEMPLATE/NSX_TYPE'] @@ -92,11 +92,20 @@ module NSXDriver # METHODS + # Return response if match with responses codes, If response not match + # with expected responses codes then raise an IncorrectResponseCodeError def check_response(response, codes_array) - codes_array.each do |code| - return true if response.code.to_i == code + unless response.nil? + return response if codes_array.include?(response.code.to_i) + + response_json = JSON.parse(response.body) + nsx_error = "\nNSX error code: " \ + "#{response_json['errorCode']}, " \ + "\nNSX error details: " \ + "#{response_json['details']}" + raise NSXError::IncorrectResponseCodeError, nsx_error end - false + raise NSXError::IncorrectResponseCodeError, nsx_error end def self.nsx_pass(nsx_pass_enc) @@ -114,17 +123,23 @@ module NSXDriver end # Return: respose.body - def get(url); end + def get(url, aditional_headers = []); end + + # Return: response + def get_full_response(url, aditional_headers = []); end # Return: id of the created object - def post(url, data); end + def post(url, data, aditional_headers = []); end - def put(url, data); end + def put(url, data, aditional_headers = []); end def delete(url); end def get_token(url); end + # Prepare headers + def add_headers(aditional_headers = []); end + end end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsx_constants.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsx_constants.rb index 9b6b6e4f4a..795206fefa 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsx_constants.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsx_constants.rb @@ -54,6 +54,7 @@ module NSXDriver NSXT_TZS = NSXT_BASE + '/transport-zones' # VirtualWire NSXV_AUTH = NSXV_BASE + '/services/auth/token' + NSXV_LS_TYPE = 'NSX-V' NSXV_LS_NAME_XPATH = '//virtualWire/name' NSXV_LS_VNI_XPATH = '//virtualWire/vdnId' NSXV_LS_BACKING_XPATH = '//virtualWire/vdsContextWithBacking' \ @@ -66,6 +67,7 @@ module NSXDriver NSXV_TZ_XPATH = '//virtualWire/vdnScopeId' # OpaqueNetwork NSXT_AUTH = NSXT_BASE + '/aaa/registration-token' + NSXT_LS_TYPE = 'Opaque Network' NSXT_LS_SECTION = NSXT_BASE + '/logical-switches/' # DFW ONE_SECTION_NAME = 'OpenNebula' @@ -75,6 +77,43 @@ module NSXDriver NSXV_DFW_SECTIONS = '/layer3sections' NSXV_DFW_SECTION_XPATH = '//section' NSXV_DFW_RULE_XPATH = '//rule' + # RULE + NSXT_RULE_BASE = NSXT_BASE + '/firewall/rules' + NSXT_RULE_PROTOCOL = { + 'TCP' => { + :service => { + :l4_protocol => 'TCP', + :source_ports => [], + :destination_ports => [], + :resource_type => 'L4PortSetNSService' + } + }, + 'UDP' => { + :service => { + :l4_protocol => 'UDP', + :source_ports => [], + :destination_ports => [], + :resource_type => 'L4PortSetNSService' + } + }, + 'ICMP' => { + :service => { + :protocol => 'ICMPv4', + :resource_type => 'ICMPTypeNSService' + } + }, + 'ICMPv6' => { + :service => { + :protocol => 'ICMPv6', + :resource_type => 'ICMPTypeNSService' + } + } + } + NSXV_RULE_BASE = 'xxx' + NSX_RULE_IPSEC_PORTS = %w[500 4500] + # Logical Ports + NSXT_LP_BASE = NSXT_BASE + '/logical-ports/' + NSXV_LP_BASE = '' # Messages MSG_INCOMPLETE_REQ = 'Incomplete request, NSX_MANAGER, NSX_USER, \ NSX_PASSWORD and NSX_TYPE are needed' diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsx_error.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsx_error.rb index a9aa978682..5ca38f4e9d 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsx_error.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsx_error.rb @@ -62,6 +62,16 @@ module NSXDriver end + # Class DeleteError + class MissingParameter < NSXError + + def initialize(parameter) + msg = "Missing NSX parameter #{parameter}" + super(msg) + end + + end + end end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsx_rule.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsx_rule.rb new file mode 100644 index 0000000000..27b43251c2 --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsx_rule.rb @@ -0,0 +1,191 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +require 'ipaddr' + +# Module NSXDriver +module NSXDriver + + ONE_LOCATION = ENV['ONE_LOCATION'] unless defined?(ONE_LOCATION) + + if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' \ + unless defined?(RUBY_LIB_LOCATION) + GEMS_LOCATION = '/usr/share/one/gems' \ + unless defined?(GEMS_LOCATION) + else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' \ + unless defined?(RUBY_LIB_LOCATION) + GEMS_LOCATION = ONE_LOCATION + '/share/gems' \ + unless defined?(GEMS_LOCATION) + end + + if File.directory?(GEMS_LOCATION) + Gem.use_paths(GEMS_LOCATION) + end + + $LOAD_PATH << RUBY_LIB_LOCATION + + require 'nsxt_rule' + require 'nsxv_rule' + + # Class Logical Switch + module NSXRule + + include NSXTRule + include NSXVRule + + def to_nets(ip_start, size) + nets = [] + ipaddr = IPAddr.new ip_start + ip_i = ipaddr.to_i + + if ipaddr.ipv4? + ip_length = 32 + elsif ipaddr.ipv6? + ip_length = 128 + else + return + end + + # Find the largest address block (look for the first 1-bit) + lblock = 0 + + lblock += 1 while ip_i[lblock] == 0 && lblock < ip_length + + # Allocate whole blocks till the size fits + while size >= 2**lblock + nets << "#{IPAddr.new(ip_i, ipaddr.family)}" \ + "/#{ip_length-lblock}" + + ip_i += 2**lblock + size -= 2**lblock + + lblock += 1 while ip_i[lblock] == 0 && lblock < ip_length + end + + # Fit remaining address blocks + ip_length.downto(0) do |i| + next if size[i] == 0 + + nets << "#{IPAddr.new(ip_i, ipaddr.family)}/#{ip_length-i}" + + ip_i += 2**i + end + + nets + end + + # Adapt port from ["22, 443"] to '22, 443' + # Adapt port from ["22", "443"] to '22, 443' + def parse_ports(rule_ports) + unless rule_ports.empty? + rule_ports = rule_ports.join(',') + end + rule_ports + end + + def extract_vnet_data(vnet_id) + if vnet_id == '' + return { + :nsxid => '', + :name => '' + } + end + # Create client to communicate with OpenNebula + one_client = OpenNebula::Client.new + # Get the network XML from OpenNebula + # This is potentially different from the Netowrk Template + # provided as the API call argument + one_vnet = OpenNebula::VirtualNetwork.new_with_id(vnet_id, + one_client) + rc = one_vnet.info + if OpenNebula.is_error?(rc) + err_msg = rc.message + raise CreateNetworkError, err_msg + end + vnet_data = { + :nsxid => one_vnet['TEMPLATE/NSX_ID'], + :name => one_vnet['NAME'] + } + vnet_data + end + + def extract_rule_data(xml_rule) + sg_id = xml_rule.xpath('SECURITY_GROUP_ID').text + sg_name = xml_rule.xpath('SECURITY_GROUP_NAME').text + in_out = xml_rule.xpath('RULE_TYPE').text.upcase + in_out == 'INBOUND' ? sg_direction = 'IN' : sg_direction = 'OUT' + # Protocol: TCP, UDP, ICMP... + sg_protocol = xml_rule.xpath('PROTOCOL').text + if sg_protocol == 'ICMP' + sg_icmp_type = xml_rule.xpath('ICMP_TYPE').text + end + # OpenNebula network ID + sg_network_id = xml_rule.xpath('NETWORK_ID').text + vnet_data = extract_vnet_data(sg_network_id) + + # ip / netmask + sg_ip = xml_rule.xpath('IP').text + sg_ipsize = xml_rule.xpath('SIZE').text + sg_subnets = [] + if sg_ip != '' && sg_ipsize != '' + sg_subnets = to_nets(sg_ip, sg_ipsize.to_i) + end + # Ports + sg_ports = '' + sg_range_port = xml_rule.xpath('RANGE').text + if sg_range_port + if sg_range_port.index(':') + sg_port_from = sg_range_port[0..sg_range_port.index(':')-1] + sg_port_to = sg_range_port[sg_range_port.index(':')+1, + sg_range_port.length] + sg_ports = "#{sg_port_from}-#{sg_port_to}" + else + sg_ports = sg_range_port + end + end + # Create hash with data + rule_data = { + :id => sg_id, + :name => sg_name, + :direction => sg_direction, + :protocol => sg_protocol, + :icmp_type => sg_icmp_type, + :network_id => sg_network_id, + :network_name => vnet_data[:name], + :network_nsxid => vnet_data[:nsxid], + :subnets => sg_subnets, + :ports => sg_ports.split(',') + } + + rule_data + end + + def rule_spec(rule, vm_data, nic_data, nsx_client) + case nsx_client.nsx_type + when NSXDriver::NSXConstants::NSXT + nsxt_rule_spec(rule, vm_data, nic_data) + when NSXDriver::NSXConstants::NSXV + nsxv_rule_spec(rule, vm_data, nic_data) + else + raise "Unsupported NSX type: #{nsx_type}" + end + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_client.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_client.rb index 7643e5099f..9a90954a26 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_client.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_client.rb @@ -37,7 +37,7 @@ module NSXDriver $LOAD_PATH << RUBY_LIB_LOCATION # Class NSXTClient - class NSXTClient < NSXDriver::NSXClient + class NSXTClient < NSXClient # ATTIBUTES attr_accessor :nsxmgr @@ -48,133 +48,122 @@ module NSXDriver # CONSTRUCTORS def initialize(nsxmgr, nsx_user, nsx_password) super(nsxmgr, nsx_user, nsx_password) - @nsx_type = NSXDriver::NSXConstants::NSXT + @nsx_type = NSXConstants::NSXT + end + + # Prepare headers + def add_headers(aditional_headers = []) + headers = NSXConstants::HEADER_JSON.clone + unless aditional_headers.empty? + aditional_headers.each do |header| + headers[header.keys[0]] = header.values[0] + end + end + headers end # METHODS - def get(url) - uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Get.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_JSON) - request.basic_auth(@nsx_user, @nsx_password) - begin - response = Net::HTTP - .start(uri.host, - uri.port, - :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE)\ - do |https| - https.request(request) - end - rescue StandardError => e - raise e + def get(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK, + NSXConstants::CODE_NO_CONTENT] end - return JSON.parse(response.body) \ - if check_response(response, [NSXDriver::NSXConstants::CODE_OK]) + uri = URI.parse(@nsxmgr + url) + headers = add_headers(aditional_headers) + request = Net::HTTP::Get.new(uri.request_uri, headers) + request.basic_auth(@nsx_user, @nsx_password) + response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) + JSON.parse(response.body) end - def get_full_response(url) - uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Get.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_JSON) - request.basic_auth(@nsx_user, @nsx_password) - begin - response = Net::HTTP - .start(uri.host, - uri.port, - :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE)\ - do |https| - https.request(request) - end - rescue StandardError => e - raise e + def get_full_response(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK, + NSXConstants::CODE_NO_CONTENT] end - return response \ - if check_response(response, [NSXDriver::NSXConstants::CODE_OK]) + uri = URI.parse(@nsxmgr + url) + headers = add_headers(aditional_headers) + request = Net::HTTP::Get.new(uri.request_uri, headers) + request.basic_auth(@nsx_user, @nsx_password) + response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + check_response(response, valid_codes) end # Return: id of the created object - def post(url, data) + def post(url, data, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_CREATED, + NSXConstants::CODE_OK] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Post.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_JSON) + headers = add_headers(aditional_headers) + request = Net::HTTP::Post.new(uri.request_uri, headers) request.body = data request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) response_json = JSON.parse(response.body) - # If response is different as expected raise the message - unless check_response(response, - [NSXDriver::NSXConstants::CODE_CREATED]) - error_msg = "\nNSX error code: " \ - "#{response_json['errorCode']}, " \ - "\nNSX error details: " \ - "#{response_json['details']}" - error = NSXDriver::NSXError::IncorrectResponseCodeError - .new(error_msg) - raise error - end - response_json['id'] end - def put(url, data) + def put(url, data, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_CREATED, + NSXConstants::CODE_OK] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Put.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_JSON) + headers = add_headers(aditional_headers) + request = Net::HTTP::Put.new(uri.request_uri, headers) request.body = data request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) response_json = JSON.parse(response.body) - # If response is different as expected raise the message - unless check_response(response, - [NSXDriver::NSXConstants::CODE_CREATED]) - error_msg = "\nNSX error code: " \ - "#{response_json['errorCode']}, " \ - "\nNSX error details: " \ - "#{response_json['details']}" - error = NSXDriver::NSXError::IncorrectResponseCodeError - .new(error_msg) - raise error - end - response_json['id'] end - def delete(url) + def delete(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK, + NSXConstants::CODE_NO_CONTENT] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Delete - .new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_JSON) + headers = add_headers(aditional_headers) + request = Net::HTTP::Delete.new(uri.request_uri, headers) request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - check_response(response, [NSXDriver::NSXConstants::CODE_OK]) + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + check_response(response, valid_codes) end - def get_token(url) + def get_token(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Post.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_JSON) + headers = add_headers(aditional_headers) + request = Net::HTTP::Post.new(uri.request_uri, headers) request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - - return unless check_response(response, - [NSXDriver::NSXConstants::CODE_OK]) - + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) response.body end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_dfw.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_dfw.rb new file mode 100644 index 0000000000..e0611083fa --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_dfw.rb @@ -0,0 +1,200 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + # Class Logical Switch + class NSXTdfw < DistributedFirewall + + # ATTRIBUTES + attr_reader :one_section_id + + # CONSTRUCTOR + # Creates OpenNebula section if not exists + def initialize(nsx_client) + super(nsx_client) + # Construct base URLs + @base_url = NSXConstants::NSXT_DFW_BASE + @url_sections = @base_url + \ + NSXConstants::NSXT_DFW_SECTIONS + @one_section_id = init_section + end + + # Sections + # Creates OpenNebula section if not exists and returns + # its section_id. Returns its section_id if OpenNebula + # section already exists + def init_section + one_section = section_by_name( + NSXConstants::ONE_SECTION_NAME + ) + one_section ||= create_section( + NSXConstants::ONE_SECTION_NAME + ) + return one_section['id'] if one_section + end + + # Get all sections + # Params: + # - None + # Return + # - nil | sections + def sections + result = @nsx_client.get(@url_sections) + result['results'] + end + + # Get section by id + # Params: + # - section_id: [String] ID of the section or @one_section_id + # Return + # - nil | section + def section_by_id(section_id = @one_section_id) + url = @url_sections + '/' + section_id + @nsx_client.get(url) + end + + # Get section by name + # Params: + # - section_name: Name of the section + # Return + # - nil | section + def section_by_name(section_name) + result = nil + all_sections = sections + return result unless all_sections + + all_sections.each do |section| + result = section if section['display_name'] == section_name + end + result + end + + # Create new section and return the section + def create_section(section_name) + section_spec = %( + { + "display_name": "#{section_name}", + "section_type": "LAYER3", + "stateful": true + } + ) + section_id = @nsx_client.post(@url_sections, section_spec) + result = section_by_id(section_id) + raise 'Section was not created in DFW' unless result + + result + end + + # Delete section + # Params: + # - section_id: [String] ID of the section or @one_section_id + def delete_section(section_id = @one_section_id) + url = @url_sections + '/' + section_id + @nsx_client.delete(url) + end + + # Rules + # Get all rules of a Section, OpenNebula section if it's not defined + # Return: + # - [Array] + def rules(section_id = @one_section_id) + url = @url_sections + '/' + section_id + '/rules' + @nsx_client.get(url) + end + + # Get rule by id + # Return: + # rule | nil + def rule_by_id(rule_id) + url = @base_url + '/rules/' + rule_id + valid_codes = [NSXConstants::CODE_CREATED, + NSXConstants::CODE_OK, + NSXConstants::CODE_BAD_REQUEST, + NSXConstants::CODE_NOT_FOUND] + additional_headers = [] + @nsx_client.get(url, additional_headers, valid_codes) + end + + # Get rules by name + # Return: + # - Array with rules or an empty array + def rules_by_name(rule_name, section_id = @one_section_id) + rules = [] + return rules unless section_id + + all_rules = rules(section_id) + return rules unless all_rules + + all_rules['results'].each do |rule| + rules << rule if rule['display_name'] == rule_name + end + rules + end + + # Get rule by regex + # Return: + # - Array with rules or an empty array + def rules_by_regex(regex, section_id = @one_section_id) + rules = [] + return rules unless section_id + + all_rules = rules(section_id) + return rules unless all_rules + + all_rules['results'].each do |rule| + rules << rule if rule['display_name'].match(regex) + end + rules + end + + # Create new rule + def create_rule(rule_spec, section_id = @one_section_id) + # Get revision from section + section = section_by_id(section_id) + unless section + error_msg = "Section with id #{section_id} not found" + error = NSXError::ObjectNotFound + .new(error_msg) + raise error + end + revision_id = section['_revision'] + rule_spec['_revision'] = revision_id + rule_spec = rule_spec.to_json + url = @url_sections + '/' + section_id + '/rules' + @nsx_client.post(url, rule_spec) + end + + # Update rule + def update_rule(rule_id, rule_spec, section_id = @one_section_id) + url = @url_sections + '/' + section_id + '/rules/' + rule_id + rule = rule_by_id(rule_id) + raise "Rule id #{rule_id} not found" unless rule + + rule_spec['_revision'] = rule['_revision'] + rule_spec = rule_spec.to_json + @nsx_client.put(url, rule_spec) + end + + # Delete rule + def delete_rule(rule_id, section_id = @one_section_id) + url = @url_sections + '/' + section_id + '/rules/' + rule_id + # Delete receive a 200 OK also if the rule doesn't exist + @nsx_client.delete(url) + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_logical_port.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_logical_port.rb new file mode 100644 index 0000000000..51e175829c --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_logical_port.rb @@ -0,0 +1,94 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + # Class NSXTLogicalPort + class NSXTLogicalPort < LogicalPort + + # ATTRIBUTES + attr_reader :id, :name, :type, :url + + # CONSTRUCTOR + # Logical port class variables: + # @lp_id + # @url_lp + # @lp_name + # @lp_type + def initialize(nsx_client, id = nil, data = nil) + super(nsx_client) + # lpid can be: + # - Logical port attach ID + if id + initialize_with_id(id) + else + if data + begin + @id = new_logical_port(data) + rescue NSXError::IncorrectResponseCodeError => e + raise 'Logical Port not created in ' \ + "NSX Manager: #{e.message}" + end + unless @id + raise 'Logical Port not created in NSX Manager: '\ + 'generic error' + end + # Construct logical port class variables + @url = NSXConstants::NSXT_LP_BASE + @id + @name = lp_name + @type = lp_type + end + end + end + + # Creates a NSXTLogicalPort from its id + def initialize_with_id(id) + @id = lp_with_attachid(id) + # Construct URL of the created logical switch + @url = NSXConstants::NSXT_LP_BASE + @id + return unless lp? + + @name = lp_name + @type = lp_type + end + + # Check if logical port exists + def lp? + @nsx_client.get(@url) + end + + # Get logical port id from attach id + def lp_with_attachid(attach_id) + lps = @nsx_client.get(NSXConstants::NSXT_LP_BASE) + lps['results'].each do |lp| + return lp['id'] if lp['attachment']['id'] == attach_id + end + end + + # # Get logical port display name + def lp_name + lp = @nsx_client.get(@url) + lp['display_name'] + end + + # # Get resource type + def lp_type + lp = @nsx_client.get(@url) + lp['resource_type'] + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_rule.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_rule.rb new file mode 100644 index 0000000000..bb194fe18c --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_rule.rb @@ -0,0 +1,188 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + module NSXRule + + # Class Logical Switch + module NSXTRule + + def nsxt_rule_spec(rule, vm_data, nic_data) + # default spec + # Allow any-any to any port applied on the + # virtual machine logical port + rule_name = "#{rule[:id]}-#{rule[:name]}-#{vm_data[:id]}" + rule_name << "-#{vm_data[:deploy_id]}-#{nic_data[:id]}" + rule_spec = { + :display_name => rule_name, + :destinations_excluded => false, + :sources => [], + :destinations => [], + :services => [], + :applied_tos => [ + { + :target_id => nic_data[:lp].id, + :target_display_name => nic_data[:name], + :target_type => nic_data[:lp].type, + :is_valid => true + } + ], + :ip_protocol => 'IPV4_IPV6', + :logged => false, + :action => 'ALLOW', + :sources_excluded => false, + :disabled => false, + :direction => rule[:direction] + } + + rule_protocol_template = { + 'TCP' => [ + { + :service => { + :l4_protocol => 'TCP', + :source_ports => [], + :destination_ports => [], + :resource_type => 'L4PortSetNSService' + } + } + ], + 'UDP' => [ + { + :service => { + :l4_protocol => 'UDP', + :source_ports => [], + :destination_ports => [], + :resource_type => 'L4PortSetNSService' + } + } + ], + 'ICMP' => [ + { + :service => { + :protocol => 'ICMPv4', + :resource_type => 'ICMPTypeNSService' + } + } + ], + 'ICMPv6' => [ + { + :service => { + :protocol => 'ICMPv6', + :resource_type => 'ICMPTypeNSService' + } + } + ], + 'IPSEC' => [ + { + :service => { + :l4_protocol => 'UDP', + :source_ports => [], + :destination_ports => [], + :resource_type => 'L4PortSetNSService' + } + }, + { + :service => { + :protocol_number => 50, + :resource_type => 'IPProtocolNSService' + } + }, + { + :service => { + :protocol_number => 51, + :resource_type => 'IPProtocolNSService' + } + } + ] + } + + # Modify default rule spec based on rule_data extracted + # from vm template + + ###### SOURCES / DESTINATIONS: Any | IP Address | Vnet ##### + src_or_dst = [] + + # Target network: Vnet + if !rule[:network_id].empty? + + src_or_dst << { + :target_id => rule[:network_nsxid], + :target_display_name => rule[:network_name], + :target_type => 'LogicalSwitch', + :is_valid => true + } + + # Target network: Manual network (IP Address) + elsif !rule[:subnets].empty? + rule[:subnets].each do |subnet| + src_or_dst << { + :target_id => subnet, + :target_display_name => subnet, + :target_type => 'IPAddress', + :is_valid => true + } + end + end + + # (OpenNebula) INBOUND => Destination (NSX) + # (OpenNebula) OUTBOUND => Source (NSX) + unless src_or_dst.empty? + rule_spec[:sources] = src_or_dst \ + if rule[:direction] == 'IN' + rule_spec[:destinations] = src_or_dst \ + if rule[:direction] == 'OUT' + end + + ##### SERVICES ##### + services = [] + service = rule_protocol_template[rule[:protocol]] + + case rule[:protocol] + when 'TCP' + service[0][:service][:source_ports] = rule[:ports] \ + if rule[:direction] == 'IN' + service[0][:service][:destination_ports] = rule[:ports] \ + if rule[:direction] == 'OUT' + when 'UDP' + service[0][:service][:source_ports] = rule[:ports] \ + if rule[:direction] == 'IN' + service[0][:service][:destination_ports] = rule[:ports] \ + if rule[:direction] == 'OUT' + # when 'ICMP' + # when 'ICMPv6' + when 'IPSEC' + ipsec_ports = NSXConstants::NSX_RULE_IPSEC_PORTS + service[0][:service][:source_ports] = ipsec_ports \ + if rule[:direction] == 'IN' + service[0][:service][:destination_ports] = ipsec_ports \ + if rule[:direction] == 'OUT' + end + + if rule[:protocol] != 'ALL' && !service.empty? + service.each do |s| + services << s + end + rule_spec[:services] = services + end + + rule_spec + end + + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_tz.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_tz.rb index c73b1b285d..f9423b815f 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsxt_tz.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxt_tz.rb @@ -16,7 +16,7 @@ module NSXDriver # Class Transport Zone - class NSXTtz < NSXDriver::TransportZone + class NSXTtz < TransportZone # ATTRIBUTES attr_reader :tz_id @@ -25,7 +25,7 @@ module NSXDriver def initialize(nsx_client) super(nsx_client) # Construct base URLs - @url_tzs_nsxt = NSXDriver::NSXConstants::NSXT_TZS + @url_tzs_nsxt = NSXConstants::NSXT_TZS end # METHODS diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_client.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_client.rb index 2fffe23b7b..c003150bd6 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_client.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_client.rb @@ -37,7 +37,7 @@ module NSXDriver $LOAD_PATH << RUBY_LIB_LOCATION # Class NSXVClient - class NSXVClient < NSXDriver::NSXClient + class NSXVClient < NSXClient # ATTIBUTES attr_accessor :nsxmgr @@ -48,130 +48,120 @@ module NSXDriver # CONSTRUCTORS def initialize(nsxmgr, nsx_user, nsx_password) super(nsxmgr, nsx_user, nsx_password) - @nsx_type = NSXDriver::NSXConstants::NSXV + @nsx_type = NSXConstants::NSXV + end + + # Prepare headers + def add_headers(aditional_headers = []) + headers = NSXConstants::HEADER_XML.clone + unless aditional_headers.empty? + aditional_headers.each do |header| + headers[header.keys[0]] = header.values[0] + end + end + headers end # METHODS - def get(url) - uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Get.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_XML) - request.basic_auth(@nsx_user, @nsx_password) - begin - response = Net::HTTP - .start(uri.host, - uri.port, - :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE)\ - do |https| - https.request(request) - end - rescue StandardError => e - raise e + def get(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK, + NSXConstants::CODE_NO_CONTENT] end - return Nokogiri::XML response.body \ - if check_response(response, [NSXDriver::NSXConstants::CODE_OK]) + uri = URI.parse(@nsxmgr + url) + headers = add_headers(aditional_headers) + request = Net::HTTP::Get.new(uri.request_uri, headers) + request.basic_auth(@nsx_user, @nsx_password) + response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) + Nokogiri::XML response.body end - def get_full_response(url) - uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Get.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_XML) - request.basic_auth(@nsx_user, @nsx_password) - begin - response = Net::HTTP - .start(uri.host, - uri.port, - :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE)\ - do |https| - https.request(request) - end - rescue StandardError => e - raise e + def get_full_response(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK, + NSXConstants::CODE_NO_CONTENT] end - return response \ - if check_response(response, [NSXDriver::NSXConstants::CODE_OK]) + uri = URI.parse(@nsxmgr + url) + headers = add_headers(aditional_headers) + request = Net::HTTP::Get.new(uri.request_uri, headers) + request.basic_auth(@nsx_user, @nsx_password) + response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + check_response(response, valid_codes) end # Return: id of the created object - def post(url, data) + def post(url, data, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_CREATED, + NSXConstants::CODE_OK] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Post.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_XML) + headers = add_headers(aditional_headers) + request = Net::HTTP::Post.new(uri.request_uri, headers) request.body = data request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - - # If response is different as expected raise the message - unless check_response(response, - [NSXDriver::NSXConstants::CODE_CREATED]) - response_json = JSON.parse(response.body) - nsx_error = "\nNSX error code: " \ - "#{response_json['errorCode']}, " \ - "\nNSX error details: " \ - "#{response_json['details']}" - raise NSXDriver::NSXError::IncorrectResponseCodeError, \ - nsx_error - end - + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) response.body end - def put(url, data) + def put(url, data, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_CREATED, + NSXConstants::CODE_OK] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Put.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_XML) + headers = add_headers(aditional_headers) + request = Net::HTTP::Put.new(uri.request_uri, headers) request.body = data request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - - # If response is different as expected raise the message - unless check_response(response, - [NSXDriver::NSXConstants::CODE_CREATED]) - response_json = JSON.parse(response.body) - nsx_error = "\nNSX error code: " \ - "#{response_json['errorCode']}, " \ - "\nNSX error details: " \ - "#{response_json['details']}" - raise NSXDriver::NSXError::IncorrectResponseCodeError, \ - nsx_error - end - + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) response.body end - def delete(url) + def delete(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK, + NSXConstants::CODE_NO_CONTENT] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Delete.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_XML) + headers = add_headers(aditional_headers) + request = Net::HTTP::Delete.new(uri.request_uri, headers) request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - check_response(response, [NSXDriver::NSXConstants::CODE_OK]) + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + check_response(response, valid_codes) end - def get_token(url) + def get_token(url, aditional_headers = [], valid_codes = []) + if valid_codes.empty? + valid_codes = [NSXConstants::CODE_OK] + end uri = URI.parse(@nsxmgr + url) - request = Net::HTTP::Post.new(uri.request_uri, - NSXDriver::NSXConstants::HEADER_XML) + headers = add_headers(aditional_headers) + request = Net::HTTP::Post.new(uri.request_uri, headers) request.basic_auth(@nsx_user, @nsx_password) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => true, - :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| - https.request(request) - end - - return unless check_response(response, - [NSXDriver::NSXConstants::CODE_OK]) - + :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https| + https.request(request) + end + response = check_response(response, valid_codes) response_xml = Nokogiri::XML response.body token = response_xml.xpath('//authToken/value').text { 'token' => token }.to_json diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_dfw.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_dfw.rb new file mode 100644 index 0000000000..37facd2b84 --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_dfw.rb @@ -0,0 +1,204 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + # Class Logical Switch + class NSXVdfw < DistributedFirewall + + # ATTRIBUTES + attr_reader :one_section_id + + # CONSTRUCTOR + # Creates OpenNebula section if not exists + def initialize(nsx_client) + super(nsx_client) + # Construct base URLs + @base_url = NSXConstants::NSXV_DFW_BASE + @url_sections = @base_url + \ + NSXConstants::NSXV_DFW_SECTIONS + @one_section_id = init_section + end + + # Sections + # Get all sections + # Creates OpenNebula section if not exists and returns + # its section_id. Returns its section_id if OpenNebula + # section already exists + def init_section + one_section = section_by_name( + NSXConstants::ONE_SECTION_NAME + ) + one_section ||= create_section( + NSXConstants::ONE_SECTION_NAME + ) + return one_section.xpath('@id').text if one_section + end + + # Get all sections + # Params: + # - None + # Return: + # - nil | [Nokogiri::XML::NodeSet] sections + def sections + result = @nsx_client.get(@base_url) + xp = NSXConstants::NSXV_DFW_SECTION_XPATH + sections = result.xpath(xp) + return sections unless sections.empty? + end + + # Get section by id + # Params: + # - section_id: [String] ID of the section or @one_section_id + # Return: + # - nil | [Nokogiri::XML::NodeSet] section + def section_by_id(section_id = @one_section_id) + url = @url_sections + '/' + section_id + result = @nsx_client.get(url) + xp = NSXConstants::NSXV_DFW_SECTION_XPATH + section = result.xpath(xp) + return section unless section.empty? + end + + # Get section etag needed to manage FW rules + # Params: + # - section_id: [String] ID of the section or @one_section_id + # Return: + # - nil | etag [String] ID of the etag header + def section_etag(section_id = @one_section_id) + url = @url_sections + '/' + section_id + response = @nsx_client.get_full_response(url) + etag = response['etag'] + return etag.delete('\"') if etag + end + + # Get section by name + # Params: + # - section_name: [String] Name of the section + # Return: + # - nil | [Nokogiri::XML::NodeSet] section + def section_by_name(section_name) + url = @url_sections + '?name=' + section_name + result = @nsx_client.get(url) + xp = NSXConstants::NSXV_DFW_SECTION_XPATH + section = result.xpath(xp) + return section unless section.empty? + end + + # Create new section + # Params: + # - section_name [String] Name of the section + # Return: + # - [Nokogiri::XML::NodeSet] + def create_section(section_name) + section_spec = + "
\ +
" + + section = @nsx_client.post(@url_sections, section_spec) + section_id = section.xpath('//section/@id').text + result = section_by_id(section_id) + raise 'Section was not created in DFW' unless result + + result + end + + # Delete section + # Params: + # - section_id: [String] ID of the section or @one_section_id + def delete_section(section_id = @one_section_id) + url = @url_sections + '/' + section_id + @nsx_client.delete(url) + end + + # Rules + # Get all rules + # Params: + # - section_id: [String] ID of the section or @one_section_id + # Return: + # - [Nokogiri::XML::NodeSet] + def rules(section_id = @one_section_id) + url = @url_sections + '/' + section_id + rules = @nsx_client.get(url) + rules.xpath(NSXConstants::NSXV_DFW_RULE_XPATH) + end + + # Get rule by id + # Return: + # - rule | nil + def rule_by_id(rule_id, section_id = @one_section_id) + url = @url_sections + '/' + section_id + '/rules/' + rule_id + valid_codes = [NSXConstants::CODE_CREATED, + NSXConstants::CODE_OK, + NSXConstants::CODE_BAD_REQUEST, + NSXConstants::CODE_NOT_FOUND] + additional_headers = [] + result = @nsx_client.get(url, additional_headers, valid_codes) + result.xpath(NSXConstants::NSXV_DFW_RULE_XPATH) + end + + # Get rules by name + # Return: + # - [Nokogiri::XML::NodeSet] + def rules_by_name(rule_name, section_id = @one_section_id) + rules = Nokogiri::XML::NodeSet.new(Nokogiri::XML::Document.new) + + all_rules = rules(section_id) + return rules unless all_rules + + all_rules.xpath("//rule[name=\"#{rule_name}\"]") + end + + # Create new rule + def create_rule(rule_spec, section_id = @one_section_id) + # etag is needed to add a new header If-Match + etag = section_etag(section_id) + raise NSXError::ObjectNotFound('etag') \ + unless etag + + aditional_headers = [{ 'If-Match' => etag }] + url = @url_sections + '/' + section_id + '/rules' + @nsx_client.post(url, rule_spec, aditional_headers) + end + + # Update rule + def update_rule(rule_id, rule_spec, section_id = @one_section_id) + url = @url_sections + '/' + section_id + '/rules/' + rule_id + rule = rule_by_id(rule_id) + raise "Rule id #{rule_id} not found" unless rule + + # etag is needed to add a new header If-Match + etag = section_etag(section_id) + raise "Cannot get etag from section: #{section_id}" unless etag + + aditional_headers = [{ 'If-Match' => etag }] + @nsx_client.put(url, rule_spec, aditional_headers) + end + + # Delete rule + def delete_rule(rule_id, section_id = @one_section_id) + url = @url_sections + '/' + section_id + '/rules/' + rule_id + # etag is needed to add a new header If-Match + etag = section_etag(section_id) + raise "Cannot get etag from section: #{section_id}" unless etag + + aditional_headers = [{ 'If-Match' => etag }] + @nsx_client.delete(url, aditional_headers) + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_logical_port.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_logical_port.rb new file mode 100644 index 0000000000..45f3fcd3fa --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_logical_port.rb @@ -0,0 +1,106 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + class NSXVLogicalPort < LogicalPort + + # ATTRIBUTES + attr_reader :id, :name, :type, :url + + # CONSTRUCTOR + # Logical port class variables: + # @lp_id + # @url_lp + # @lp_name + # @lp_type + def initialize(nsx_client, id = nil, data = nil) + super(nsx_client) + # lpid can be: + # - Logical port ID + # - Logical port attach ID + if id + initialize_with_id(id) + else + if data + begin + @id = new_logical_port(data) + rescue NSXError::IncorrectResponseCodeError => e + raise 'Logical Port not created in ' \ + "NSX Manager: #{e.message}" + end + unless @id + raise 'Logical Port not created in NSX Manager: '\ + 'generic error' + end + # Construct logical port class variables + @url = NSXConstants::NSXT_LP_BASE + @id + @name = lp_name + @type = lp_type + end + end + end + + # Creates a NSXTLogicalPort from its id + def initialize_with_id(id) + # First try lpid as logical port id + @id = id + # Construct URL of the created logical switch + @url = NSXConstants::NSXV_LP_BASE + @id + if lp? + @name = lp_name + @type = lp_type + else + # Second try with lpid as logical port attach id + @id = lp_with_attachid(id) + if @id.nil? + error_msg = "Logical port with id: #{id} not found" + error = NSXError::ObjectNotFound + .new(error_msg) + raise error + else + @url = NSXConstants::NSXT_LP_BASE + @id + @name = lp_name + @type = lp_type + end + end + end + + # Check if logical port exists + def lp? + @nsx_client.get(@url) ? true : false + end + + # Get logical port id from attach id + def lp_with_attachid(attach_id) + lps = @nsx_client.get(NSXConstants::NSXT_LP_BASE) + lps['results'].each do |lp| + return lp['id'] if lp['attachment']['id'] == attach_id + end + end + + # Get logical port display name + def lp_name + @nsx_client.get(@url)['display_name'] + end + + # Get resource type + def lp_type + @nsx_client.get(@url)['resource_type'] + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_rule.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_rule.rb new file mode 100644 index 0000000000..f44f29a56b --- /dev/null +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_rule.rb @@ -0,0 +1,172 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +module NSXDriver + + module NSXRule + + # Module NSXVRule + module NSXVRule + + def nsxv_rule_spec(rule, vm_data, nic_data) + rule_name = "#{rule[:id]}-#{rule[:name]}-#{vm_data[:id]}" + rule_name << "-#{vm_data[:deploy_id]}-#{nic_data[:id]}" + + # rubocop:disable Layout/LineLength + builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| + # rubocop:enable Layout/LineLength + xml.rule('disabled' => 'false', 'logged' => 'false') do + xml.name rule_name + xml.action 'allow' + xml.appliedToList do + xml.appliedTo do + xml.name nic_data[:name] + xml.value nic_data[:lp] + xml.type 'Vnic' + xml.isValid 'true' + end + end + xml.sectionId @one_section_id + + # SOURCES / DESTINATIONS: Any | IP Address | Vnet + + unless rule[:network_id].empty? && rule[:subnets].empty? + + if rule[:direction] == 'IN' + xml.sources('excluded' => 'false') do + if !rule[:network_id].empty? + xml.source do + xml.name rule[:network_name] + xml.value rule[:network_nsxid] + xml.type 'VirtualWire' + xml.isValid 'true' + end + elsif !rule[:subnets].empty? + rule[:subnets].each do |subnet| + xml.source do + # rubocop:disable Layout/LineLength + ip_version = IPAddr.new(subnet).ipv4? ? 'Ipv4Address' : 'Ipv6Address' + # rubocop:enable Layout/LineLength + xml.value subnet + xml.type ip_version + xml.isValid 'true' + end + end + end + end + else + xml.destinations('excluded' => 'false') do + # Target network: Vnet + if !rule[:network_id].empty? + xml.destination do + xml.name nic_data[:network_name] + xml.value rule[:network_nsxid] + xml.type 'VirtualWire' + xml.isValid 'true' + end + # Target network: Manual network(IP Address) + elsif !rule[:subnets].empty? + rule[:subnets].each do |subnet| + xml.destination do + # rubocop:disable Layout/LineLength + ip_version = IPAddr.new(subnet).ipv4? ? 'Ipv4Address' : 'Ipv6Address' + # rubocop:enable Layout/LineLength + xml.value subnet + xml.type ip_version + xml.isValid 'true' + end + end + end + end + end + end + + ##### SERVICES ##### + unless rule[:protocol].empty? + xml.services do + case rule[:protocol] + when 'TCP' + xml.service do + xml.isValid 'true' + xml.protocol '6' + xml.protocolName 'TCP' + # rubocop:disable Layout/LineLength + xml.sourcePort parse_ports(rule[:ports]) \ + if rule[:direction] == 'IN' + xml.destinationPort parse_ports(rule[:ports]) \ + if rule[:direction] == 'OUT' + # rubocop:enable Layout/LineLength + end + when 'UDP' + xml.service do + xml.isValid 'true' + xml.protocol '17' + xml.protocolName 'UDP' + # rubocop:disable Layout/LineLength + xml.sourcePort parse_ports(rule[:ports]) \ + if rule[:direction] == 'IN' + xml.destinationPort parse_ports(rule[:ports]) \ + if rule[:direction] == 'OUT' + # rubocop:enable Layout/LineLength + end + when 'ICMP' + xml.service do + xml.isValid 'true' + xml.protocol '1' + xml.protocolName 'ICMP' + end + when 'ICMPv6' + xml.service do + xml.isValid 'true' + xml.protocol '58' + xml.protocolName 'IPV6ICMP' + end + when 'IPSEC' + ports = NSXConstants::NSX_RULE_IPSEC_PORTS + xml.service do + xml.isValid 'true' + xml.protocol '50' + xml.protocolName 'ESP' + end + xml.service do + xml.isValid 'true' + xml.protocol '51' + xml.protocolName 'AH' + end + xml.service do + xml.isValid 'true' + xml.protocol '17' + xml.protocolName 'UDP' + xml.sourcePort parse_ports(ports) \ + if rule[:direction] == 'IN' + xml.destinationPort parse_ports(ports) \ + if rule[:direction] == 'OUT' + end + end + end + end + + xml.direction rule[:direction].downcase + xml.packetType 'any' + end + end + builder.to_xml + end + + end + + end + +end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_tz.rb b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_tz.rb index 4096380a6c..fe1c79bc2b 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/nsxv_tz.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/nsxv_tz.rb @@ -16,7 +16,7 @@ module NSXDriver # Class Transport Zone - class NSXVtz < NSXDriver::TransportZone + class NSXVtz < TransportZone # ATTRIBUTES attr_reader :tz_id @@ -25,7 +25,7 @@ module NSXDriver def initialize(nsx_client) super(nsx_client) # Construct base URLs - @url_tzs_nsxv = NSXDriver::NSXConstants::NSXV_TZS + @url_tzs_nsxv = NSXConstants::NSXV_TZS end # METHODS @@ -33,7 +33,7 @@ module NSXDriver def tzs @nsx_client .get(@url_tzs_nsxv) - .xpath(NSXDriver::NSXConstants::NSXV_TZS_XPATH) + .xpath(NSXConstants::NSXV_TZS_XPATH) end end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/opaque_network.rb b/src/vmm_mad/remotes/lib/nsx_driver/opaque_network.rb index d113bd40ec..bb7f5eda01 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/opaque_network.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/opaque_network.rb @@ -16,7 +16,7 @@ module NSXDriver # Class Opaque Network NSX-T Network - class OpaqueNetwork < NSXDriver::LogicalSwitch + class OpaqueNetwork < LogicalSwitch # ATTRIBUTES # attr_reader :ls_id, :admin_display @@ -31,7 +31,7 @@ module NSXDriver if ls_data begin @ls_id = new_logical_switch(ls_data) - rescue NSXDriver::NSXError:: + rescue NSXError:: IncorrectResponseCodeError => e raise 'Opaque Network not created in ' \ "NSX Manager: #{e.message}" @@ -42,7 +42,7 @@ module NSXDriver end # Construct URL of the created logical switch - @url_ls = NSXDriver::NSXConstants::NSXT_LS_SECTION + \ + @url_ls = NSXConstants::NSXT_LS_SECTION + \ @ls_id @ls_vni = ls_vni @ls_name = ls_name @@ -53,13 +53,13 @@ module NSXDriver end end - # Creates a NSXDriver::OpaqueNetwork from its name + # Creates a OpaqueNetwork from its name def self.new_from_name(nsx_client, ls_name) lswitch = new(nsx_client) ls_id = lswitch.ls_id_from_name(nsx_client, ls_name) unless ls_id error_msg = "Opaque Network with name: #{ls_name} not found" - error = NSXDriver::NSXError::ObjectNotFound + error = NSXError::ObjectNotFound .new(error_msg) raise error end @@ -69,11 +69,11 @@ module NSXDriver lswitch end - # Creates a NSXDriver::OpaqueNetwork from its id + # Creates a OpaqueNetwork from its id def initialize_with_id(ls_id) @ls_id = ls_id # Construct URL of the created logical switch - @url_ls = NSXDriver::NSXConstants::NSXT_LS_SECTION + \ + @url_ls = NSXConstants::NSXT_LS_SECTION + \ @ls_id if ls? @ls_vni = ls_vni @@ -82,7 +82,7 @@ module NSXDriver @admin_display = 'UP' else error_msg = "Opaque Network with id: #{ls_id} not found" - error = NSXDriver::NSXError::ObjectNotFound + error = NSXError::ObjectNotFound .new(error_msg) raise error end @@ -90,7 +90,7 @@ module NSXDriver # Get the logical switch id from its name def ls_id_from_name(nsx_client, name) - url = NSXDriver::NSXConstants::NSXT_LS_SECTION + url = NSXConstants::NSXT_LS_SECTION lswitches = nsx_client.get(url)['results'] lswitches.each do |lswitch| lsname = lswitch['display_name'] @@ -125,7 +125,7 @@ module NSXDriver # Create a new logical switch (NSX-T: opaque network) def new_logical_switch(ls_data) - @nsx_client.post(NSXDriver::NSXConstants::NSXT_LS_SECTION, ls_data) + @nsx_client.post(NSXConstants::NSXT_LS_SECTION, ls_data) end # Delete a logical switch diff --git a/src/vmm_mad/remotes/lib/nsx_driver/transport_zone.rb b/src/vmm_mad/remotes/lib/nsx_driver/transport_zone.rb index d1e782f5b5..85989d64a0 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/transport_zone.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/transport_zone.rb @@ -16,7 +16,7 @@ module NSXDriver # Class Transport Zone - class TransportZone < NSXDriver::NSXComponent + class TransportZone < NSXComponent # ATTRIBUTES attr_reader :tz_id @@ -28,13 +28,13 @@ module NSXDriver def self.new_child(nsx_client) case nsx_client.nsx_type.upcase - when NSXDriver::NSXConstants::NSXT - NSXDriver::NSXTtz.new(nsx_client) - when NSXDriver::NSXConstants::NSXV - NSXDriver::NSXVtz.new(nsx_client) + when NSXConstants::NSXT + NSXTtz.new(nsx_client) + when NSXConstants::NSXV + NSXVtz.new(nsx_client) else error_msg = "Unknown object type: #{nsx_client.nsx_type}" - error = NSXDriver::NSXError::UnknownObject.new(error_msg) + error = NSXError::UnknownObject.new(error_msg) raise error end end diff --git a/src/vmm_mad/remotes/lib/nsx_driver/virtual_wire.rb b/src/vmm_mad/remotes/lib/nsx_driver/virtual_wire.rb index 309a059de2..3ae20200e4 100644 --- a/src/vmm_mad/remotes/lib/nsx_driver/virtual_wire.rb +++ b/src/vmm_mad/remotes/lib/nsx_driver/virtual_wire.rb @@ -16,7 +16,7 @@ module NSXDriver # Class VirtualWire NSX-V Network - class VirtualWire < NSXDriver::LogicalSwitch + class VirtualWire < LogicalSwitch # CONSTRUCTOR def initialize(nsx_client, ls_id = nil, tz_id = nil, ls_data = nil) @@ -28,7 +28,7 @@ module NSXDriver if ls_data begin @ls_id = new_logical_switch(ls_data, tz_id) - rescue NSXDriver::NSXError:: + rescue NSXError:: IncorrectResponseCodeError => e raise 'VirtualWire not created in NSX Manager: ' \ "#{e.message}" @@ -39,7 +39,7 @@ module NSXDriver end # Construct URL of the created logical switch - @url_ls = NSXDriver::NSXConstants::NSXV_LS_SECTION + \ + @url_ls = NSXConstants::NSXV_LS_SECTION + \ @ls_id @ls_vni = ls_vni @ls_name = ls_name @@ -51,13 +51,13 @@ module NSXDriver end end - # Creates a NSXDriver::VirtualWire from its name + # Creates a VirtualWire from its name def self.new_from_name(nsx_client, ls_name) virtualwire = new(nsx_client) ls_id = virtualwire.ls_id_from_name(nsx_client, ls_name) unless ls_id error_msg = "VirtualWire with name: #{ls_name} not found" - error = NSXDriver::NSXError::ObjectNotFound + error = NSXError::ObjectNotFound .new(error_msg) raise error end @@ -67,16 +67,16 @@ module NSXDriver virtualwire end - # Creates a NSXDriver::VirtualWire from its id + # Creates a VirtualWire from its id def initialize_with_id(ls_id) @ls_id = ls_id # Construct URL of the created logical switch - @url_ls = NSXDriver::NSXConstants::NSXV_LS_SECTION + \ + @url_ls = NSXConstants::NSXV_LS_SECTION + \ @ls_id # Raise an error if VirtualWire id doesn't exists unless ls? error_msg = "VirtualWire with id: #{ls_id} not found" - error = NSXDriver::NSXError::ObjectNotFound + error = NSXError::ObjectNotFound .new(error_msg) raise error end @@ -90,10 +90,10 @@ module NSXDriver # Get the logical switch id from its name def ls_id_from_name(nsx_client, name) - url = NSXDriver::NSXConstants::NSXV_LS_SECTION + url = NSXConstants::NSXV_LS_SECTION virtualwires = nsx_client .get(url) - .xpath(NSXDriver::NSXConstants::NSXV_LS_XPATH) + .xpath(NSXConstants::NSXV_LS_XPATH) virtualwires.each do |virtualwire| lsname_arr = name.split(/-sid-/) lsname = lsname_arr[-1].split('-', 2)[-1] @@ -116,38 +116,38 @@ module NSXDriver # Get logical switch's name def ls_name @nsx_client.get(@url_ls) - .xpath(NSXDriver::NSXConstants::NSXV_LS_NAME_XPATH).text + .xpath(NSXConstants::NSXV_LS_NAME_XPATH).text end # Get logical switch's vni def ls_vni @nsx_client.get(@url_ls) - .xpath(NSXDriver::NSXConstants::NSXV_LS_VNI_XPATH).text + .xpath(NSXConstants::NSXV_LS_VNI_XPATH).text end # Get the Transport Zone of the logical switch def ls_tz @nsx_client.get(@url_ls) - .xpath(NSXDriver::NSXConstants::NSXV_TZ_XPATH).text + .xpath(NSXConstants::NSXV_TZ_XPATH).text end # Get the logical switch reference into vcenter def ls_vcenter_ref @nsx_client.get(@url_ls) - .xpath(NSXDriver::NSXConstants::NSXV_LS_BACKING_XPATH) + .xpath(NSXConstants::NSXV_LS_BACKING_XPATH) .text end # Get the distributed virtual switch's ref associated to a LS def ls_dvs_ref @nsx_client.get(@url_ls) - .xpath(NSXDriver::NSXConstants::NSXV_LS_OBJECTID_XPATH) + .xpath(NSXConstants::NSXV_LS_OBJECTID_XPATH) .text end # Create a new logical switch (NSX-V: virtualwire) def new_logical_switch(ls_data, tz_id) - url = "#{NSXDriver::NSXConstants::NSXV_TZ_SECTION}#{tz_id}" \ + url = "#{NSXConstants::NSXV_TZ_SECTION}#{tz_id}" \ '/virtualwires' @nsx_client.post(url, ls_data) end diff --git a/src/vmm_mad/remotes/nsx/nsx_driver.rb b/src/vmm_mad/remotes/nsx/nsx_driver.rb index 22e9d5dbe3..ea3d7937b0 100644 --- a/src/vmm_mad/remotes/nsx/nsx_driver.rb +++ b/src/vmm_mad/remotes/nsx/nsx_driver.rb @@ -59,6 +59,15 @@ require 'transport_zone' require 'nsxt_tz' require 'nsxv_tz' require 'virtual_wire' +require 'distributed_firewall' +require 'nsxt_dfw' +require 'nsxv_dfw' +require 'logical_port' +require 'nsxt_logical_port' +require 'nsxv_logical_port' +require 'nsx_rule' +require 'nsxt_rule' +require 'nsxv_rule' # NSX Driver module module NSXDriver diff --git a/src/vnm_mad/remotes/vcenter/clean b/src/vnm_mad/remotes/vcenter/clean deleted file mode 120000 index 300563f2ad..0000000000 --- a/src/vnm_mad/remotes/vcenter/clean +++ /dev/null @@ -1 +0,0 @@ -../common/dummy.sh \ No newline at end of file diff --git a/src/vnm_mad/remotes/vcenter/clean b/src/vnm_mad/remotes/vcenter/clean new file mode 100755 index 0000000000..1d35bdd973 --- /dev/null +++ b/src/vnm_mad/remotes/vcenter/clean @@ -0,0 +1,91 @@ +#!/usr/bin/env ruby + +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +# Define libraries location +ONE_LOCATION = ENV['ONE_LOCATION'] + +if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' + GEMS_LOCATION = '/usr/share/one/gems' + VMDIR = '/var/lib/one' + CONFIG_FILE = '/var/lib/one/config' +else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' + GEMS_LOCATION = ONE_LOCATION + '/share/gems' + VMDIR = ONE_LOCATION + '/var' + CONFIG_FILE = ONE_LOCATION + '/var/config' +end + +if File.directory?(GEMS_LOCATION) + Gem.use_paths(GEMS_LOCATION) +end + +$LOAD_PATH << RUBY_LIB_LOCATION + +$LOAD_PATH << File.dirname(__FILE__) +$LOAD_PATH << File.join(File.dirname(__FILE__), '..') + +require 'vnmmad' +require 'nokogiri' +require 'opennebula' +require 'vcenter_driver' +require 'nsx_driver' + +def modified?(template) + template_xml = Nokogiri::XML(template) + action = template_xml.xpath('//TEMPLATE/NIC[ATTACH="YES"]') + action.empty? ? false : true +end + +template = Base64.decode64(STDIN.read) +template_xml = Nokogiri::XML(template) + +# Check Host exists +host_name = template_xml + .xpath('//HISTORY_RECORDS/HISTORY[last()]/HOSTNAME').text +one_host = VCenterDriver::VIHelper + .find_by_name(OpenNebula::HostPool, host_name) +rc = one_host.info +if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg +end + +# Exit with error if NSX_STATUS != OK +nsx_status = one_host['TEMPLATE/NSX_STATUS'] +unless nsx_status == 'OK' + OpenNebula.log_error('NSX_STATUS is not OK') + OpenNebula.error_message('NSX_STATUS is not OK') + exit 1 +end + +# Clear rules +nsx_client = NSXDriver::NSXClient.new_from_id(one_host['ID']) +dfw = NSXDriver::DistributedFirewall.new_child(nsx_client) + +begin + dfw.clear_rules(template, modified?(template)) +rescue StandardError => e + OpenNebula.log_error('Error deleting security groups rules ' \ + "due to \"#{e.message}\"") + if VCenterDriver::CONFIG[:debug_information] + OpenNebula.error_message(e.backtrace) + end + exit 1 +end + +exit 0 diff --git a/src/vnm_mad/remotes/vcenter/post b/src/vnm_mad/remotes/vcenter/post deleted file mode 120000 index 300563f2ad..0000000000 --- a/src/vnm_mad/remotes/vcenter/post +++ /dev/null @@ -1 +0,0 @@ -../common/dummy.sh \ No newline at end of file diff --git a/src/vnm_mad/remotes/vcenter/post b/src/vnm_mad/remotes/vcenter/post new file mode 100755 index 0000000000..e2457d3ecc --- /dev/null +++ b/src/vnm_mad/remotes/vcenter/post @@ -0,0 +1,103 @@ +#!/usr/bin/env ruby + +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +# Define libraries location +ONE_LOCATION = ENV['ONE_LOCATION'] + +if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' + GEMS_LOCATION = '/usr/share/one/gems' + VMDIR = '/var/lib/one' + CONFIG_FILE = '/var/lib/one/config' +else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' + GEMS_LOCATION = ONE_LOCATION + '/share/gems' + VMDIR = ONE_LOCATION + '/var' + CONFIG_FILE = ONE_LOCATION + '/var/config' +end + +if File.directory?(GEMS_LOCATION) + Gem.use_paths(GEMS_LOCATION) +end + +$LOAD_PATH << RUBY_LIB_LOCATION + +$LOAD_PATH << File.dirname(__FILE__) +$LOAD_PATH << File.join(File.dirname(__FILE__), '..') + +require 'vnmmad' +require 'nokogiri' +require 'opennebula' +require 'vcenter_driver' +require 'nsx_driver' + +def modified?(template) + template_xml = Nokogiri::XML(template) + action = template_xml.xpath('//TEMPLATE/NIC[ATTACH="YES"]') + action.empty? ? false : true +end + +template = Base64.decode64(STDIN.read) +deploy_id = ARGV[0] + +template_xml = Nokogiri::XML(template) + +# OpenNebula host +host_name = template_xml + .xpath('//HISTORY_RECORDS/HISTORY[last()]/HOSTNAME').text +one_host = VCenterDriver::VIHelper + .find_by_name(OpenNebula::HostPool, host_name) +rc = one_host.info +if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg +end + +# OpenNebula VM +vmid = template_xml.xpath('//VM/ID') +one_vm = VCenterDriver::VIHelper.one_item(OpenNebula::VirtualMachine, vmid) + +rc = one_vm.info +if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg +end + +# NSX Objects +nsx_client = NSXDriver::NSXTClient.new_from_id(one_host['ID']) +dfw = NSXDriver::DistributedFirewall.new_child(nsx_client) +ls = NSXDriver::LogicalSwitch.new(nsx_client) + +# Get all modified or all NSX Nics +is_modified = modified?(template) +nsx_nics = ls.nsx_nics(template_xml, is_modified) +vm_state = one_vm.state_str +unless nsx_nics.empty? || (vm_state == 'POWEROFF') + begin + dfw.create_rules(deploy_id, template, is_modified) + rescue StandardError => e + dfw.clear_rules(template, is_modified) + OpenNebula.log_error('Error creating Security Group rules ' \ + "due to \"#{e.message}\"") + if VCenterDriver::CONFIG[:debug_information] + OpenNebula.error_message(e.backtrace) + end + exit 1 + end +end + +exit 0 diff --git a/src/vnm_mad/remotes/vcenter/pre b/src/vnm_mad/remotes/vcenter/pre deleted file mode 120000 index 300563f2ad..0000000000 --- a/src/vnm_mad/remotes/vcenter/pre +++ /dev/null @@ -1 +0,0 @@ -../common/dummy.sh \ No newline at end of file diff --git a/src/vnm_mad/remotes/vcenter/pre b/src/vnm_mad/remotes/vcenter/pre new file mode 100755 index 0000000000..0b02f33f58 --- /dev/null +++ b/src/vnm_mad/remotes/vcenter/pre @@ -0,0 +1,71 @@ +#!/usr/bin/env ruby + +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +# Define libraries location +ONE_LOCATION = ENV['ONE_LOCATION'] + +if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' + GEMS_LOCATION = '/usr/share/one/gems' + VMDIR = '/var/lib/one' + CONFIG_FILE = '/var/lib/one/config' +else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' + GEMS_LOCATION = ONE_LOCATION + '/share/gems' + VMDIR = ONE_LOCATION + '/var' + CONFIG_FILE = ONE_LOCATION + '/var/config' +end + +if File.directory?(GEMS_LOCATION) + Gem.use_paths(GEMS_LOCATION) +end + +$LOAD_PATH << RUBY_LIB_LOCATION + +$LOAD_PATH << File.dirname(__FILE__) +$LOAD_PATH << File.join(File.dirname(__FILE__), '..') + +require 'vnmmad' +require 'nokogiri' +require 'opennebula' +require 'vcenter_driver' +require 'nsx_driver' + +template = Base64.decode64(STDIN.read) +template_xml = Nokogiri::XML(template) + +# Check Host exists +host_name = template_xml + .xpath('//HISTORY_RECORDS/HISTORY[last()]/HOSTNAME').text + +one_host = VCenterDriver::VIHelper + .find_by_name(OpenNebula::HostPool, host_name) +rc = one_host.info +if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg +end + +# Exit with error if NSX_STATUS != OK +nsx_status = one_host['TEMPLATE/NSX_STATUS'] +unless nsx_status == 'OK' + OpenNebula.log_error('NSX_STATUS is not OK') + OpenNebula.error_message('NSX_STATUS is not OK') + exit 1 +end + +exit 0 diff --git a/src/vnm_mad/remotes/vcenter/update_sg b/src/vnm_mad/remotes/vcenter/update_sg new file mode 100755 index 0000000000..a858abc214 --- /dev/null +++ b/src/vnm_mad/remotes/vcenter/update_sg @@ -0,0 +1,97 @@ +#!/usr/bin/env ruby + +# -------------------------------------------------------------------------- # +# Copyright 2002-2019, OpenNebula Project, OpenNebula Systems # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # +# Define libraries location +ONE_LOCATION = ENV['ONE_LOCATION'] + +if !ONE_LOCATION + RUBY_LIB_LOCATION = '/usr/lib/one/ruby' + GEMS_LOCATION = '/usr/share/one/gems' + VMDIR = '/var/lib/one' + CONFIG_FILE = '/var/lib/one/config' +else + RUBY_LIB_LOCATION = ONE_LOCATION + '/lib/ruby' + GEMS_LOCATION = ONE_LOCATION + '/share/gems' + VMDIR = ONE_LOCATION + '/var' + CONFIG_FILE = ONE_LOCATION + '/var/config' +end + +if File.directory?(GEMS_LOCATION) + Gem.use_paths(GEMS_LOCATION) +end + +$LOAD_PATH << RUBY_LIB_LOCATION + +$LOAD_PATH << File.dirname(__FILE__) +$LOAD_PATH << File.join(File.dirname(__FILE__), '..') + +require 'vnmmad' +require 'nokogiri' +require 'opennebula' +require 'vcenter_driver' +require 'nsx_driver' + +def modified?(template) + template_xml = Nokogiri::XML(template) + action = template_xml.xpath('//TEMPLATE/NIC[ATTACH="YES"]') + action.empty? ? false : true +end + +template = Base64.decode64(STDIN.read) +deploy_id = ARGV[0] +template_xml = Nokogiri::XML(template) + +# OpenNebula host +host_name = template_xml + .xpath('//HISTORY_RECORDS/HISTORY[last()]/HOSTNAME').text +one_host = VCenterDriver::VIHelper + .find_by_name(OpenNebula::HostPool, host_name) +rc = one_host.info +if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg +end + +vmid = template_xml.xpath('//VM/ID') +one_vm = VCenterDriver::VIHelper.one_item(OpenNebula::VirtualMachine, vmid) +# OpenNebula VM +rc = one_vm.info +if OpenNebula.is_error?(rc) + err_msg = rc.message + raise err_msg +end + +# NSX Objects +nsx_client = NSXDriver::NSXTClient.new_from_id(one_host['ID']) +dfw = NSXDriver::DistributedFirewall.new_child(nsx_client) + +vm_state = one_vm.state_str +unless vm_state == 'POWEROFF' + begin + dfw.clear_rules(template, false) + dfw.create_rules(deploy_id, template, false) + rescue StandardError => e + OpenNebula.log_error('Error updating security groups ' \ + "due to \"#{e.message}\"") + if VCenterDriver::CONFIG[:debug_information] + OpenNebula.error_message(e.backtrace) + end + exit 1 + end +end + +exit 0