From 0105ec0dd9c48a0573b10168bf1a8fa1c94953ef Mon Sep 17 00:00:00 2001 From: Paula Zomignani Oliveira Date: Fri, 29 Apr 2022 10:44:52 -0300 Subject: [PATCH 01/23] Improving code related to the Agent properties --- agent/conf/agent.properties | 532 +++++--- .../src/main/java/com/cloud/agent/Agent.java | 3 +- .../main/java/com/cloud/agent/AgentShell.java | 26 +- .../agent/properties/AgentProperties.java | 691 +++++++++- .../AgentPropertiesFileHandler.java | 37 +- .../AgentPropertiesFileHandlerTest.java | 52 + .../kvm/resource/BridgeVifDriver.java | 7 +- .../hypervisor/kvm/resource/IvsVifDriver.java | 8 +- .../resource/LibvirtComputingResource.java | 304 ++--- .../hypervisor/kvm/resource/OvsVifDriver.java | 10 +- .../kvm/storage/KVMStorageProcessor.java | 11 +- .../LibvirtComputingResourceTest.java | 1151 ++++++++--------- .../kvm/resource/LibvirtVifDriverTest.java | 25 +- 13 files changed, 1790 insertions(+), 1067 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index d2f87d66c100..be72ca1482f3 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -17,277 +17,431 @@ # Sample configuration file for CloudStack agent -# The GUID to identify the agent with, this is mandatory! -# Generate with "uuidgen" +# MANDATORY: The GUID to identify the agent with. +# Generated with "uuidgen" guid= -#resource= the java class, which agent load to execute +# The java class which the agent loads to execute. +# Default value: com.cloud.hypervisor.kvm.resource.LibvirtComputingResource resource=com.cloud.hypervisor.kvm.resource.LibvirtComputingResource -#workers= number of threads running in agent +# The number of threads running in the agent. +# Default value: 5 workers=5 -#host= The IP address of management server +# The IP address of the management server. +# Default value: localhost host=localhost -# The time interval in seconds after which agent will check if connected host -# is the preferred host (the first host in the comma-separated list is preferred -# one) and will attempt to reconnect to the preferred host when it's connected -# to one of the secondary/backup hosts. The timer task is scheduled after agent -# connects to a management server. On connection, it receives admin configured +# The time interval (in seconds) after which agent will check if the connected host +# is the preferred host (the first host in the comma-separated list is the preferred +# one). After that interval, if the agent is connected to one of the secondary/backup hosts, +# it will attempt to reconnect to the preferred host. +# The timer task is scheduled after the agent connects to a management server. +# On connection, it receives admin configured # cluster-level 'indirect.agent.lb.check.interval' setting that will be used by -# the agent as the preferred host check interval however the following setting -# if defined overrides the received value. The value 0 and lb algorithm 'shuffle' +# the agent as the preferred host check interval, however, if the following setting +# is defined it will override the received value. The value 0 and lb algorithm 'shuffle' # disables this background task. +# Default value: 0 #host.lb.check.interval=0 -#port = The port management server listening on, default is 8250 +# The port that the management server is listening on. +# Default value = 8250 port=8250 -#cluster= The cluster which the agent belongs to +# The cluster which the agent belongs to. +# Default value: default cluster=default -#pod= The pod which the agent belongs to +# The pod which the agent belongs to. +# Default value: default pod=default -#zone= The zone which the agent belongs to +# The zone which the agent belongs to. +# Default value: default zone=default -#public.network.device= the public nic device -# if this is commented, it is autodetected on service startup -# public.network.device=cloudbr0 +# The public NIC device. +# If this is commented, it will be autodetected on service startup. +# Default value: cloudbr0 +#public.network.device=cloudbr0 -#private.network.device= the private nic device -# if this is commented, it is autodetected on service startup -# private.network.device=cloudbr1 +# The private NIC device. +# If this is commented, it will be autodetected on service startup. +# Default value: cloudbr1 +#private.network.device=cloudbr1 -#guest.network.device= the guest nic device -# if this is commented, the private nic device will be used +# The guest NIC device. +# If this is commented, the value of the private NIC device will be used. +# Default value: the private NIC device value +#guest.network.device= -# local storage path, by default, it's /var/lib/libvirt/images/ +# Local storage path. Multiple values can be entered and separated by commas. +# Default value: /var/lib/libvirt/images/ #local.storage.path=/var/lib/libvirt/images/ -# Qemu socket path, directory where Qemu sockets are placed. -# These sockets are for the Qemu Guest Agent and SSVM privisioning -# Make sure that AppArmor or SELinux allow libvirt to write there +# Directory where Qemu sockets are placed. +# These sockets are for the Qemu Guest Agent and SSVM provisioning. +# Make sure that AppArmor or SELinux allow libvirt to write there. +# Default value: /var/lib/libvirt/qemu #qemu.sockets.path=/var/lib/libvirt/qemu -# The UUID for the local storage pool, this is mandatory! -# Generate with "uuidgen" +# MANDATORY: The UUID for the local storage pool. Multiple values can be entered and separated by commas. +# Generated with "uuidgen". local.storage.uuid= -# Location for KVM scripts +# Location for KVM virtual router scripts. +# The path defined in this property is relative to the directory "/usr/share/cloudstack-common/". +# Default value: scripts/network/domr/kvm domr.scripts.dir=scripts/network/domr/kvm -# the timeout for time-consuming operations, such as create/copy snapshot +# The timeout (in ms) for time-consuming operations, such as create/copy a snapshot. +# Default value: 7200 #cmds.timeout=7200 -# set the vm migrate speed, by default, it will try to guess the speed of the guest network -# In MegaBytes per second -#vm.migrate.speed=0 - -# set target downtime at end of livemigration, the 'hiccup' for final copy. Higher numbers -# make livemigration easier, lower numbers may cause migration to never complete. Less than 1 -# means hypervisor default (20ms). -#vm.migrate.downtime=0 - -# Busy VMs may never finish migrating, depending on environment. When its available, we will -# want to add support for autoconvergence migration flag which should fix this. Set an upper -# limit in milliseconds for how long live migration should wait, at which point VM is paused and -# migration will finish quickly. Less than 1 means disabled. -#vm.migrate.pauseafter=0 - -# Time (in seconds) to wait for VM migrate finish. Less than 1 means disabled. -# If vm migration is not finished in the time, the vm job will be cancelled by libvirt. +# This parameter sets the VM migration speed. +# By default, it will try to guess the speed of the guest network and consume all possible bandwidth. +# The default value is -1, which means that the agent will use all possible bandwidth. +# When entering a value, make sure to enter it in megabytes per second. +# Default value: -1 +#vm.migrate.speed=-1 + +# Sets target downtime (in ms) at end of livemigration, the 'hiccup' for final copy. +# Higher numbers make livemigration easier, lower numbers may cause migration to never complete. +# Less than 1 means hypervisor default (20ms). +# Default value: -1 +#vm.migrate.downtime=-1 + +# Busy VMs may never finish migrating, depending on environment. +# Therefore, if configured, this option will pause the VM after the time entered (in ms) to force the migration to finish. +# Less than 1 means disabled. +# Default value: -1 +#vm.migrate.pauseafter=-1 + +# Time (in seconds) to wait for VM migraton to finish. Less than 1 means disabled. +# If the VM migration is not finished in the time, the VM job will be cancelled by libvirt. # It will be configured by cloudstack management server when cloudstack agent connects. -# please change the global setting 'migratewait' if needed (default value: 3600) -#vm.migrate.wait=0 +# please change the global setting 'migratewait' if needed (migratewait default value: 3600). +# Default value: -1 +#vm.migrate.wait=-1 +# ---------------- AGENT HOOKS ----------------- # Agent hooks is the way to override default agent behavior to extend the functionality without excessive coding -# for a custom deployment. The first hook promoted is libvirt-vm-xml-transformer which allows provider to modify -# VM XML specification before send to libvirt. Hooks are implemented in Groovy and must be implemented in the way -# to keep default CS behaviour is something goes wrong. -# All hooks are located in a special directory defined in 'agent.hooks.basedir' -# +# for a custom deployment. +# There are 3 arguments needed for the hook to be called: the base directory (defined in agent.hooks.basedir), +# the name of the script that is located in the base directory (defined in agent.hooks.*.script) +# and the method that is going to be called on the script (defined in agent.hooks.*.method). +# These properties are detailed below. +# Hooks are implemented in Groovy and must be implemented in a way +# that keeps default CS behavior if something goes wrong. + +# All hooks are located in a special directory defined in 'agent.hooks.basedir'. +# Default value: /etc/cloudstack/agent/hooks # agent.hooks.basedir=/etc/cloudstack/agent/hooks -# every hook has two major attributes - script name, specified in 'agent.hooks.*.script' and method name +# Every hook has two major attributes - script name, specified in 'agent.hooks.*.script' and method name # specified in 'agent.hooks.*.method'. -# Libvirt XML transformer hook does XML-to-XML transformation which provider can use to add/remove/modify some -# sort of attributes in Libvirt XML domain specification. -# agent.hooks.libvirt_vm_xml_transformer.script=libvirt-vm-xml-transformer.groovy -# agent.hooks.libvirt_vm_xml_transformer.method=transform -# -# The hook is called right after libvirt successfully launched VM -# agent.hooks.libvirt_vm_on_start.script=libvirt-vm-state-change.groovy -# agent.hooks.libvirt_vm_on_start.method=onStart -# -# The hook is called right after libvirt successfully stopped VM -# agent.hooks.libvirt_vm_on_stop.script=libvirt-vm-state-change.groovy -# agent.hooks.libvirt_vm_on_stop.method=onStop -# - -# set the type of bridge used on the hypervisor, this defines what commands the resource -# will use to setup networking. Currently supported NATIVE, OPENVSWITCH +# Libvirt XML transformer hook does XML-to-XML transformation, which allows the provider to modify +# VM XML specification before is sent to libvirt. +# The provider can use this to add/remove/modify some sort of attributes in Libvirt XML domain specification. +# Default value script: libvirt-vm-xml-transformer.groovy +# Default value method: transform +#agent.hooks.libvirt_vm_xml_transformer.script=libvirt-vm-xml-transformer.groovy +#agent.hooks.libvirt_vm_xml_transformer.method=transform + +# The hook is called right after libvirt successfully launched the VM. +# Default value script: libvirt-vm-state-change.groovy +# Default value method: onStart +#agent.hooks.libvirt_vm_on_start.script=libvirt-vm-state-change.groovy +#agent.hooks.libvirt_vm_on_start.method=onStart + +# The hook is called right after libvirt successfully stopped the VM. +# Default value script: libvirt-vm-state-change.groovy +# Default value method: onStop +#agent.hooks.libvirt_vm_on_stop.script=libvirt-vm-state-change.groovy +#agent.hooks.libvirt_vm_on_stop.method=onStop +# ---------------- END AGENT HOOKS --------------- + +# Sets the type of bridge used on the hypervisor. This defines what commands the resource +# will use to setup networking. +# Possible Values: native | openvswitch +# Default value: native. #network.bridge.type=native -# set the driver used to plug and unplug nics from the bridges -# a sensible default will be selected based on the network.bridge.type but can +# Sets the driver used to plug and unplug NICs from the bridges. +# A sensible default value will be selected based on the network.bridge.type but can # be overridden here. -# native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver -# openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver +# Also used to enable direct networking in libvirt (see properties below). +# Value for native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver +# Value for openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver #libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.BridgeVifDriver -# Set DPDK Support on OpenVswitch -#openvswitch.dpdk.enabled=true +# Settings to enable direct networking in libvirt. +# Should not be used on hosts that run system VMs. +# Possible values for mode: private | bridge | vepa +#libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.DirectVifDriver +#network.direct.source.mode=private +#network.direct.device=eth0 + +# Sets DPDK Support on OpenVswitch. +# Default value for openvswitch.dpdk.enabled: false. +#openvswitch.dpdk.enabled=false #openvswitch.dpdk.ovs.path=/var/run/openvswitch -# set the hypervisor type, values are: kvm, lxc +# Sets the hypervisor type. +# Possible values: kvm | lxc hypervisor.type=kvm -# This parameter specifies a directory on the host local storage for temporary storing direct download templates +# This parameter specifies a directory on the host local storage for temporary storing direct download templates. +# Default value: /var/lib/libvirt/images #direct.download.temporary.download.location=/var/lib/libvirt/images -# This parameter specifies a directory on the host local storage for creating and hosting the config drives +# This parameter specifies a directory on the host local storage for creating and hosting the config drives. +# Default value: /var/cache/cloud #host.cache.location=/var/cache/cloud -# set the rolling maintenance hook scripts directory +# Sets the rolling maintenance hook scripts directory. #rolling.maintenance.hooks.dir=/etc/cloudstack/agent/hooks.d -# disable the rolling maintenance service execution -#rolling.maintenance.service.executor.disabled=true +# Disables the rolling maintenance service execution. +# Default value: false +#rolling.maintenance.service.executor.disabled=false -# set the hypervisor URI. Usually there is no need for changing this +# Sets the hypervisor URI. # For KVM: qemu:///system # For LXC: lxc:/// -# hypervisor.uri=qemu:///system - -# settings to enable direct networking in libvirt, should not be used -# on hosts that run system vms, values for mode are: private, bridge, vepa -# libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.DirectVifDriver -# network.direct.source.mode=private -# network.direct.device=eth0 - -# setting to enable the cpu model to kvm guest globally. -# three option:custom,host-model and host-passthrough. -# custom - user custom the CPU model which specified by guest.cpu.model. -# host-model - identify the named CPU model which most closely matches the host, -# and then request additional CPU flags to complete the match. This should give -# close to maximum functionality/performance, which maintaining good +#hypervisor.uri=qemu:///system + +# Setting to enable the CPU model to KVM guest globally. +# Possible values: custom | host-model | host-passthrough +# - custom: user customs the CPU model, which is specified by property guest.cpu.model. +# - host-model: identifies the named CPU model which most closely matches the host, +# and then requests additional CPU flags to complete the match. This should give +# close to maximum functionality/performance, which maintains good # reliability/compatibility if the guest is migrated to another host with slightly different host CPUs. -# host-passthrough - tell KVM to passthrough the host CPU with no modifications. -# The difference to host-model, instead of just matching feature flags, +# - host-passthrough: tells KVM to passthrough the host CPU with no modifications. +# It is different from host-model because instead of just matching feature flags, # every last detail of the host CPU is matched. This gives absolutely best performance, # and can be important to some apps which check low level CPU details, -# but it comes at a cost wrt migration. The guest can only be migrated to +# but it comes at a cost with migration. The guest can only be migrated to # an exactly matching host CPU. -# -# guest.cpu.mode=custom|host-model|host-passthrough -# This param is only valid if guest.cpu.mode=custom, -# for examples:"Conroe" "Penryn", "Nehalem", "Westmere", "pentiumpro" and so -# on,run virsh capabilities for more details. -# guest.cpu.model= -# -# This param will set the CPU architecture for the domain override what -# the management server would send +#guest.cpu.mode=host-model + +# Custom CPU model. This param is only valid if guest.cpu.mode=custom. +# Possible values:"Conroe" | "Penryn" | "Nehalem" | "Westmere" | "pentiumpro" etc. +# Run virsh capabilities for more details. +#guest.cpu.model= + +# This param will set the CPU architecture for the domain to override what +# the management server would send. # In case of arm64 (aarch64), this will change the machine type to 'virt' and # adds a SCSI and a USB controller in the domain xml. -# guest.cpu.arch=x86_64|aarch64 -# -# This param will require CPU features on the section -# guest.cpu.features=vmx vme -# -# vm.memballoon.disable=true -# Disable memory ballooning on vm guests for overcommit, by default overcommit -# feature enables balloon and sets currentMemory to a minimum value. -# -# vm.diskactivity.checkenabled=false +# Possible values: x86_64 | aarch64 +#guest.cpu.arch=x86_64 + +# This param will require CPU features on the CPU section. +# The features listed in this property must be separated by a blank space (see example below). +#guest.cpu.features=vmx vme + +# Disables memory ballooning on VM guests for overcommit. +# By default overcommit feature enables balloon and sets currentMemory to a minimum value. +# Default value: false +#vm.memballoon.disable=false + + # Set to true to check disk activity on VM's disks before starting a VM. This only applies # to QCOW2 files, and ensures that there is no other running instance accessing -# the file before starting. It works by checking the modify time against the current time, -# so care must be taken to ensure the cluster has time synced, otherwise VMs may fail to start. -# -# vm.diskactivity.checktimeout_s=120 -# Timeout for giving up on waiting for VM's disk files to become inactive. Hitting -# this timeout will result in failure to start VM. -# -# vm.diskactivity.inactivetime_ms=30000 -# This is the length of time that the disk needs to be inactive in order to pass the check. -# This means current time minus mtime of disk file needs to be greater than this number. +# the file before starting. It works by checking the modified time against the current time, +# so care must be taken to ensure that the cluster's time is synchronized, otherwise VMs may fail to start. +# Default value: false +#vm.diskactivity.checkenabled=false + +# Timeout (in seconds) for giving up on waiting for VM's disk files to become inactive. +# Hitting this timeout will result in failure to start VM. +# Value must be > 0. +# Default value: 120 +#vm.diskactivity.checktimeout_s=120 + +# This is the length of time (in ms) that the disk needs to be inactive in order to pass the check. +# This means current time minus time of disk file needs to be greater than this number. # It also has the side effect of setting the minimum threshold between a stop and start of # a given VM. -# -# kvmclock.disable=false -# Some newer linux kernels are incapable of reliably migrating vms with kvmclock -# This is a workaround for the bug, admin can set this to true per-host -# -# vm.rng.enable=false -# This enabled the VirtIO Random Number Generator device for guests. -# -# vm.rng.model=random +# Default value: 30000 +#vm.diskactivity.inactivetime_ms=30000 + +# Some newer linux kernels are incapable of reliably migrating VMs with KVMclock. +# This is a workaround for the bug, admin can set this to true per-host. +# Default value: false. +#kvmclock.disable=false + +# This enables the VirtIO Random Number Generator (RNG) device for guests. +# Default value: false. +#vm.rng.enable=false + # The model of VirtIO Random Number Generator (RNG) to present to the Guest. # Currently only 'random' is supported. -# -# vm.rng.path=/dev/random +#vm.rng.model=random + # Local Random Number Device Generator to use for VirtIO RNG for Guests. -# This is usually /dev/random, but per platform this might be different -# -# vm.rng.rate.bytes=2048 +# This is usually /dev/random, but it might be different per platform. +# Default value: /dev/random +#vm.rng.path=/dev/random + # The amount of bytes the Guest may request/obtain from the RNG in the period -# specified below. -# -# vm.rng.rate.period=1000 +# specified in the property vm.rng.rate.period. +# Default value: 2048 +#vm.rng.rate.bytes=2048 + # The number of milliseconds in which the guest is allowed to obtain the bytes -# specified above. -# -# router.aggregation.command.each.timeout=600 -# timeout value for aggregation commands send to virtual router -# -# host.overcommit.mem.mb = 0 -# allows to increase amount of ram available on host virtually to utilize Zswap, KSM features -# and modern fast SSD/3D XPoint devices. Specified amount of MBs is added to the memory agent -# reports to the Management Server -# Default: 0 -# -# host.reserved.mem.mb = 0 -# How much host memory to reserve for non-allocation. -# A useful parameter if a node uses some other software that requires memory, -# or in case that OOM Killer kicks in sometimes. -# If this parameter is used, host.overcommit.mem.mb must be set to 0. +# specified in the property vm.rng.rate.bytes. +# Default value: 1000 +#vm.rng.rate.period=1000 + +# Timeout value for aggregation commands to be sent to the virtual router (in seconds). +#router.aggregation.command.each.timeout=600 + +# Allows virtually increase the amount of RAM (in MB) available on the host. +# This property can be useful if the host uses Zswap, KSM features and other memory compressing technologies. +# For example: if the host has 2GB of RAM and this property is set to 2048, the amount of RAM of the host will be read as 4GB. # Default value: 0 -# -# vm.watchdog.model=i6300esb -# The model of Watchdog timer to present to the Guest +#host.overcommit.mem.mb=0 + +# How much host memory (in MB) to reserve for non-allocation. +# A useful parameter if a node uses some other software that requires memory, +# or in case that OOM Killer kicks in. +# If this parameter is used, property host.overcommit.mem.mb must be set to 0. +# Default value: 1024 +#host.reserved.mem.mb=1024 + +# The model of Watchdog timer to present to the Guest. # For all models refer to the libvirt documentation. -# Recommend value is: i6300esb -# -# vm.watchdog.action=none -# Action to take when the Guest/Instance is no longer notifying the Watchdog -# timer. +# Default value: i6300esb +#vm.watchdog.model=i6300esb + +# Action to take when the Guest/Instance is no longer notifying the Watchdog timer. # For all actions refer to the libvirt documentation. -# Recommended values are: none, reset and poweroff. -# +# Possible values: none | reset | poweroff +# Default value: none +#vm.watchdog.action=none + +# Automatically clean up iSCSI sessions not attached to any VM. +# Should be enabled for users using managed storage (for example solidfire). +# Should be disabled for users with unmanaged iSCSI connections on their hosts. iscsi.session.cleanup.enabled=false -# Automatically clean up iscsi sessions not attached to any VM. -# Should be enabled for users using managed storage for example solidfire. -# Should be disabled for users with unmanaged iscsi connections on their hosts -# This parameter specifies the heartbeat update timeout in ms; The default value is 60000ms (1 min). +# The heartbeat update timeout (in ms). # Depending on the use case, this timeout might need increasing/decreasing. -# heartbeat.update.timeout=60000 +# Default value: 60000 +#heartbeat.update.timeout=60000 -# This parameter specifies the timeout in seconds to retrieve the target's domain id when migrating a VM with KVM. -# vm.migrate.domain.retrieve.timeout=10 +# The timeout (in seconds) to retrieve the target's domain id when migrating a VM with KVM. +# # Default value: 10 +#vm.migrate.domain.retrieve.timeout=10 # This parameter specifies if the host must be rebooted when something goes wrong with the heartbeat. -# reboot.host.and.alert.management.on.heartbeat.timeout=true +# Default value: true +#reboot.host.and.alert.management.on.heartbeat.timeout=true + +# Enables manually setting CPU's topology on KVM's VM. +# Default value: true +#enable.manually.setting.cpu.topology.on.kvm.vm=true + +# Manually sets the host CPU MHz, in cases where CPU scaling support detects the value is wrong. +#host.cpu.manual.speed.mhz=0 + +# Enables/disables the IO driver for Qemu. It's enabled by default on KVM agents. +#enable.io.uring=true + +# Defines the location for Hypervisor scripts. +# The path defined in this property is relative. +# To locate the script, ACS first tries to concatenate +# the property path with "/usr/share/cloudstack-agent/lib/". +# If it fails, it will test each folder of the path, +# decreasing one by one, until it reaches root. +# If the script is not found, ACS will repeat the same +# steps concatenating the property path with "/usr/share/cloudstack-common/". +# The path defined in this property is relative +# to the directory "/usr/share/cloudstack-common/". +# Default value: scripts/vm/hypervisor +#hypervisor.scripts.dir=scripts/vm/hypervisor + +# Defines the location for KVM scripts. +# The path defined in this property is relative. +# To locate the script, ACS first tries to concatenate +# the property path with "/usr/share/cloudstack-agent/lib/". +# If it fails, it will test each folder of the path, +# decreasing one by one, until it reaches root. +# If the script is not found, ACS will repeat the same +# steps concatenating the property path with "/usr/share/cloudstack-common/". +# The path defined in this property is relative +# to the directory "/usr/share/cloudstack-common/". +# Default value: scripts/vm/hypervisor/kvm +#kvm.scripts.dir=scripts/vm/hypervisor/kvm + +# Specifies start MAC address for private IP range. +# Default value: 00:16:3e:77:e2:a0 +#private.macaddr.start=00:16:3e:77:e2:a0 + +# Specifies start IP address for private IP range. +# Default value: 192.168.166.128 +#private.ipaddr.start=192.168.166.128 + +# Defines Local Bridge Name. +#private.bridge.name= + +# Defines private network name. +#private.network.name= + +# Defines the location for network scripts. +# The path defined in this property is relative. +# To locate the script, ACS first tries to concatenate +# the property path with "/usr/share/cloudstack-agent/lib/". +# If it fails, it will test each folder of the path, +# decreasing one by one, until it reaches root. +# If the script is not found, ACS will repeat the same +# steps concatenating the property path with "/usr/share/cloudstack-common/". +# The path defined in this property is relative +# to the directory "/usr/share/cloudstack-common/". +# Default value: scripts/vm/network/vnet +#network.scripts.dir=scripts/vm/network/vnet + +# Defines the location for storage scripts. +# The path defined in this property is relative. +# To locate the script, ACS first tries to concatenate +# the property path with "/usr/share/cloudstack-agent/lib/". +# If it fails, it will test each folder of the path, +# decreasing one by one, until it reaches root. +# If the script is not found, ACS will repeat the same +# steps concatenating the property path with "/usr/share/cloudstack-common/". +# The path defined in this property is relative +# to the directory "/usr/share/cloudstack-common/". +# Default value: scripts/storage/qcow2 +#storage.scripts.dir=scripts/storage/qcow2 + +# Time (in seconds) to wait for the VM to shutdown gracefully. +# If the time is exceeded shutdown will be forced. +# Default value: 120 +#stop.script.timeout=120 + +# Definition of VMs video model type. +#vm.video.hardware= + +# Definition of VMs video, specifies the amount of RAM in kibibytes (blocks of 1024 bytes). +# Default value: 0 +#vm.video.ram=0 + +# System VM ISO path. +#systemvm.iso.path= -# Enable manually setting CPU's topology on KVM's VM. -# enable.manually.setting.cpu.topology.on.kvm.vm=true +# If set to "true", allows override of the properties: private.macaddr.start, private.ipaddr.start, private.ipaddr.end. +# Default value: false +#developer=false -# Manually set the host CPU MHz, in cases where CPU scaling support detected value is wrong -# host.cpu.manual.speed.mhz=0 +# Can only be used if property developer = true. This property is used to define the link local bridge name and private network name. +#instance= -# Enable/disable IO driver for Qemu / It's enabled by default on KVM agents -# enable.io.uring=true +# Shows the path to the base directory in which NFS servers are going to be mounted. +# Default value: /mnt +#mount.path=/mnt \ No newline at end of file diff --git a/agent/src/main/java/com/cloud/agent/Agent.java b/agent/src/main/java/com/cloud/agent/Agent.java index 7fec460124ac..3379c439ba97 100644 --- a/agent/src/main/java/com/cloud/agent/Agent.java +++ b/agent/src/main/java/com/cloud/agent/Agent.java @@ -27,6 +27,7 @@ import java.nio.channels.ClosedChannelException; import java.nio.charset.Charset; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; @@ -179,7 +180,7 @@ public Agent(final IAgentShell shell, final int localAgentId, final ServerResour _id = value != null ? Long.parseLong(value) : null; s_logger.info("id is " + (_id != null ? _id : "")); - final Map params = PropertiesUtil.toMap(_shell.getProperties()); + final Map params = new HashMap(); // merge with properties from command line to let resource access command line parameters for (final Map.Entry cmdLineProp : _shell.getCmdLineProperties().entrySet()) { diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index b693ce1b2b3e..f187626767a9 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -41,7 +41,6 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; @@ -437,25 +436,14 @@ private void launchAgentFromClassInfo(String resourceClassNames) throws Configur Class impl; try { impl = Class.forName(name); - final Constructor constructor = impl.getDeclaredConstructor(); + Constructor constructor = impl.getDeclaredConstructor(); constructor.setAccessible(true); ServerResource resource = (ServerResource)constructor.newInstance(); launchNewAgent(resource); - } catch (final ClassNotFoundException e) { - throw new ConfigurationException("Resource class not found: " + name + " due to: " + e.toString()); - } catch (final SecurityException e) { - throw new ConfigurationException("Security exception when loading resource: " + name + " due to: " + e.toString()); - } catch (final NoSuchMethodException e) { - throw new ConfigurationException("Method not found exception when loading resource: " + name + " due to: " + e.toString()); - } catch (final IllegalArgumentException e) { - throw new ConfigurationException("Illegal argument exception when loading resource: " + name + " due to: " + e.toString()); - } catch (final InstantiationException e) { - throw new ConfigurationException("Instantiation exception when loading resource: " + name + " due to: " + e.toString()); - } catch (final IllegalAccessException e) { - throw new ConfigurationException("Illegal access exception when loading resource: " + name + " due to: " + e.toString()); - } catch (final InvocationTargetException e) { - throw new ConfigurationException("Invocation target exception when loading resource: " + name + " due to: " + e.toString()); - } + } catch (final Exception e) { + ConfigurationException configurationException = new ConfigurationException(String.format("Error while creating Agent with class [%s].", name)); + configurationException.setRootCause(e); + throw configurationException; } } } @@ -539,10 +527,6 @@ public void start() { s_logger.debug("[ignored] AgentShell was interrupted."); } - } catch (final ConfigurationException e) { - s_logger.error("Unable to start agent: " + e.getMessage()); - System.out.println("Unable to start agent: " + e.getMessage()); - System.exit(ExitStatus.Configuration.value()); } catch (final Exception e) { s_logger.error("Unable to start agent: ", e); System.out.println("Unable to start agent: " + e.getMessage()); diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 980c9b080aa5..92a0536930e2 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -26,48 +26,699 @@ public class AgentProperties{ /** - * Heartbeat update timeout.
- * Data type: int.
- * Default value: 60000 (ms). + * MANDATORY: The GUID to identify the agent with.
+ * Generated with "uuidgen".
+ * Data type: String.
+ * Default value: null + */ + public static final Property GUID = new Property("guid", null, String.class); + + /** + * The java class which the agent loads to execute.
+ * Data type: String.
+ * Default value: com.cloud.hypervisor.kvm.resource.LibvirtComputingResource + */ + public static final Property RESOURCE = new Property("resource", "com.cloud.hypervisor.kvm.resource.LibvirtComputingResource"); + + /** + * The number of threads running in the agent.
+ * Data type: Integer.
+ * Default value: 5 + */ + public static final Property WORKERS = new Property("workers", 5); + + /** + * The IP address of the management server.
+ * Data type: String.
+ * Default value: localhost + */ + public static final Property HOST = new Property("host", "localhost"); + + /** + * The time interval (in seconds) after which the agent will check if the connected host is the preferred host.
+ * After that interval, if the agent is connected to one of the secondary/backup hosts, it will attempt to reconnect to the preferred host.
+ * For more information see the agent.properties file.
+ * Data type: Integer.
+ * Default value: null + */ + public static final Property HOST_LB_CHECK_INTERVAL = new Property("host.lb.check.interval", null, Integer.class); + + /** + * The port that the management server is listening on.
+ * Data type: Integer.
+ * Default value: 8250 + */ + public static final Property PORT = new Property("port", 8250); + + /** + * The cluster which the agent belongs to.
+ * Data type: String.
+ * Default value: default + */ + public static final Property CLUSTER = new Property("cluster", "default"); + + /** + * The pod which the agent belongs to.
+ * Data type: String.
+ * Default value: default + */ + public static final Property POD = new Property("pod", "default"); + + /** + * The zone which the agent belongs to.
+ * Data type: String.
+ * Default value: default + */ + public static final Property ZONE = new Property("zone", "default"); + + /** + * Public NIC device. If this property is commented, it will be autodetected on service startup.
+ * Data type: String.
+ * Default value: cloudbr0 + */ + public static final Property PUBLIC_NETWORK_DEVICE = new Property("public.network.device", "cloudbr0"); + + /** + * Private NIC device. If this property is commented, it will be autodetected on service startup.
+ * Data type: String.
+ * Default value: cloudbr1 + */ + public static final Property PRIVATE_NETWORK_DEVICE = new Property("private.network.device", "cloudbr1"); + + /** + * Guest NIC device. If this property is commented, the value of the private NIC device will be used.
+ * Data type: String.
+ * Default value: the private NIC device value. + */ + public static final Property GUEST_NETWORK_DEVICE = new Property("guest.network.device", null, String.class); + + /** + * Local storage path.
+ * This property allows multiple values to be entered in a single String. The differente values must be separated by commas.
+ * Data type: String.
+ * Default value: /var/lib/libvirt/images/ + */ + public static final Property LOCAL_STORAGE_PATH = new Property("local.storage.path", "/var/lib/libvirt/images/"); + + /** + * Directory where Qemu sockets are placed.
+ * These sockets are for the Qemu Guest Agent and SSVM provisioning.
+ * Make sure that AppArmor or SELinux allows Libvirt to write there.
+ * Data type: String.
+ * Default value: /var/lib/libvirt/qemu + */ + public static final Property QEMU_SOCKETS_PATH = new Property("qemu.sockets.path", "/var/lib/libvirt/qemu"); + + /** + * MANDATORY: The UUID for the local storage pool.
+ * This property allows multiple values to be entered in a single String. The differente values must be separated by commas.
+ * Data type: String.
+ * Default value: null + */ + public static final Property LOCAL_STORAGE_UUID = new Property("local.storage.uuid", null, String.class); + + /** + * Location for KVM virtual router scripts.
+ * The path defined in this property is relative to the directory "/usr/share/cloudstack-common/".
+ * Data type: String.
+ * Default value: scripts/network/domr + */ + public static final Property DOMR_SCRIPTS_DIR = new Property("domr.scripts.dir", "scripts/network/domr"); + + /** + * The timeout (in ms) for time-consuming operations, such as create/copy a snapshot.
+ * Data type: Integer.
+ * Default value: 7200 + */ + public static final Property CMDS_TIMEOUT = new Property("cmds.timeout", 7200); + + /** + * This parameter sets the VM migration speed (in mbps). The default value is -1,
+ * which means that the agent will try to guess the speed of the guest network and consume all possible bandwidth.
+ * When entering a value, make sure to enter it in megabits per second.
+ * Data type: Integer.
+ * Default value: -1 + */ + public static final Property VM_MIGRATE_SPEED = new Property("vm.migrate.speed", -1); + + /** + * Sets target downtime (in ms) at end of livemigration, the 'hiccup' for final copy.
+ * Higher numbers make livemigration easier, lower numbers may cause migration to never complete.
+ * Less than 1 means hypervisor default (20ms).
+ * Data type: Integer.
+ * Default value: -1 + */ + public static final Property VM_MIGRATE_DOWNTIME = new Property("vm.migrate.downtime", -1); + + /** + * Busy VMs may never finish migrating, depending on the environment.
+ * Therefore, if configured, this option will pause the VM after the time entered (in ms) to force the migration to finish.
+ * Less than 1 means disabled.
+ * Data type: Integer.
+ * Default value: -1 + */ + public static final Property VM_MIGRATE_PAUSEAFTER = new Property("vm.migrate.pauseafter", -1); + + /** + * Time (in seconds) to wait for VM migration to finish. Less than 1 means disabled.
+ * For more information see the agent.properties file.
+ * Data type: Integer.
+ * Default value: -1 + */ + public static final Property VM_MIGRATE_WAIT = new Property("vm.migrate.wait", -1); + + /** + * Agent Hooks is the way to override default agent behavior to extend the functionality without excessive coding for a custom deployment.
+ * There are 3 arguments needed for the hook to be called: the base directory (defined in agent.hooks.basedir),
+ * the name of the script that is located in the base directory (defined in agent.hooks.*.script)
+ * and the method that is going to be called on the script (defined in agent.hooks.*.method).
+ * This property defines the agent hooks base directory, where all hooks are located.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: /etc/cloudstack/agent/hooks + */ + public static final Property AGENT_HOOKS_BASEDIR = new Property("agent.hooks.basedir", "/etc/cloudstack/agent/hooks"); + + /** + * This property is used with the agent.hooks.basedir property to define the Libvirt VM XML transformer script.
+ * The method to be called on the script is defined in the property agent.hooks.libvirt_vm_xml_transformer.method.
+ * Libvirt XML transformer hook does XML-to-XML transformation.
+ * The provider can use this to add/remove/modify some sort of attributes in Libvirt XML domain specification.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: libvirt-vm-xml-transformer.groovy + */ + public static final Property AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_SCRIPT = new Property("agent.hooks.libvirt_vm_xml_transformer.script", "libvirt-vm-xml-transformer.groovy"); + + /** + * This property is used with the agent.hooks.basedir and agent.hooks.libvirt_vm_xml_transformer.script properties to define the Libvirt VM XML transformer method.
+ * Libvirt XML transformer hook does XML-to-XML transformation.
+ * The provider can use this to add/remove/modify some sort of attributes in Libvirt XML domain specification.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: transform + */ + public static final Property AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_METHOD = new Property("agent.hooks.libvirt_vm_xml_transformer.method", "transform"); + + /** + * This property is used with the agent.hooks.basedir property to define the Libvirt VM on start script.
+ * The method to be called on the script is defined in the property agent.hooks.libvirt_vm_on_start.method.
+ * The hook is called right after Libvirt successfully launched the VM.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: libvirt-vm-state-change.groovy + */ + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_START_SCRIPT = new Property("agent.hooks.libvirt_vm_on_start.script", "libvirt-vm-state-change.groovy"); + + /** + * This property is used with the agent.hooks.basedir and agent.hooks.libvirt_vm_on_start.script properties to define the Libvirt VM on start method.
+ * The hook is called right after Libvirt successfully launched the VM.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: onStart + */ + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_START_METHOD = new Property("agent.hooks.libvirt_vm_on_start.method", "onStart"); + + /** + * This property is used with the agent.hooks.basedir property to define the Libvirt VM on stop script.
+ * The method to be called on the script is defined in the property agent.hooks.libvirt_vm_on_stop.method.
+ * The hook is called right after Libvirt successfully stopped the VM.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: libvirt-vm-state-change.groovy + */ + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_STOP_SCRIPT = new Property("agent.hooks.libvirt_vm_on_stop.script", "libvirt-vm-state-change.groovy"); + + /** + * This property is used with the agent.hooks.basedir and agent.hooks.libvirt_vm_on_stop.script properties to define the Libvirt VM on stop method.
+ * The hook is called right after libvirt successfully stopped the VM.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: onStop + */ + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_STOP_METHOD = new Property("agent.hooks.libvirt_vm_on_stop.method", "onStop"); + + /** + * Sets the type of bridge used on the hypervisor. This defines what commands the resource will use to setup networking.
+ * Possible values: native | openvswitch
+ * Data type: String.
+ * Default value: native + */ + public static final Property NETWORK_BRIDGE_TYPE = new Property("network.bridge.type", "native"); + + /** + * Sets DPDK Support on OpenVSwitch.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property OPENVSWITCH_DPDK_ENABLED = new Property("openvswitch.dpdk.enabled", false); + + /** + * Sets DPDK Support on OpenVSwitch (path).
+ * Data type: String.
+ * Default value: null + */ + public static final Property OPENVSWITCH_DPDK_OVS_PATH = new Property("openvswitch.dpdk.ovs.path", null, String.class); + + /** + * Sets the hypervisor type.
+ * Possible values: kvm | lxc
+ * Data type: String.
+ * Default value: kvm + */ + public static final Property HYPERVISOR_TYPE = new Property("hypervisor.type", "kvm"); + + /** + * Specifies a directory on the host local storage for temporary storing direct download templates.
+ * Data type: String.
+ * Default value: /var/lib/libvirt/images + */ + public static final Property DIRECT_DOWNLOAD_TEMPORARY_DOWNLOAD_LOCATION = new Property("direct.download.temporary.download.location", + "/var/lib/libvirt/images"); + + /** + * Specifies a directory on the host local storage for creating and hosting the config drives.
+ * Data type: String.
+ * Default value: /var/cache/cloud + */ + public static final Property HOST_CACHE_LOCATION = new Property("host.cache.location", "/var/cache/cloud"); + + /** + * Sets the rolling maintenance hook scripts directory.
+ * Data type: String.
+ * Default value: null + */ + public static final Property ROLLING_MAINTENANCE_HOOKS_DIR = new Property("rolling.maintenance.hooks.dir", null, String.class); + + /** + * Disables the rolling maintenance service execution.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property ROLLING_MAINTENANCE_SERVICE_EXECUTOR_DISABLED = new Property("rolling.maintenance.service.executor.disabled", false); + + /** + * Sets the hypervisor URI.
+ * Value for KVM: qemu:///system
+ * Value for LXC: lxc:///
+ * Data type: String.
+ * Default value: null + */ + public static final Property HYPERVISOR_URI = new Property("hypervisor.uri", null, String.class); + + /** + * Sets the driver used to plug and unplug NICs from the bridges.
+ * A sensible default value will be selected based on the network.bridge.type but can be overridden here.
+ * Value for native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver
+ * Value for openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver
+ * Value to enable direct networking in libvirt = com.cloud.hypervisor.kvm.resource.DirectVifDriver (should not be used on hosts that run system VMs)
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: null + */ + public static final Property LIBVIRT_VIF_DRIVER = new Property("libvirt.vif.driver", null, String.class); + + /** + * Setting to enable direct networking in libvirt.
+ * Should not be used on hosts that run system VMs.
+ * For more information see the agent.properties file.
+ * Possible values: private | bridge | vepa
+ * Data type: String.
+ * Default value: null + */ + public static final Property NETWORK_DIRECT_SOURCE_MODE = new Property("network.direct.source.mode", null, String.class); + + /** + * Setting to enable direct networking in libvirt.
+ * Should not be used on hosts that run system VMs.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: null + */ + public static final Property NETWORK_DIRECT_DEVICE = new Property("network.direct.device", null, String.class); + + /** + * Setting to enable the CPU model to KVM guest globally.
+ * Possible values: custom | host-model | host-passthrough
+ * For more information on each value see the agent.properties file.
+ * Data type: String.
+ * Default value: null + */ + public static final Property GUEST_CPU_MODE = new Property("guest.cpu.mode", null, String.class); + + /** + * Custom CPU model. This param is only valid if property guest.cpu.mode=custom.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: null + */ + public static final Property GUEST_CPU_MODEL = new Property("guest.cpu.model", null, String.class); + + /** + * This param will set the CPU architecture for the domain to override what the management server would send.
+ * In case of arm64 (aarch64), this will change the machine type to 'virt' and add a SCSI and a USB controller in the domain XML.
+ * Possible values: x86_64 | aarch64
+ * Data type: String.
+ * Default value: null (will set as the default of the host's OS). + */ + public static final Property GUEST_CPU_ARCH = new Property("guest.cpu.arch", null, String.class); + + /** + * This param will require CPU features on the CPU section.
+ * The features listed in this property must be separated by a blank space (see example below).
+ * Possible values: vmx vme
+ * Data type: String.
+ * Default value: null + */ + public static final Property GUEST_CPU_FEATURES = new Property("guest.cpu.features", null, String.class); + + /** + * Disables memory ballooning on VM guests for overcommit.
+ * By default overcommit feature enables balloon and sets currentMemory to a minimum value.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property VM_MEMBALLOON_DISABLE = new Property("vm.memballoon.disable", false); + + /** + * Set to true to check disk activity on VM's disks before starting a VM.
+ * This only applies to QCOW2 files, and ensures that there is no other running instance accessing the file before starting.
+ * It works by checking the modified time against the current time, so care must be taken to ensure that the cluster's time is synchronized, otherwise VMs may fail to start.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property VM_DISKACTIVITY_CHECKENABLED = new Property("vm.diskactivity.checkenabled", false); + + /** + * Timeout (in seconds) for giving up on waiting for VM's disk files to become inactive.
+ * Hitting this timeout will result in failure to start VM.
+ * Value must be greater than 0 (zero), otherwise the default value will be used.
+ * Data type: Integer.
+ * Default value: 120 + */ + public static final Property VM_DISKACTIVITY_CHECKTIMEOUT_S = new Property("vm.diskactivity.checktimeout_s", 120); + + /** + * The length of time (in ms) that the disk needs to be inactive in order to pass the check.
+ * This means current time minus time of disk file needs to be greater than this number.
+ * It also has the side effect of setting the minimum threshold between a stop and start of a given VM.
+ * Value must be greater than 0 (zero), otherwise the default value will be used.
+ * Data type: Long.
+ * Default value: 30000L + */ + public static final Property VM_DISKACTIVITY_INACTIVETIME_MS = new Property("vm.diskactivity.inactivetime_ms", 30000L); + + /** + * Some newer linux kernels are incapable of reliably migrating VMs with KVMclock.
+ * This is a workaround for the bug, admin can set this to true per-host.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property KVMCLOCK_DISABLE = new Property("kvmclock.disable", false); + + /** + * This enables the VirtIO Random Number Generator device for guests.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property VM_RNG_ENABLE = new Property("vm.rng.enable", false); + + /** + * The model of VirtIO Random Number Generator (RNG) to present to the Guest.
+ * Currently only 'random' is supported.
+ * Data type: String.
+ * Default value: random + */ + public static final Property VM_RNG_MODEL = new Property("vm.rng.model", "random"); + + /** + * Local Random Number Device Generator to use for VirtIO RNG for Guests.
+ * This is usually /dev/random, but it might be different per platform.
+ * Data type: String.
+ * Default value: /dev/random + */ + public static final Property VM_RNG_PATH = new Property("vm.rng.path", "/dev/random"); + + /** + * The amount of bytes the Guest may request/obtain from the RNG in the period specified in the property vm.rng.rate.period.
+ * Data type: Integer.
+ * Default value: 2048 + */ + public static final Property VM_RNG_RATE_BYTES = new Property("vm.rng.rate.bytes", 2048); + + /** + * The number of milliseconds in which the guest is allowed to obtain the bytes specified in vm.rng.rate.bytes.
+ * Data type: Integer.
+ * Default value: 1000 + */ + public static final Property VM_RNG_RATE_PERIOD = new Property("vm.rng.rate.period", 1000); + + /** + * Timeout value for aggregation commands to be sent to the virtual router (in seconds).
+ * Data type: Long.
+ * Default value: null + */ + public static final Property ROUTER_AGGREGATION_COMMAND_EACH_TIMEOUT = new Property("router.aggregation.command.each.timeout", null, Long.class); + + /** + * Allows to virtually increase the amount of RAM (in MB) available on the host.
+ * This property can be useful if the host uses Zswap, KSM features and other memory compressing technologies.
+ * For example: if the host has 2GB of RAM and this property is set to 2048, the amount of RAM of the host will be read as 4GB.
+ * Data type: Integer.
+ * Default value: 0 + */ + public static final Property HOST_OVERCOMMIT_MEM_MB = new Property("host.overcommit.mem.mb", 0); + + /** + * How much host memory (in MB) to reserve for non-allocation.
+ * A useful parameter if a node uses some other software that requires memory, or in case that OOM Killer kicks in.
+ * If this parameter is used, property host.overcommit.mem.mb must be set to 0.
+ * Data type: Integer.
+ * Default value: 1024 + */ + public static final Property HOST_RESERVED_MEM_MB = new Property("host.reserved.mem.mb", 1024); + + /** + * The model of Watchdog timer to present to the Guest.
+ * For all models refer to the libvirt documentation.
+ * Data type: String.
+ * Default value: i6300esb + */ + public static final Property VM_WATCHDOG_MODEL = new Property("vm.watchdog.model", "i6300esb"); + + /** + * Action to take when the Guest/Instance is no longer notifiying the Watchdog timer.
+ * Possible values: none | reset | poweroff
+ * Data type: String.
+ * Default value: none + */ + public static final Property VM_WATCHDOG_ACTION = new Property("vm.watchdog.action", "none"); + + /** + * Automatically clean up iSCSI sessions not attached to any VM.
+ * Should be enabled for users using managed storage (for example solidfire).
+ * Should be disabled for users with unmanaged iSCSI connections on their hosts.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property ISCSI_SESSION_CLEANUP_ENABLED = new Property("iscsi.session.cleanup.enabled", false); + + /** + * Heartbeat update timeout (in ms).
+ * Depending on the use case, this timeout might need increasing/decreasing.
+ * Data type: Integer.
+ * Default value: 60000 */ public static final Property HEARTBEAT_UPDATE_TIMEOUT = new Property("heartbeat.update.timeout", 60000); /** - * The timeout in seconds to retrieve the target's domain id when migrating a VM with KVM.
- * Data type: int.
- * Default value: 10 (sec). + * The timeout (in seconds) to retrieve the target's domain ID when migrating a VM with KVM.
+ * Data type: Integer.
+ * Default value: 10 */ public static final Property VM_MIGRATE_DOMAIN_RETRIEVE_TIMEOUT = new Property("vm.migrate.domain.retrieve.timeout", 10); /** - * Reboot host and alert management on heartbeat timeout.
- * Data type: boolean.
- * Default value: true. + * This parameter specifies if the host must be rebooted when something goes wrong with the heartbeat.
+ * Data type: Boolean.
+ * Default value: true */ public static final Property REBOOT_HOST_AND_ALERT_MANAGEMENT_ON_HEARTBEAT_TIMEOUT = new Property("reboot.host.and.alert.management.on.heartbeat.timeout", true); /** - * Enable manually setting CPU's topology on KVM's VM.
- * Data type: boolean.
- * Default value: true. + * Enables manually setting CPU's topology on KVM's VM.
+ * Data type: Boolean.
+ * Default value: true */ public static final Property ENABLE_MANUALLY_SETTING_CPU_TOPOLOGY_ON_KVM_VM = new Property("enable.manually.setting.cpu.topology.on.kvm.vm", true); + /** + * Manually sets the host CPU speed (in MHz), in cases where CPU scaling support detects the value is wrong.
+ * Data type: Integer.
+ * Default value: 0 + */ + public static final Property HOST_CPU_MANUAL_SPEED_MHZ = new Property("host.cpu.manual.speed.mhz", 0); + /** * Enable manually IO driver on KVM's VM.
- * Data type: boolean.
- * Default value: true. + * Data type: Boolean.
+ * Default value: true */ public static final Property ENABLE_IO_URING = new Property("enable.io.uring", true); + /** + * Defines the location for Hypervisor scripts.
+ * The path defined in this property is relative.
+ * To locate the script, ACS first tries to concatenate the property path with "/usr/share/cloudstack-agent/lib/".
+ * If it fails, it will test each folder of the path, decreasing one by one, until it reaches root.
+ * If the script is not found, ACS will repeat the same steps concatenating the property path with "/usr/share/cloudstack-common/".
+ * The path defined in this property is relative to the directory "/usr/share/cloudstack-common/".
+ * Data type: String.
+ * Default value: scripts/vm/hypervisor + */ + public static final Property HYPERVISOR_SCRIPTS_DIR = new Property("hypervisor.scripts.dir", "scripts/vm/hypervisor"); + + /** + * Defines the location for KVM scripts.
+ * The path defined in this property is relative.
+ * To locate the script, ACS first tries to concatenate the property path with "/usr/share/cloudstack-agent/lib/".
+ * If it fails, it will test each folder of the path, decreasing one by one, until it reaches root.
+ * If the script is not found, ACS will repeat the same steps concatenating the property path with "/usr/share/cloudstack-common/".
+ * The path defined in this property is relative to the directory "/usr/share/cloudstack-common/".
+ * Data type: String.
+ * Default value: scripts/vm/hypervisor/kvm + */ + public static final Property KVM_SCRIPTS_DIR = new Property("kvm.scripts.dir", "scripts/vm/hypervisor/kvm"); + + /** + * Specifies start MAC address for private IP range.
+ * Data type: String.
+ * Default value: 00:16:3e:77:e2:a0 + */ + public static final Property PRIVATE_MACADDR_START = new Property("private.macaddr.start", "00:16:3e:77:e2:a0"); + + /** + * Specifies start IP for private IP range.
+ * Data type: String.
+ * Default value: 192.168.166.128 + */ + public static final Property PRIVATE_IPADDR_START = new Property("private.ipaddr.start", "192.168.166.128"); + + /** + * Defines Local Bridge Name.
+ * Data type: String.
+ * Default value: null + */ + public static final Property PRIVATE_BRIDGE_NAME = new Property("private.bridge.name", null, String.class); + + /** + * Defines private network name.
+ * Data type: String.
+ * Default value: null + */ + public static final Property PRIVATE_NETWORK_NAME = new Property("private.network.name", null, String.class); + + /** + * Defines the location for network scripts.
+ * The path defined in this property is relative.
+ * To locate the script, ACS first tries to concatenate the property path with "/usr/share/cloudstack-agent/lib/".
+ * If it fails, it will test each folder of the path, decreasing one by one, until it reaches root.
+ * If the script is not found, ACS will repeat the same steps concatenating the property path with "/usr/share/cloudstack-common/".
+ * The path defined in this property is relative to the directory "/usr/share/cloudstack-common/".
+ * Data type: String.
+ * Default value: scripts/vm/network/vnet + */ + public static final Property NETWORK_SCRIPTS_DIR = new Property("network.scripts.dir", "scripts/vm/network/vnet"); + + /** + * Defines the location for storage scripts.
+ * The path defined in this property is relative.
+ * To locate the script, ACS first tries to concatenate the property path with "/usr/share/cloudstack-agent/lib/".
+ * If it fails, it will test each folder of the path, decreasing one by one, until it reaches root.
+ * If the script is not found, ACS will repeat the same steps concatenating the property path with "/usr/share/cloudstack-common/".
+ * The path defined in this property is relative to the directory "/usr/share/cloudstack-common/".
+ * Data type: String.
+ * Default value: scripts/storage/qcow2 + */ + public static final Property STORAGE_SCRIPTS_DIR = new Property("storage.scripts.dir", "scripts/storage/qcow2"); + + /** + * Time (in seconds) to wait for the VM to shutdown gracefully.
+ * If the time is exceeded shutdown will be forced.
+ * Data type: Integer.
+ * Default value: 120 + */ + public static final Property STOP_SCRIPT_TIMEOUT = new Property("stop.script.timeout", 120); + + /** + * Definition of VMs video model type.
+ * Data type: String.
+ * Default value: null + */ + public static final Property VM_VIDEO_HARDWARE = new Property("vm.video.hardware", null, String.class); + + /** + * Definition of VMs video, specifies the amount of RAM in kibibytes (blocks of 1024 bytes).
+ * Data type: Integer.
+ * Default value: 0 + */ + public static final Property VM_VIDEO_RAM = new Property("vm.video.ram", 0); + + /** + * System VM ISO path.
+ * Data type: String.
+ * Default value: null + */ + public static final Property SYSTEMVM_ISO_PATH = new Property("systemvm.iso.path", null, String.class); + + /** + * If set to "true", allows override of the properties: private.macaddr.start, private.ipaddr.start, private.ipaddr.end.
+ * Data type: Boolean.
+ * Default value: false + */ + public static final Property DEVELOPER = new Property("developer", false); + + /** + * Can only be used if developer = true. This property is used to define the local bridge name and private network name.
+ * Data type: String.
+ * Default value: null + */ + public static final Property INSTANCE = new Property("instance", null, String.class); + + /** + * Shows the path to the base directory in which NFS servers are going to be mounted.
+ * Data type: String.
+ * Default value: /mnt + */ + public static final Property MOUNT_PATH = new Property("mount.path", "/mnt"); + public static class Property { - private final String name; - private final T defaultValue; + private String name; + private T defaultValue; + private Class typeClass; + + Property(String name, T value) { + init(name, value); + } - private Property(String name, T value) { + Property(String name, T defaultValue, Class typeClass) { + this.typeClass = typeClass; + init(name, defaultValue); + } + + private void init(String name, T defaultValue) { this.name = name; - this.defaultValue = value; + this.defaultValue = defaultValue; + + if (defaultValue != null) { + this.typeClass = (Class)defaultValue.getClass(); + } + + if (this.typeClass == null) { + throw new RuntimeException("Could not \"discover\" the type class. If you are using \"Null\" as the default value, you must enter the Type class."); + } + } public String getName() { @@ -77,5 +728,9 @@ public String getName() { public T getDefaultValue() { return defaultValue; } + + public Class getTypeClass() { + return typeClass; + } } } diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java b/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java index 6d515f0004f0..7d213199c895 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java @@ -20,6 +20,7 @@ import org.apache.cloudstack.utils.security.KeyStoreUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.converters.IntegerConverter; +import org.apache.commons.beanutils.converters.LongConverter; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; @@ -45,24 +46,34 @@ public static T getPropertyValue(AgentProperties.Property property) { File agentPropertiesFile = PropertiesUtil.findConfigFile(KeyStoreUtils.AGENT_PROPSFILE); - if (agentPropertiesFile != null) { - try { - String configValue = PropertiesUtil.loadFromFile(agentPropertiesFile).getProperty(name); - if (StringUtils.isNotBlank(configValue)) { - if (defaultValue instanceof Integer) { - ConvertUtils.register(new IntegerConverter(defaultValue), Integer.class); - } + if (agentPropertiesFile == null) { + logger.debug(String.format("File [%s] was not found, we will use default defined values. Property [%s]: [%s].", KeyStoreUtils.AGENT_PROPSFILE, name, defaultValue)); + + return defaultValue; + } + + try { + String configValue = PropertiesUtil.loadFromFile(agentPropertiesFile).getProperty(name); + if (StringUtils.isBlank(configValue)) { + logger.debug(String.format("Property [%s] has empty or null value. Using default value [%s].", name, defaultValue)); + + return defaultValue; + } - return (T)ConvertUtils.convert(configValue, defaultValue.getClass()); - } else { - logger.debug(String.format("Property [%s] has empty or null value. Using default value [%s].", name, defaultValue)); + if (defaultValue instanceof Integer) { + ConvertUtils.register(new IntegerConverter(defaultValue), Integer.class); } + + if (defaultValue instanceof Long) { + ConvertUtils.register(new LongConverter(defaultValue), Long.class); + } + + logger.debug(String.format("Property [%s] was altered. Now using the value [%s].", name, configValue)); + return (T)ConvertUtils.convert(configValue, property.getTypeClass()); + } catch (IOException ex) { logger.debug(String.format("Failed to get property [%s]. Using default value [%s].", name, defaultValue), ex); } - } else { - logger.debug(String.format("File [%s] was not found, we will use default defined values. Property [%s]: [%s].", KeyStoreUtils.AGENT_PROPSFILE, name, defaultValue)); - } return defaultValue; } diff --git a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesFileHandlerTest.java b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesFileHandlerTest.java index d91d0e03fb29..1a73bf242566 100644 --- a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesFileHandlerTest.java +++ b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesFileHandlerTest.java @@ -44,12 +44,29 @@ public class AgentPropertiesFileHandlerTest extends TestCase { @Mock AgentProperties.Property agentPropertiesIntegerMock; + @Mock + AgentProperties.Property agentPropertiesLongMock; + @Mock File fileMock; @Mock Properties propertiesMock; + @Test + public void getPropertyValueTestFileNotFoundReturnDefaultValueNull() throws Exception{ + String expectedResult = null; + + AgentProperties.Property agentPropertiesStringMock = new AgentProperties.Property("Test-null", null, String.class); + + PowerMockito.mockStatic(PropertiesUtil.class); + PowerMockito.doReturn(null).when(PropertiesUtil.class, "findConfigFile", Mockito.anyString()); + + String result = AgentPropertiesFileHandler.getPropertyValue(agentPropertiesStringMock); + + Assert.assertEquals(expectedResult, result); + } + @Test public void validateGetPropertyValueFileNotFoundReturnDefaultValue() throws Exception{ String expectedResult = "default value"; @@ -125,11 +142,28 @@ public void validateGetPropertyValueValidPropertyReturnPropertyValue() throws Ex Assert.assertEquals(expectedResult, result); } + @Test + public void getPropertyValueTestValidPropertyReturnPropertyValueWhenDefaultValueIsNull() throws Exception { + String expectedResult = "test"; + + AgentProperties.Property agentPropertiesStringMock = new AgentProperties.Property("Test-null", null, String.class); + + PowerMockito.mockStatic(PropertiesUtil.class); + PowerMockito.doReturn(fileMock).when(PropertiesUtil.class, "findConfigFile", Mockito.anyString()); + PowerMockito.doReturn(propertiesMock).when(PropertiesUtil.class, "loadFromFile", Mockito.any()); + Mockito.doReturn(expectedResult).when(propertiesMock).getProperty(Mockito.anyString()); + + String result = AgentPropertiesFileHandler.getPropertyValue(agentPropertiesStringMock); + + Assert.assertEquals(expectedResult, result); + } + @Test public void validateGetPropertyValueValidIntegerPropertyReturnPropertyValue() throws Exception{ Integer expectedResult = 2; Mockito.doReturn(1).when(agentPropertiesIntegerMock).getDefaultValue(); Mockito.doReturn("name").when(agentPropertiesIntegerMock).getName(); + Mockito.doReturn(Integer.class).when(agentPropertiesIntegerMock).getTypeClass(); PowerMockito.mockStatic(PropertiesUtil.class); PowerMockito.doReturn(fileMock).when(PropertiesUtil.class, "findConfigFile", Mockito.anyString()); @@ -140,4 +174,22 @@ public void validateGetPropertyValueValidIntegerPropertyReturnPropertyValue() th Assert.assertEquals(expectedResult, result); } + + @Test + public void getPropertyValueTestValidLongPropertyReturnPropertyValue() throws Exception{ + Long expectedResult = 600L; + Mockito.doReturn(1L).when(agentPropertiesLongMock).getDefaultValue(); + Mockito.doReturn("name").when(agentPropertiesLongMock).getName(); + Mockito.doReturn(Long.class).when(agentPropertiesLongMock).getTypeClass(); + + PowerMockito.mockStatic(PropertiesUtil.class); + PowerMockito.doReturn(fileMock).when(PropertiesUtil.class, "findConfigFile", Mockito.anyString()); + PowerMockito.doReturn(propertiesMock).when(PropertiesUtil.class, "loadFromFile", Mockito.any()); + Mockito.doReturn(String.valueOf(expectedResult)).when(propertiesMock).getProperty(Mockito.anyString()); + + Long result = AgentPropertiesFileHandler.getPropertyValue(agentPropertiesLongMock); + + Assert.assertEquals(expectedResult, result); + } + } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index 18ff8d42b16f..8d8271a2fbe7 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -35,6 +35,8 @@ import org.libvirt.LibvirtException; import com.cloud.agent.api.to.NicTO; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.exception.InternalErrorException; import com.cloud.network.Networks; import com.cloud.utils.NumbersUtil; @@ -61,10 +63,7 @@ public void configure(Map params) throws ConfigurationException // Set the domr scripts directory params.put("domr.scripts.dir", "scripts/network/domr/kvm"); - String networkScriptsDir = (String)params.get("network.scripts.dir"); - if (networkScriptsDir == null) { - networkScriptsDir = "scripts/vm/network/vnet"; - } + String networkScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_SCRIPTS_DIR); String controlCidr = (String)params.get("control.cidr"); if (StringUtils.isNotBlank(controlCidr)) { diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/IvsVifDriver.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/IvsVifDriver.java index 4c165f74a125..c0dceb3832dd 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/IvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/IvsVifDriver.java @@ -31,6 +31,8 @@ import org.libvirt.LibvirtException; import com.cloud.agent.api.to.NicTO; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.exception.InternalErrorException; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; import com.cloud.network.Networks; @@ -52,10 +54,8 @@ public class IvsVifDriver extends VifDriverBase { @Override public void configure(Map params) throws ConfigurationException { super.configure(params); - String networkScriptsDir = (String)params.get("network.scripts.dir"); - if (networkScriptsDir == null) { - networkScriptsDir = "scripts/vm/network/vnet"; - } + String networkScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_SCRIPTS_DIR); + String utilScriptsDir = "scripts/util/"; String value = (String)params.get("scripts.timeout"); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index c513be6be229..8f0297f018d8 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -322,7 +322,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv public static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud"; public static final String DEFAULTDOMRSSHPORT = "3922"; - public final static String HOST_CACHE_PATH_PARAMETER = "host.cache.location"; public final static String CONFIG_DIR = "config"; public static final String BASH_SCRIPT_PATH = "/bin/bash"; @@ -737,34 +736,6 @@ private Map getDeveloperProperties() throws ConfigurationExcepti } } - private String getDefaultDirectDownloadTemporaryPath() { - return "/var/lib/libvirt/images"; - } - - private String getDefaultCachePath() { - return "/var/cache/cloud"; - } - - protected String getDefaultNetworkScriptsDir() { - return "scripts/vm/network/vnet"; - } - - protected String getDefaultStorageScriptsDir() { - return "scripts/storage/qcow2"; - } - - protected String getDefaultHypervisorScriptsDir() { - return "scripts/vm/hypervisor"; - } - - protected String getDefaultKvmScriptsDir() { - return "scripts/vm/hypervisor/kvm"; - } - - protected String getDefaultDomrScriptsDir() { - return "scripts/network/domr"; - } - protected String getNetworkDirectSourceMode() { return _networkDirectSourceMode; } @@ -788,56 +759,31 @@ public boolean configure(final String name, final Map params) th _storage = new JavaStorageLayer(); _storage.configure("StorageLayer", params); - String domrScriptsDir = (String)params.get("domr.scripts.dir"); - if (domrScriptsDir == null) { - domrScriptsDir = getDefaultDomrScriptsDir(); - } + String domrScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DOMR_SCRIPTS_DIR); - String hypervisorScriptsDir = (String)params.get("hypervisor.scripts.dir"); - if (hypervisorScriptsDir == null) { - hypervisorScriptsDir = getDefaultHypervisorScriptsDir(); - } + String hypervisorScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HYPERVISOR_SCRIPTS_DIR); - String kvmScriptsDir = (String)params.get("kvm.scripts.dir"); - if (kvmScriptsDir == null) { - kvmScriptsDir = getDefaultKvmScriptsDir(); - } + String kvmScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVM_SCRIPTS_DIR); - String networkScriptsDir = (String)params.get("network.scripts.dir"); - if (networkScriptsDir == null) { - networkScriptsDir = getDefaultNetworkScriptsDir(); - } + String networkScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_SCRIPTS_DIR); - String storageScriptsDir = (String)params.get("storage.scripts.dir"); - if (storageScriptsDir == null) { - storageScriptsDir = getDefaultStorageScriptsDir(); - } + String storageScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.STORAGE_SCRIPTS_DIR); - final String bridgeType = (String)params.get("network.bridge.type"); - if (bridgeType == null) { - _bridgeType = BridgeType.NATIVE; - } else { - _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); - } + final String bridgeType = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_BRIDGE_TYPE); + _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); - String dpdk = (String) params.get("openvswitch.dpdk.enabled"); - if (_bridgeType == BridgeType.OPENVSWITCH && Boolean.parseBoolean(dpdk)) { + Boolean dpdk = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_ENABLED); + if (_bridgeType == BridgeType.OPENVSWITCH && dpdk) { dpdkSupport = true; - dpdkOvsPath = (String) params.get("openvswitch.dpdk.ovs.path"); + dpdkOvsPath = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_OVS_PATH); if (dpdkOvsPath != null && !dpdkOvsPath.endsWith("/")) { dpdkOvsPath += "/"; } } - directDownloadTemporaryDownloadPath = (String) params.get("direct.download.temporary.download.location"); - if (StringUtils.isBlank(directDownloadTemporaryDownloadPath)) { - directDownloadTemporaryDownloadPath = getDefaultDirectDownloadTemporaryPath(); - } + directDownloadTemporaryDownloadPath = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DIRECT_DOWNLOAD_TEMPORARY_DOWNLOAD_LOCATION); - cachePath = (String) params.get(HOST_CACHE_PATH_PARAMETER); - if (StringUtils.isBlank(cachePath)) { - cachePath = getDefaultCachePath(); - } + cachePath = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_CACHE_LOCATION); params.put("domr.scripts.dir", domrScriptsDir); @@ -848,22 +794,13 @@ public boolean configure(final String name, final Map params) th return false; } - _host = (String)params.get("host"); - if (_host == null) { - _host = "localhost"; - } + _host = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST); - _dcId = (String)params.get("zone"); - if (_dcId == null) { - _dcId = "default"; - } + _dcId = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ZONE); - _pod = (String)params.get("pod"); - if (_pod == null) { - _pod = "default"; - } + _pod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.POD); - _clusterId = (String)params.get("cluster"); + _clusterId = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CLUSTER); _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, VRScripts.UPDATE_HOST_PASSWD); if (_updateHostPasswdPath == null) { @@ -940,9 +877,7 @@ public boolean configure(final String name, final Map params) th throw new ConfigurationException("Unable to find the ovs-pvlan-kvm-vm.sh"); } - String value = (String)params.get("developer"); - final boolean isDeveloper = Boolean.parseBoolean(value); - + final boolean isDeveloper = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER); if (isDeveloper) { params.putAll(getDeveloperProperties()); } @@ -952,42 +887,32 @@ public boolean configure(final String name, final Map params) th _pool = "/root"; } - final String instance = (String)params.get("instance"); + final String instance = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.INSTANCE); - _hypervisorType = HypervisorType.getType((String)params.get("hypervisor.type")); - if (_hypervisorType == HypervisorType.None) { - _hypervisorType = HypervisorType.KVM; - } + _hypervisorType = HypervisorType.getType(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HYPERVISOR_TYPE)); - String hooksDir = (String)params.get("rolling.maintenance.hooks.dir"); - value = (String) params.get("rolling.maintenance.service.executor.disabled"); - rollingMaintenanceExecutor = Boolean.parseBoolean(value) ? new RollingMaintenanceAgentExecutor(hooksDir) : + String hooksDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROLLING_MAINTENANCE_HOOKS_DIR); + rollingMaintenanceExecutor = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROLLING_MAINTENANCE_SERVICE_EXECUTOR_DISABLED) ? new RollingMaintenanceAgentExecutor(hooksDir) : new RollingMaintenanceServiceExecutor(hooksDir); - _hypervisorURI = (String)params.get("hypervisor.uri"); + _hypervisorURI = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HYPERVISOR_URI); if (_hypervisorURI == null) { _hypervisorURI = LibvirtConnection.getHypervisorURI(_hypervisorType.toString()); } - _networkDirectSourceMode = (String)params.get("network.direct.source.mode"); - _networkDirectDevice = (String)params.get("network.direct.device"); + _networkDirectSourceMode = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_DIRECT_SOURCE_MODE); + _networkDirectDevice = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_DIRECT_DEVICE); - String startMac = (String)params.get("private.macaddr.start"); - if (startMac == null) { - startMac = "00:16:3e:77:e2:a0"; - } + String startMac = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_MACADDR_START); - String startIp = (String)params.get("private.ipaddr.start"); - if (startIp == null) { - startIp = "192.168.166.128"; - } + String startIp = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_IPADDR_START); _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh"); if (_pingTestPath == null) { throw new ConfigurationException("Unable to find the pingtest.sh"); } - _linkLocalBridgeName = (String)params.get("private.bridge.name"); + _linkLocalBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_BRIDGE_NAME); if (_linkLocalBridgeName == null) { if (isDeveloper) { _linkLocalBridgeName = "cloud-" + instance + "-0"; @@ -996,22 +921,16 @@ public boolean configure(final String name, final Map params) th } } - _publicBridgeName = (String)params.get("public.network.device"); - if (_publicBridgeName == null) { - _publicBridgeName = "cloudbr0"; - } + _publicBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PUBLIC_NETWORK_DEVICE); - _privBridgeName = (String)params.get("private.network.device"); - if (_privBridgeName == null) { - _privBridgeName = "cloudbr1"; - } + _privBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_NETWORK_DEVICE); - _guestBridgeName = (String)params.get("guest.network.device"); + _guestBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUEST_NETWORK_DEVICE); if (_guestBridgeName == null) { _guestBridgeName = _privBridgeName; } - _privNwName = (String)params.get("private.network.name"); + _privNwName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_NETWORK_NAME); if (_privNwName == null) { if (isDeveloper) { _privNwName = "cloud-" + instance + "-private"; @@ -1020,80 +939,54 @@ public boolean configure(final String name, final Map params) th } } - configureLocalStorage(params); + configureLocalStorage(); /* Directory to use for Qemu sockets like for the Qemu Guest Agent */ - _qemuSocketsPath = new File("/var/lib/libvirt/qemu"); - String _qemuSocketsPathVar = (String)params.get("qemu.sockets.path"); - if (_qemuSocketsPathVar != null && StringUtils.isNotBlank(_qemuSocketsPathVar)) { - _qemuSocketsPath = new File(_qemuSocketsPathVar); - } + String _qemuSocketsPathVar = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.QEMU_SOCKETS_PATH); + _qemuSocketsPath = new File(_qemuSocketsPathVar); - value = (String)params.get("scripts.timeout"); + // This value is never set. Default value is always used. + String value = (String)params.get("scripts.timeout"); _timeout = Duration.standardSeconds(NumbersUtil.parseInt(value, 30 * 60)); - value = (String)params.get("stop.script.timeout"); - _stopTimeout = NumbersUtil.parseInt(value, 120) * 1000; + _stopTimeout = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.STOP_SCRIPT_TIMEOUT) * 1000; - value = (String)params.get("cmds.timeout"); - _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; + _cmdsTimeout = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CMDS_TIMEOUT) * 1000; - value = (String) params.get("vm.memballoon.disable"); - if (Boolean.parseBoolean(value)) { - _noMemBalloon = true; - } + _noMemBalloon = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MEMBALLOON_DISABLE); + + _manualCpuSpeed = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_CPU_MANUAL_SPEED_MHZ); - value = (String)params.get("host.cpu.manual.speed.mhz"); - _manualCpuSpeed = NumbersUtil.parseInt(value, 0); + _videoHw = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_VIDEO_HARDWARE); - _videoHw = (String) params.get("vm.video.hardware"); - value = (String) params.get("vm.video.ram"); - _videoRam = NumbersUtil.parseInt(value, 0); + _videoRam = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_VIDEO_RAM); - value = (String)params.get("host.reserved.mem.mb"); // Reserve 1GB unless admin overrides - _dom0MinMem = NumbersUtil.parseInt(value, 1024) * 1024* 1024L; + _dom0MinMem = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB) * 1024 * 1024L; - value = (String)params.get("host.overcommit.mem.mb"); // Support overcommit memory for host if host uses ZSWAP, KSM and other memory // compressing technologies - _dom0OvercommitMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024L; + _dom0OvercommitMem = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB) * 1024 * 1024L; - value = (String) params.get("kvmclock.disable"); - if (Boolean.parseBoolean(value)) { + if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVMCLOCK_DISABLE)) { _noKvmClock = true; } - value = (String) params.get("vm.rng.enable"); - if (Boolean.parseBoolean(value)) { + if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_ENABLE)) { _rngEnable = true; - value = (String) params.get("vm.rng.model"); - if (StringUtils.isNotEmpty(value)) { - _rngBackendModel = RngBackendModel.valueOf(value.toUpperCase()); - } + _rngBackendModel = RngBackendModel.valueOf(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_MODEL).toUpperCase()); - value = (String) params.get("vm.rng.path"); - if (StringUtils.isNotEmpty(value)) { - _rngPath = value; - } + _rngPath = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_PATH); - value = (String) params.get("vm.rng.rate.bytes"); - _rngRateBytes = NumbersUtil.parseInt(value, new Integer(_rngRateBytes)); + _rngRateBytes = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_RATE_BYTES); - value = (String) params.get("vm.rng.rate.period"); - _rngRatePeriod = NumbersUtil.parseInt(value, new Integer(_rngRatePeriod)); + _rngRatePeriod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_RATE_PERIOD); } - value = (String) params.get("vm.watchdog.model"); - if (StringUtils.isNotEmpty(value)) { - _watchDogModel = WatchDogModel.valueOf(value.toUpperCase()); - } + _watchDogModel = WatchDogModel.valueOf(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_WATCHDOG_MODEL).toUpperCase()); - value = (String) params.get("vm.watchdog.action"); - if (StringUtils.isNotEmpty(value)) { - _watchDogAction = WatchDogAction.valueOf(value.toUpperCase()); - } + _watchDogAction = WatchDogAction.valueOf(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_WATCHDOG_ACTION).toUpperCase()); LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; @@ -1141,15 +1034,15 @@ public boolean configure(final String name, final Map params) th s_logger.trace("Ignoring libvirt error.", e); } - final String cpuArchOverride = (String)params.get("guest.cpu.arch"); + final String cpuArchOverride = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUEST_CPU_ARCH); if (StringUtils.isNotEmpty(cpuArchOverride)) { _guestCpuArch = cpuArchOverride; s_logger.info("Using guest CPU architecture: " + _guestCpuArch); } - _guestCpuMode = (String)params.get("guest.cpu.mode"); + _guestCpuMode = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUEST_CPU_MODE); if (_guestCpuMode != null) { - _guestCpuModel = (String)params.get("guest.cpu.model"); + _guestCpuModel = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUEST_CPU_MODEL); if (_hypervisorLibvirtVersion < 9 * 1000 + 10) { s_logger.warn("Libvirt version 0.9.10 required for guest cpu mode, but version " + prettyVersion(_hypervisorLibvirtVersion) + @@ -1161,7 +1054,7 @@ public boolean configure(final String name, final Map params) th params.put("guest.cpu.model", _guestCpuModel); } - final String cpuFeatures = (String)params.get("guest.cpu.features"); + final String cpuFeatures = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUEST_CPU_FEATURES); if (cpuFeatures != null) { _cpuFeatures = new ArrayList(); for (final String feature: cpuFeatures.split(" ")) { @@ -1220,24 +1113,17 @@ public boolean configure(final String name, final Map params) th s_logger.warn("No default IPv4 gateway found"); } - _mountPoint = (String)params.get("mount.path"); - if (_mountPoint == null) { - _mountPoint = "/mnt"; - } + _mountPoint = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.MOUNT_PATH); - value = (String) params.get("vm.migrate.downtime"); - _migrateDowntime = NumbersUtil.parseInt(value, -1); + _migrateDowntime = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_DOWNTIME); - value = (String) params.get("vm.migrate.pauseafter"); - _migratePauseAfter = NumbersUtil.parseInt(value, -1); + _migratePauseAfter = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_PAUSEAFTER); - value = (String) params.get("vm.migrate.wait"); - _migrateWait = NumbersUtil.parseInt(value, -1); + _migrateWait = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_WAIT); configureAgentHooks(params); - value = (String)params.get("vm.migrate.speed"); - _migrateSpeed = NumbersUtil.parseInt(value, -1); + _migrateSpeed = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_SPEED); if (_migrateSpeed == -1) { //get guest network device speed _migrateSpeed = 0; @@ -1269,7 +1155,7 @@ public boolean configure(final String name, final Map params) th storageProcessor.configure(name, params); storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor); - Boolean _iscsiCleanUpEnabled = Boolean.parseBoolean((String)params.get("iscsi.session.cleanup.enabled")); + Boolean _iscsiCleanUpEnabled = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ISCSI_SESSION_CLEANUP_ENABLED); if (BooleanUtils.isTrue(_iscsiCleanUpEnabled)) { IscsiStorageCleanupMonitor isciCleanupMonitor = new IscsiStorageCleanupMonitor(); @@ -1282,20 +1168,21 @@ public boolean configure(final String name, final Map params) th return true; } - protected void configureLocalStorage(final Map params) throws ConfigurationException { - String localStoragePath = (String)params.get(LOCAL_STORAGE_PATH); - if (localStoragePath == null) { - localStoragePath = DEFAULT_LOCAL_STORAGE_PATH; - } - String localStorageUUIDString = (String)params.get(LOCAL_STORAGE_UUID); + protected void configureLocalStorage() throws ConfigurationException { + String localStoragePath = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LOCAL_STORAGE_PATH); + s_logger.debug(String.format("Local Storage Path set: [%s].", localStoragePath)); + + String localStorageUUIDString = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LOCAL_STORAGE_UUID); if (localStorageUUIDString == null) { localStorageUUIDString = UUID.randomUUID().toString(); } + s_logger.debug(String.format("Local Storage UUID set: [%s].", localStorageUUIDString)); String[] localStorageRelativePaths = localStoragePath.split(CONFIG_VALUES_SEPARATOR); String[] localStorageUUIDStrings = localStorageUUIDString.split(CONFIG_VALUES_SEPARATOR); if (localStorageRelativePaths.length != localStorageUUIDStrings.length) { - throw new ConfigurationException("The path and UUID of local storage pools have different length"); + s_logger.error(String.format("The path and UUID of the local storage pools have different length. Path: [%s], UUID: [%s].", localStoragePath, localStorageUUIDString)); + throw new ConfigurationException(String.format("The path and UUID of the local storage pools have different length. Path: [%s], UUID: [%s].", localStoragePath, localStorageUUIDString)); } for (String localStorageRelativePath : localStorageRelativePaths) { final File storagePath = new File(localStorageRelativePath); @@ -1328,9 +1215,8 @@ public boolean configureHostParams(final Map params) { // Save configurations in agent.properties PropertiesStorage storage = new PropertiesStorage(); storage.configure("Storage", new HashMap()); - if (params.get("router.aggregation.command.each.timeout") != null) { - String value = (String)params.get("router.aggregation.command.each.timeout"); - Long longValue = NumbersUtil.parseLong(value, 600); + Long longValue = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROUTER_AGGREGATION_COMMAND_EACH_TIMEOUT); + if (longValue != null) { storage.persist("router.aggregation.command.each.timeout", String.valueOf(longValue)); } @@ -1345,46 +1231,26 @@ public boolean configureHostParams(final Map params) { } private void configureAgentHooks(final Map params) { - String value = (String) params.get("agent.hooks.basedir"); - if (null != value) { - _agentHooksBasedir = value; - } + _agentHooksBasedir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_BASEDIR); s_logger.debug("agent.hooks.basedir is " + _agentHooksBasedir); - value = (String) params.get("agent.hooks.libvirt_vm_xml_transformer.script"); - if (null != value) { - _agentHooksLibvirtXmlScript = value; - } + + _agentHooksLibvirtXmlScript = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_SCRIPT); s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.script is " + _agentHooksLibvirtXmlScript); - value = (String) params.get("agent.hooks.libvirt_vm_xml_transformer.method"); - if (null != value) { - _agentHooksLibvirtXmlMethod = value; - } + _agentHooksLibvirtXmlMethod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_METHOD); s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.method is " + _agentHooksLibvirtXmlMethod); - value = (String) params.get("agent.hooks.libvirt_vm_on_start.script"); - if (null != value) { - _agentHooksVmOnStartScript = value; - } + _agentHooksVmOnStartScript = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_ON_START_SCRIPT); s_logger.debug("agent.hooks.libvirt_vm_on_start.script is " + _agentHooksVmOnStartScript); - value = (String) params.get("agent.hooks.libvirt_vm_on_start.method"); - if (null != value) { - _agentHooksVmOnStartMethod = value; - } + _agentHooksVmOnStartMethod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_ON_START_METHOD); s_logger.debug("agent.hooks.libvirt_vm_on_start.method is " + _agentHooksVmOnStartMethod); - value = (String) params.get("agent.hooks.libvirt_vm_on_stop.script"); - if (null != value) { - _agentHooksVmOnStopScript = value; - } + _agentHooksVmOnStopScript = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_ON_STOP_SCRIPT); s_logger.debug("agent.hooks.libvirt_vm_on_stop.script is " + _agentHooksVmOnStopScript); - value = (String) params.get("agent.hooks.libvirt_vm_on_stop.method"); - if (null != value) { - _agentHooksVmOnStopMethod = value; - } + _agentHooksVmOnStopMethod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_ON_STOP_METHOD); s_logger.debug("agent.hooks.libvirt_vm_on_stop.method is " + _agentHooksVmOnStopMethod); } @@ -1414,13 +1280,13 @@ private void loadUefiProperties() throws FileNotFoundException { } protected void configureDiskActivityChecks(final Map params) { - _diskActivityCheckEnabled = Boolean.parseBoolean((String)params.get("vm.diskactivity.checkenabled")); + _diskActivityCheckEnabled = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_DISKACTIVITY_CHECKENABLED); if (_diskActivityCheckEnabled) { - final int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0); + final int timeout = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_DISKACTIVITY_CHECKTIMEOUT_S); if (timeout > 0) { _diskActivityCheckTimeoutSeconds = timeout; } - final long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L); + final long inactiveTime = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_DISKACTIVITY_INACTIVETIME_MS); if (inactiveTime > 0) { _diskActivityInactiveThresholdMilliseconds = inactiveTime; } @@ -1433,7 +1299,7 @@ protected void configureVifDrivers(final Map params) throws Conf _trafficTypeVifDrivers = new HashMap(); // Load the default vif driver - String defaultVifDriverName = (String)params.get(LIBVIRT_VIF_DRIVER); + String defaultVifDriverName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER); if (defaultVifDriverName == null) { if (_bridgeType == BridgeType.OPENVSWITCH) { s_logger.info("No libvirt.vif.driver specified. Defaults to OvsVifDriver."); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 05d33bc3418f..b97cfd5ab905 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -33,6 +33,8 @@ import org.libvirt.LibvirtException; import com.cloud.agent.api.to.NicTO; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.exception.InternalErrorException; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; import com.cloud.network.Networks; @@ -53,13 +55,9 @@ public void configure(Map params) throws ConfigurationException getPifs(); - String networkScriptsDir = (String)params.get("network.scripts.dir"); - if (networkScriptsDir == null) { - networkScriptsDir = "scripts/vm/network/vnet"; - } + String networkScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_SCRIPTS_DIR); - String dpdk = (String) params.get("openvswitch.dpdk.enabled"); - if (StringUtils.isNotBlank(dpdk) && Boolean.parseBoolean(dpdk)) { + if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_ENABLED)) { dpdkDriver = new DpdkDriverImpl(); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java index f73307be131b..e9776eb73504 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java @@ -99,6 +99,8 @@ import com.cloud.agent.direct.download.HttpsDirectTemplateDownloader; import com.cloud.agent.direct.download.MetalinkDirectTemplateDownloader; import com.cloud.agent.direct.download.NfsDirectTemplateDownloader; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.exception.InternalErrorException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.hypervisor.Hypervisor; @@ -122,7 +124,6 @@ import com.cloud.storage.template.QCOW2Processor; import com.cloud.storage.template.TemplateConstants; import com.cloud.storage.template.TemplateLocation; -import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.UriUtils; import com.cloud.utils.exception.CloudRuntimeException; @@ -168,10 +169,7 @@ public boolean configure(final String name, final Map params) th storageLayer = new JavaStorageLayer(); storageLayer.configure("StorageLayer", params); - String storageScriptsDir = (String)params.get("storage.scripts.dir"); - if (storageScriptsDir == null) { - storageScriptsDir = getDefaultStorageScriptsDir(); - } + String storageScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.STORAGE_SCRIPTS_DIR); _createTmplPath = Script.findScript(storageScriptsDir, "createtmplt.sh"); if (_createTmplPath == null) { @@ -183,8 +181,7 @@ public boolean configure(final String name, final Map params) th throw new ConfigurationException("Unable to find the managesnapshot.sh"); } - final String value = (String)params.get("cmds.timeout"); - _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; + _cmdsTimeout = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CMDS_TIMEOUT) * 1000; return true; } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java index ffe54f73da5f..b1427510f05c 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java @@ -162,6 +162,8 @@ import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.exception.InternalErrorException; import com.cloud.hypervisor.Hypervisor.HypervisorType; @@ -213,12 +215,12 @@ import org.libvirt.VcpuInfo; @RunWith(PowerMockRunner.class) -@PrepareForTest(value = {MemStat.class, SshHelper.class}) +@PrepareForTest(value = {MemStat.class, SshHelper.class, AgentPropertiesFileHandler.class}) @PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*"}) public class LibvirtComputingResourceTest { @Mock - private LibvirtComputingResource libvirtComputingResource; + private LibvirtComputingResource libvirtComputingResourceMock; @Mock VirtualMachineTO vmTO; @Mock @@ -995,7 +997,7 @@ public void testStopCommandNoCheck() { final String vmName = "Test"; final StopCommand command = new StopCommand(vmName, false, false); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); } catch (final LibvirtException e) { @@ -1005,11 +1007,11 @@ public void testStopCommandNoCheck() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1029,7 +1031,7 @@ public void testStopCommandCheckVmNOTRunning() { final String vmName = "Test"; final StopCommand command = new StopCommand(vmName, false, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); when(conn.domainLookupByName(command.getVmName())).thenReturn(vm); @@ -1043,11 +1045,11 @@ public void testStopCommandCheckVmNOTRunning() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(2)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1068,7 +1070,7 @@ public void testStopCommandCheckException1() { final String vmName = "Test"; final StopCommand command = new StopCommand(vmName, false, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class); when(conn.domainLookupByName(command.getVmName())).thenReturn(vm); @@ -1082,11 +1084,11 @@ public void testStopCommandCheckException1() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(2)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1106,7 +1108,7 @@ public void testStopCommandCheckVmRunning() { final String vmName = "Test"; final StopCommand command = new StopCommand(vmName, false, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); when(conn.domainLookupByName(command.getVmName())).thenReturn(vm); @@ -1120,11 +1122,11 @@ public void testStopCommandCheckVmRunning() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1144,7 +1146,7 @@ public void testGetVmStatsCommand() { final GetVmStatsCommand command = new GetVmStatsCommand(vms, uuid, "hostname"); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); } catch (final LibvirtException e) { @@ -1154,10 +1156,10 @@ public void testGetVmStatsCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1177,7 +1179,7 @@ public void testGetVmDiskStatsCommand() { final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname"); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnection()).thenReturn(conn); } catch (final LibvirtException e) { @@ -1187,10 +1189,10 @@ public void testGetVmDiskStatsCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnection(); } catch (final LibvirtException e) { @@ -1210,7 +1212,7 @@ public void testGetVmDiskStatsCommandException() { final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname"); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnection()).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -1220,10 +1222,10 @@ public void testGetVmDiskStatsCommandException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnection(); } catch (final LibvirtException e) { @@ -1239,7 +1241,7 @@ public void testRebootCommand() { final String vmName = "Test"; final RebootCommand command = new RebootCommand(vmName, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); } catch (final LibvirtException e) { @@ -1249,10 +1251,10 @@ public void testRebootCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1268,7 +1270,7 @@ public void testRebootCommandException1() { final String vmName = "Test"; final RebootCommand command = new RebootCommand(vmName, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -1278,10 +1280,10 @@ public void testRebootCommandException1() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1297,10 +1299,10 @@ public void testRebootCommandError() { final String vmName = "Test"; final RebootCommand command = new RebootCommand(vmName, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); - when(libvirtComputingResource.rebootVM(conn, command.getVmName())).thenReturn("error"); + when(libvirtComputingResourceMock.rebootVM(conn, command.getVmName())).thenReturn("error"); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -1308,10 +1310,10 @@ public void testRebootCommandError() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1328,10 +1330,10 @@ public void testRebootCommandException2() { final String vmName = "Test"; final RebootCommand command = new RebootCommand(vmName, true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); - when(libvirtComputingResource.rebootVM(conn, command.getVmName())).thenThrow(LibvirtException.class); + when(libvirtComputingResourceMock.rebootVM(conn, command.getVmName())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -1339,10 +1341,10 @@ public void testRebootCommandException2() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1359,8 +1361,8 @@ public void testRebootRouterCommand() { final String vmName = "Test"; final RebootRouterCommand command = new RebootRouterCommand(vmName, "127.0.0.1"); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(routingResource); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); } catch (final LibvirtException e) { @@ -1370,12 +1372,12 @@ public void testRebootRouterCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getVirtRouterResource(); + verify(libvirtComputingResourceMock, times(1)).getVirtRouterResource(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1392,8 +1394,8 @@ public void testRebootRouterCommandConnect() { final String vmName = "Test"; final RebootRouterCommand command = new RebootRouterCommand(vmName, "127.0.0.1"); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(routingResource); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(routingResource.connect(command.getPrivateIpAddress())).thenReturn(true); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); @@ -1404,11 +1406,11 @@ public void testRebootRouterCommandConnect() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getVirtRouterResource(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getVirtRouterResource(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1426,9 +1428,9 @@ public void testGetHostStatsCommand() { final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6"; final GetHostStatsCommand command = new GetHostStatsCommand(uuid, "summer", 1l); - when(libvirtComputingResource.getCPUStat()).thenReturn(cpuStat); - when(libvirtComputingResource.getMemStat()).thenReturn(memStat); - when(libvirtComputingResource.getNicStats(nullable(String.class))).thenReturn(new Pair(1.0d, 1.0d)); + when(libvirtComputingResourceMock.getCPUStat()).thenReturn(cpuStat); + when(libvirtComputingResourceMock.getMemStat()).thenReturn(memStat); + when(libvirtComputingResourceMock.getNicStats(nullable(String.class))).thenReturn(new Pair(1.0d, 1.0d)); when(cpuStat.getCpuUsedPercent()).thenReturn(0.5d); when(memStat.getAvailable()).thenReturn(1500L); when(memStat.getTotal()).thenReturn(15000L); @@ -1436,11 +1438,11 @@ public void testGetHostStatsCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getCPUStat(); - verify(libvirtComputingResource, times(1)).getMemStat(); + verify(libvirtComputingResourceMock, times(1)).getCPUStat(); + verify(libvirtComputingResourceMock, times(1)).getMemStat(); verify(cpuStat, times(1)).getCpuUsedPercent(); verify(memStat, times(1)).getAvailable(); verify(memStat, times(1)).getTotal(); @@ -1453,7 +1455,7 @@ public void testCheckHealthCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -1470,7 +1472,7 @@ public void testPrepareForMigrationCommand() { final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -1483,23 +1485,23 @@ public void testPrepareForMigrationCommand() { when(nicTO.getType()).thenReturn(TrafficType.Guest); when(diskTO.getType()).thenReturn(Volume.Type.ISO); - when(libvirtComputingResource.getVifDriver(nicTO.getType(), nicTO.getName())).thenReturn(vifDriver); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager); + when(libvirtComputingResourceMock.getVifDriver(nicTO.getType(), nicTO.getName())).thenReturn(vifDriver); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName()); } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(vm, times(1)).getNics(); verify(vm, times(1)).getDisks(); verify(diskTO, times(1)).getType(); @@ -1518,7 +1520,7 @@ public void testPrepareForMigrationCommandMigration() { final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -1531,24 +1533,24 @@ public void testPrepareForMigrationCommandMigration() { when(nicTO.getType()).thenReturn(TrafficType.Guest); when(diskTO.getType()).thenReturn(Volume.Type.ISO); - when(libvirtComputingResource.getVifDriver(nicTO.getType(), nicTO.getName())).thenReturn(vifDriver); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager); + when(libvirtComputingResourceMock.getVifDriver(nicTO.getType(), nicTO.getName())).thenReturn(vifDriver); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager); when(storagePoolManager.connectPhysicalDisksViaVmSpec(vm)).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName()); } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(vm, times(1)).getNics(); verify(vm, times(1)).getDisks(); verify(diskTO, times(1)).getType(); @@ -1566,7 +1568,7 @@ public void testPrepareForMigrationCommandLibvirtException() { final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -1576,23 +1578,23 @@ public void testPrepareForMigrationCommandLibvirtException() { when(vm.getNics()).thenReturn(new NicTO[]{nicTO}); when(nicTO.getType()).thenReturn(TrafficType.Guest); - when(libvirtComputingResource.getVifDriver(nicTO.getType())).thenReturn(vifDriver); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager); + when(libvirtComputingResourceMock.getVifDriver(nicTO.getType())).thenReturn(vifDriver); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName()); } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(vm, times(1)).getNics(); } @@ -1610,7 +1612,7 @@ public void testPrepareForMigrationCommandURISyntaxException() { final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -1623,10 +1625,10 @@ public void testPrepareForMigrationCommandURISyntaxException() { when(nicTO.getType()).thenReturn(TrafficType.Guest); when(volume.getType()).thenReturn(Volume.Type.ISO); - when(libvirtComputingResource.getVifDriver(nicTO.getType(), nicTO.getName())).thenReturn(vifDriver); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager); + when(libvirtComputingResourceMock.getVifDriver(nicTO.getType(), nicTO.getName())).thenReturn(vifDriver); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager); try { - when(libvirtComputingResource.getVolumePath(conn, volume)).thenThrow(URISyntaxException.class); + when(libvirtComputingResourceMock.getVolumePath(conn, volume)).thenThrow(URISyntaxException.class); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final URISyntaxException e) { @@ -1636,17 +1638,17 @@ public void testPrepareForMigrationCommandURISyntaxException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName()); } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(vm, times(1)).getNics(); verify(vm, times(1)).getDisks(); verify(volume, times(1)).getType(); @@ -1665,7 +1667,7 @@ public void testPrepareForMigrationCommandInternalErrorException() { final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -1675,10 +1677,10 @@ public void testPrepareForMigrationCommandInternalErrorException() { when(vm.getNics()).thenReturn(new NicTO[]{nicTO}); when(nicTO.getType()).thenReturn(TrafficType.Guest); - BDDMockito.given(libvirtComputingResource.getVifDriver(nicTO.getType(), nicTO.getName())).willAnswer(invocationOnMock -> {throw new InternalErrorException("Exception Occurred");}); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager); + BDDMockito.given(libvirtComputingResourceMock.getVifDriver(nicTO.getType(), nicTO.getName())).willAnswer(invocationOnMock -> {throw new InternalErrorException("Exception Occurred");}); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolManager); try { - when(libvirtComputingResource.getVolumePath(conn, volume)).thenReturn("/path"); + when(libvirtComputingResourceMock.getVolumePath(conn, volume)).thenReturn("/path"); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final URISyntaxException e) { @@ -1688,17 +1690,17 @@ public void testPrepareForMigrationCommandInternalErrorException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName()); } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(vm, times(1)).getNics(); } @@ -1716,7 +1718,7 @@ public void testMigrateCommand() { DiskTO[] diskTOS = new DiskTO[]{}; final MigrateCommand command = new MigrateCommand(vmName, destIp, isWindows, vmTO, executeInSequence ); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(vmTO.getDisks()).thenReturn(diskTOS); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); @@ -1730,18 +1732,18 @@ public void testMigrateCommand() { final List ifaces = new ArrayList(); ifaces.add(interfaceDef); - when(libvirtComputingResource.getInterfaces(conn, vmName)).thenReturn(ifaces); + when(libvirtComputingResourceMock.getInterfaces(conn, vmName)).thenReturn(ifaces); final DiskDef diskDef = Mockito.mock(DiskDef.class); final List disks = new ArrayList(); disks.add(diskDef); - when(libvirtComputingResource.getDisks(conn, vmName)).thenReturn(disks); + when(libvirtComputingResourceMock.getDisks(conn, vmName)).thenReturn(disks); final Domain dm = Mockito.mock(Domain.class); try { when(conn.domainLookupByName(vmName)).thenReturn(dm); - when(libvirtComputingResource.getPrivateIp()).thenReturn("127.0.0.1"); + when(libvirtComputingResourceMock.getPrivateIp()).thenReturn("127.0.0.1"); when(dm.getXMLDesc(8)).thenReturn("" + " " + " " + " " + " " + " " + ""); when(dm.getXMLDesc(1)).thenReturn("" + " " + " " @@ -1758,10 +1760,10 @@ public void testMigrateCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); verify(libvirtUtilitiesHelper, times(1)).retrieveQemuConnection("qemu+tcp://" + command.getDestinationIp() + "/system"); @@ -1769,8 +1771,8 @@ public void testMigrateCommand() { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getInterfaces(conn, vmName); - verify(libvirtComputingResource, times(1)).getDisks(conn, vmName); + verify(libvirtComputingResourceMock, times(1)).getInterfaces(conn, vmName); + verify(libvirtComputingResourceMock, times(1)).getDisks(conn, vmName); try { verify(conn, times(1)).domainLookupByName(vmName); } catch (final LibvirtException e) { @@ -1796,7 +1798,7 @@ public void testPingTestHostIpCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -1807,7 +1809,7 @@ public void testPingTestPvtIpCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -1818,7 +1820,7 @@ public void testPingOnlyOneIpCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -1830,22 +1832,22 @@ public void testCheckVirtualMachineCommand() { final String vmName = "Test"; final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); } catch (final LibvirtException e) { fail(e.getMessage()); } - when(libvirtComputingResource.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn); + when(libvirtComputingResourceMock.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1862,22 +1864,22 @@ public void testExceptionCheckVirtualMachineCommand() { final String vmName = "Test"; final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { fail(e.getMessage()); } - when(libvirtComputingResource.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn); + when(libvirtComputingResourceMock.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1892,7 +1894,7 @@ public void testReadyCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -1904,7 +1906,7 @@ public void testAttachIsoCommand() { final String vmName = "Test"; final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); } catch (final LibvirtException e) { @@ -1914,10 +1916,10 @@ public void testAttachIsoCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1933,7 +1935,7 @@ public void testAttachIsoCommandLibvirtException() { final String vmName = "Test"; final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -1943,10 +1945,10 @@ public void testAttachIsoCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1962,7 +1964,7 @@ public void testAttachIsoCommandURISyntaxException() { final String vmName = "Test"; final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { BDDMockito.given(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).willAnswer(invocationOnMock -> {throw new URISyntaxException("Exception trying to get connection by VM name", vmName);}); } catch (final LibvirtException e) { @@ -1972,10 +1974,10 @@ public void testAttachIsoCommandURISyntaxException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -1991,7 +1993,7 @@ public void testAttachIsoCommandInternalErrorException() { final String vmName = "Test"; final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { BDDMockito.given(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).willAnswer(invocationOnMock -> {throw new InternalErrorException("Exception Occurred");}); } catch (final LibvirtException e) { @@ -2001,10 +2003,10 @@ public void testAttachIsoCommandInternalErrorException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -2025,7 +2027,7 @@ public void testWatchConsoleProxyLoadCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -2041,7 +2043,7 @@ public void testCheckConsoleProxyLoadCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -2052,7 +2054,7 @@ public void testGetVncPortCommand() { final GetVncPortCommand command = new GetVncPortCommand(1l, "host"); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -2062,10 +2064,10 @@ public void testGetVncPortCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getName()); } catch (final LibvirtException e) { @@ -2080,7 +2082,7 @@ public void testGetVncPortCommandLibvirtException() { final GetVncPortCommand command = new GetVncPortCommand(1l, "host"); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getName())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -2090,10 +2092,10 @@ public void testGetVncPortCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getName()); } catch (final LibvirtException e) { @@ -2106,21 +2108,21 @@ public void testModifySshKeysCommand() { final ModifySshKeysCommand command = new ModifySshKeysCommand("", ""); final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.retrieveSshKeysPath()).thenReturn("/path/keys"); when(libvirtUtilitiesHelper.retrieveSshPubKeyPath()).thenReturn("/path/pub/keys"); when(libvirtUtilitiesHelper.retrieveSshPrvKeyPath()).thenReturn("/path/pvt/keys"); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getTimeout(); + verify(libvirtComputingResourceMock, times(1)).getTimeout(); } @Test @@ -2130,7 +2132,7 @@ public void testMaintainCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -2146,7 +2148,7 @@ public void testCreateCommandNoTemplate() { final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class); final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(poolManager); when(poolManager.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary); when(primary.createPhysicalDisk(diskCharacteristics.getPath(), diskCharacteristics.getProvisioningType(), diskCharacteristics.getSize())).thenReturn(vol); @@ -2154,10 +2156,10 @@ public void testCreateCommandNoTemplate() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid()); } @@ -2174,19 +2176,19 @@ public void testCreateCommand() { final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class); final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(poolManager); when(poolManager.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary); when(primary.getType()).thenReturn(StoragePoolType.CLVM); - when(libvirtComputingResource.templateToPrimaryDownload(command.getTemplateUrl(), primary, diskCharacteristics.getPath())).thenReturn(vol); + when(libvirtComputingResourceMock.templateToPrimaryDownload(command.getTemplateUrl(), primary, diskCharacteristics.getPath())).thenReturn(vol); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid()); } @@ -2204,7 +2206,7 @@ public void testCreateCommandCLVM() { final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class); final KVMPhysicalDisk baseVol = Mockito.mock(KVMPhysicalDisk.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(poolManager); when(poolManager.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary); when(primary.getPhysicalDisk(command.getTemplateUrl())).thenReturn(baseVol); @@ -2213,10 +2215,10 @@ public void testCreateCommandCLVM() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid()); } @@ -2233,16 +2235,16 @@ public void testDestroyCommand() { final VolumeTO vol = command.getVolume(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(poolManager); when(poolManager.getStoragePool(vol.getPoolType(), vol.getPoolUuid())).thenReturn(primary); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(poolManager, times(1)).getStoragePool(vol.getPoolType(), vol.getPoolUuid()); } @@ -2260,7 +2262,7 @@ public void testDestroyCommandError() { final VolumeTO vol = command.getVolume(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(poolManager); when(poolManager.getStoragePool(vol.getPoolType(), vol.getPoolUuid())).thenReturn(primary); when(primary.deletePhysicalDisk(vol.getPath(), null)).thenThrow(CloudRuntimeException.class); @@ -2268,10 +2270,10 @@ public void testDestroyCommandError() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(poolManager, times(1)).getStoragePool(vol.getPoolType(), vol.getPoolUuid()); } @@ -2300,7 +2302,7 @@ public void testPrimaryStorageDownloadCommandNOTemplateDisk() { final int index = url.lastIndexOf("/"); final String mountpoint = url.substring(0, index); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool); when(secondaryPool.listPhysicalDisks()).thenReturn(disks); when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool); @@ -2309,10 +2311,10 @@ public void testPrimaryStorageDownloadCommandNOTemplateDisk() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -2337,7 +2339,7 @@ public void testPrimaryStorageDownloadCommandNOTemplateNODisk() { final int index = url.lastIndexOf("/"); final String mountpoint = url.substring(0, index); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool); when(secondaryPool.listPhysicalDisks()).thenReturn(disks); when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool); @@ -2346,10 +2348,10 @@ public void testPrimaryStorageDownloadCommandNOTemplateNODisk() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -2375,7 +2377,7 @@ public void testPrimaryStorageDownloadCommandNOTemplateNOQcow2() { final int index = url.lastIndexOf("/"); final String mountpoint = url.substring(0, index); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool); when(secondaryPool.listPhysicalDisks()).thenReturn(spiedDisks); when(spiedDisks.isEmpty()).thenReturn(false); @@ -2386,10 +2388,10 @@ public void testPrimaryStorageDownloadCommandNOTemplateNOQcow2() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test(expected = NullPointerException.class) @@ -2412,7 +2414,7 @@ public void testPrimaryStorageDownloadCommandTemplateNoDisk() { final int index = url.lastIndexOf("/"); final String mountpoint = url.substring(0, index); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool); when(secondaryPool.getPhysicalDisk("template.qcow2")).thenReturn(tmplVol); when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool); @@ -2421,10 +2423,10 @@ public void testPrimaryStorageDownloadCommandTemplateNoDisk() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), command.getPoolUuid()); } @@ -2436,16 +2438,16 @@ public void testGetStorageStatsCommand() { final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class); final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(command.getPooltype(), command.getStorageId(), true)).thenReturn(secondaryPool); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePool(command.getPooltype(), command.getStorageId(), true); } @@ -2455,15 +2457,15 @@ public void testGetStorageStatsCommandException() { final DataStoreTO store = Mockito.mock(DataStoreTO.class); final GetStorageStatsCommand command = new GetStorageStatsCommand(store ); - when(libvirtComputingResource.getStoragePoolMgr()).thenThrow(CloudRuntimeException.class); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenThrow(CloudRuntimeException.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -2485,7 +2487,7 @@ public void testUpgradeSnapshotCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -2497,16 +2499,16 @@ public void testDeleteStoragePoolCommand() { final DeleteStoragePoolCommand command = new DeleteStoragePoolCommand(storagePool); final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.deleteStoragePool(pool.getType(), pool.getUuid())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).deleteStoragePool(pool.getType(), pool.getUuid()); } @@ -2519,16 +2521,16 @@ public void testDeleteStoragePoolCommandException() { final DeleteStoragePoolCommand command = new DeleteStoragePoolCommand(storagePool); final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.deleteStoragePool(pool.getType(), pool.getUuid())).thenThrow(CloudRuntimeException.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).deleteStoragePool(pool.getType(), pool.getUuid()); } @@ -2540,19 +2542,19 @@ public void testOvsSetupBridgeCommand() { final OvsSetupBridgeCommand command = new OvsSetupBridgeCommand(name, hostId, networkId); - when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true); - when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(), + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true); + when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getHostId(), command.getBridgeName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); - verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(), + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(), command.getBridgeName()); } @@ -2564,19 +2566,19 @@ public void testOvsSetupBridgeCommandFailure1() { final OvsSetupBridgeCommand command = new OvsSetupBridgeCommand(name, hostId, networkId); - when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true); - when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(), + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true); + when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getHostId(), command.getBridgeName())).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); - verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(), + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(), command.getBridgeName()); } @@ -2588,19 +2590,19 @@ public void testOvsSetupBridgeCommandFailure2() { final OvsSetupBridgeCommand command = new OvsSetupBridgeCommand(name, hostId, networkId); - when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(false); - when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(), + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(false); + when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getHostId(), command.getBridgeName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); - verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(), + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(), command.getBridgeName()); } @@ -2612,16 +2614,16 @@ public void testOvsDestroyBridgeCommand() { final OvsDestroyBridgeCommand command = new OvsDestroyBridgeCommand(networkId, name, hostId); - when(libvirtComputingResource.destroyTunnelNetwork(command.getBridgeName())).thenReturn(true); + when(libvirtComputingResourceMock.destroyTunnelNetwork(command.getBridgeName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).destroyTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).destroyTunnelNetwork(command.getBridgeName()); } @Test @@ -2632,16 +2634,16 @@ public void testOvsDestroyBridgeCommandFailure() { final OvsDestroyBridgeCommand command = new OvsDestroyBridgeCommand(networkId, name, hostId); - when(libvirtComputingResource.destroyTunnelNetwork(command.getBridgeName())).thenReturn(false); + when(libvirtComputingResourceMock.destroyTunnelNetwork(command.getBridgeName())).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).destroyTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).destroyTunnelNetwork(command.getBridgeName()); } @Test @@ -2653,7 +2655,7 @@ public void testOvsFetchInterfaceCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -2666,18 +2668,18 @@ public void testOvsVpcPhysicalTopologyConfigCommand() { final OvsVpcPhysicalTopologyConfigCommand command = new OvsVpcPhysicalTopologyConfigCommand(hosts, tiers, vms, cidr); - when(libvirtComputingResource.getOvsTunnelPath()).thenReturn("/path"); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getOvsTunnelPath()).thenReturn("/path"); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getOvsTunnelPath(); - verify(libvirtComputingResource, times(1)).getTimeout(); + verify(libvirtComputingResourceMock, times(1)).getOvsTunnelPath(); + verify(libvirtComputingResourceMock, times(1)).getTimeout(); } @SuppressWarnings("unchecked") @@ -2690,15 +2692,15 @@ public void testOvsVpcPhysicalTopologyConfigCommandFailure() { final OvsVpcPhysicalTopologyConfigCommand command = new OvsVpcPhysicalTopologyConfigCommand(hosts, tiers, vms, cidr); - when(libvirtComputingResource.getOvsTunnelPath()).thenThrow(Exception.class); + when(libvirtComputingResourceMock.getOvsTunnelPath()).thenThrow(Exception.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getOvsTunnelPath(); + verify(libvirtComputingResourceMock, times(1)).getOvsTunnelPath(); } @Test @@ -2710,18 +2712,18 @@ public void testOvsVpcRoutingPolicyConfigCommand() { final OvsVpcRoutingPolicyConfigCommand command = new OvsVpcRoutingPolicyConfigCommand(id, cidr, acls, tiers); - when(libvirtComputingResource.getOvsTunnelPath()).thenReturn("/path"); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getOvsTunnelPath()).thenReturn("/path"); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getOvsTunnelPath(); - verify(libvirtComputingResource, times(1)).getTimeout(); + verify(libvirtComputingResourceMock, times(1)).getOvsTunnelPath(); + verify(libvirtComputingResourceMock, times(1)).getTimeout(); } @SuppressWarnings("unchecked") @@ -2734,15 +2736,15 @@ public void testOvsVpcRoutingPolicyConfigCommandFailure() { final OvsVpcRoutingPolicyConfigCommand command = new OvsVpcRoutingPolicyConfigCommand(id, cidr, acls, tiers); - when(libvirtComputingResource.getOvsTunnelPath()).thenThrow(Exception.class); + when(libvirtComputingResourceMock.getOvsTunnelPath()).thenThrow(Exception.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getOvsTunnelPath(); + verify(libvirtComputingResourceMock, times(1)).getOvsTunnelPath(); } @Test @@ -2753,7 +2755,7 @@ public void testCreateStoragePoolCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -2766,7 +2768,7 @@ public void testModifyStoragePoolCommand() { final KVMStoragePool kvmStoragePool = Mockito.mock(KVMStoragePool.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool() .getUserInfo(), command.getPool().getType())).thenReturn(kvmStoragePool); @@ -2774,10 +2776,10 @@ public void testModifyStoragePoolCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool() .getUserInfo(), command.getPool().getType()); } @@ -2789,7 +2791,7 @@ public void testModifyStoragePoolCommandFailure() { final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool() .getUserInfo(), command.getPool().getType())).thenReturn(null); @@ -2797,10 +2799,10 @@ public void testModifyStoragePoolCommandFailure() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool() .getUserInfo(), command.getPool().getType()); } @@ -2809,15 +2811,15 @@ public void testModifyStoragePoolCommandFailure() { public void testCleanupNetworkRulesCmd() { final CleanupNetworkRulesCmd command = new CleanupNetworkRulesCmd(1); - when(libvirtComputingResource.cleanupRules()).thenReturn(true); + when(libvirtComputingResourceMock.cleanupRules()).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).cleanupRules(); + verify(libvirtComputingResourceMock, times(1)).cleanupRules(); } @Test @@ -2832,18 +2834,18 @@ public void testNetworkRulesVmSecondaryIpCommand() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); final Connect conn = Mockito.mock(Connect.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); } catch (final LibvirtException e) { fail(e.getMessage()); } - when(libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmMac(), command.getVmSecIp(), command.getAction())).thenReturn(true); + when(libvirtComputingResourceMock.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmMac(), command.getVmSecIp(), command.getAction())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); try { @@ -2851,8 +2853,8 @@ public void testNetworkRulesVmSecondaryIpCommand() { } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); - verify(libvirtComputingResource, times(1)).configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmMac(), command.getVmSecIp(), command.getAction()); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmMac(), command.getVmSecIp(), command.getAction()); } @SuppressWarnings("unchecked") @@ -2867,7 +2869,7 @@ public void testNetworkRulesVmSecondaryIpCommandFailure() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -2876,7 +2878,7 @@ public void testNetworkRulesVmSecondaryIpCommandFailure() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); try { @@ -2884,7 +2886,7 @@ public void testNetworkRulesVmSecondaryIpCommandFailure() { } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); } @Test @@ -2897,18 +2899,18 @@ public void testNetworkRulesSystemVmCommand() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); final Connect conn = Mockito.mock(Connect.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); } catch (final LibvirtException e) { fail(e.getMessage()); } - when(libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, command.getVmName())).thenReturn(true); + when(libvirtComputingResourceMock.configureDefaultNetworkRulesForSystemVm(conn, command.getVmName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); try { @@ -2916,8 +2918,8 @@ public void testNetworkRulesSystemVmCommand() { } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); - verify(libvirtComputingResource, times(1)).configureDefaultNetworkRulesForSystemVm(conn, command.getVmName()); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).configureDefaultNetworkRulesForSystemVm(conn, command.getVmName()); } @SuppressWarnings("unchecked") @@ -2930,7 +2932,7 @@ public void testNetworkRulesSystemVmCommandFailure() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -2940,7 +2942,7 @@ public void testNetworkRulesSystemVmCommandFailure() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); try { @@ -2948,7 +2950,7 @@ public void testNetworkRulesSystemVmCommandFailure() { } catch (final LibvirtException e) { fail(e.getMessage()); } - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); } @Test @@ -2964,16 +2966,16 @@ public void testCheckSshCommand() { final String privateIp = command.getIp(); final int cmdPort = command.getPort(); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(virtRouterResource); when(virtRouterResource.connect(privateIp, cmdPort)).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getVirtRouterResource(); + verify(libvirtComputingResourceMock, times(1)).getVirtRouterResource(); verify(virtRouterResource, times(1)).connect(privateIp, cmdPort); } @@ -2990,16 +2992,16 @@ public void testCheckSshCommandFailure() { final String privateIp = command.getIp(); final int cmdPort = command.getPort(); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(virtRouterResource); when(virtRouterResource.connect(privateIp, cmdPort)).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getVirtRouterResource(); + verify(libvirtComputingResourceMock, times(1)).getVirtRouterResource(); verify(virtRouterResource, times(1)).connect(privateIp, cmdPort); } @@ -3012,19 +3014,19 @@ public void testCheckNetworkCommand() { final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList); - when(libvirtComputingResource.checkNetwork(TrafficType.Guest, nic.getGuestNetworkName())).thenReturn(true); - when(libvirtComputingResource.checkNetwork(TrafficType.Management, nic.getPrivateNetworkName())).thenReturn(true); - when(libvirtComputingResource.checkNetwork(TrafficType.Public, nic.getPublicNetworkName())).thenReturn(true); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Guest, nic.getGuestNetworkName())).thenReturn(true); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Management, nic.getPrivateNetworkName())).thenReturn(true); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Public, nic.getPublicNetworkName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Guest, nic.getGuestNetworkName()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Management, nic.getPrivateNetworkName()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Public, nic.getPublicNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Guest, nic.getGuestNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Management, nic.getPrivateNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Public, nic.getPublicNetworkName()); } @Test @@ -3036,15 +3038,15 @@ public void testCheckNetworkCommandFail1() { final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList); - when(libvirtComputingResource.checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName())).thenReturn(false); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName())).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName()); } @Test @@ -3056,17 +3058,17 @@ public void testCheckNetworkCommandFail2() { final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList); - when(libvirtComputingResource.checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName())).thenReturn(true); - when(libvirtComputingResource.checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName())).thenReturn(false); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName())).thenReturn(true); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName())).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName()); } @Test @@ -3078,18 +3080,18 @@ public void testCheckNetworkCommandFail3() { final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList); - when(libvirtComputingResource.checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName())).thenReturn(true); - when(libvirtComputingResource.checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName())).thenReturn(true); - when(libvirtComputingResource.checkNetwork(TrafficType.Public, networkSetupInfo.getPublicNetworkName())).thenReturn(false); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName())).thenReturn(true); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName())).thenReturn(true); + when(libvirtComputingResourceMock.checkNetwork(TrafficType.Public, networkSetupInfo.getPublicNetworkName())).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName()); - verify(libvirtComputingResource, times(1)).checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Guest, networkSetupInfo.getGuestNetworkName()); + verify(libvirtComputingResourceMock, times(1)).checkNetwork(TrafficType.Management, networkSetupInfo.getPrivateNetworkName()); } @Test @@ -3100,15 +3102,15 @@ public void testOvsDestroyTunnelCommand() { final OvsDestroyTunnelCommand command = new OvsDestroyTunnelCommand(networkId, networkName, inPortName); - when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true); + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); } @Test @@ -3119,15 +3121,15 @@ public void testOvsDestroyTunnelCommandFailure1() { final OvsDestroyTunnelCommand command = new OvsDestroyTunnelCommand(networkId, networkName, inPortName); - when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(false); + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(false); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); } @SuppressWarnings("unchecked") @@ -3139,15 +3141,15 @@ public void testOvsDestroyTunnelCommandFailure2() { final OvsDestroyTunnelCommand command = new OvsDestroyTunnelCommand(networkId, networkName, inPortName); - when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenThrow(Exception.class); + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(command.getBridgeName())).thenThrow(Exception.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(command.getBridgeName()); } @Test @@ -3158,15 +3160,15 @@ public void testCheckOnHostCommand() { final KVMHAMonitor monitor = Mockito.mock(KVMHAMonitor.class); - when(libvirtComputingResource.getMonitor()).thenReturn(monitor); + when(libvirtComputingResourceMock.getMonitor()).thenReturn(monitor); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getMonitor(); + verify(libvirtComputingResourceMock, times(1)).getMonitor(); } @Test @@ -3184,19 +3186,19 @@ public void testOvsCreateTunnelCommand() { final String bridge = command.getNetworkName(); - when(libvirtComputingResource.findOrCreateTunnelNetwork(bridge)).thenReturn(true); - when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(bridge)).thenReturn(true); + when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName())).thenReturn(true); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(bridge); - verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(), + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(bridge); + verify(libvirtComputingResourceMock, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName()); } @@ -3215,18 +3217,18 @@ public void testOvsCreateTunnelCommandFailure1() { final String bridge = command.getNetworkName(); - when(libvirtComputingResource.findOrCreateTunnelNetwork(bridge)).thenReturn(false); - when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(bridge)).thenReturn(false); + when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(bridge); - verify(libvirtComputingResource, times(0)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(), + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(bridge); + verify(libvirtComputingResourceMock, times(0)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName()); } @@ -3246,18 +3248,18 @@ public void testOvsCreateTunnelCommandFailure2() { final String bridge = command.getNetworkName(); - when(libvirtComputingResource.findOrCreateTunnelNetwork(bridge)).thenReturn(true); - when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), + when(libvirtComputingResourceMock.findOrCreateTunnelNetwork(bridge)).thenReturn(true); + when(libvirtComputingResourceMock.configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName())).thenThrow(Exception.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(bridge); - verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(), + verify(libvirtComputingResourceMock, times(1)).findOrCreateTunnelNetwork(bridge); + verify(libvirtComputingResourceMock, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(), command.getNetworkName()); } @@ -3287,7 +3289,7 @@ public void testCreateVolumeFromSnapshotCommand() { final String primaryUuid = command.getPrimaryStoragePoolNameLabel(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(secondaryPool); when(secondaryPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot); when(storagePoolMgr.getStoragePool(command.getPool().getType(), primaryUuid)).thenReturn(primaryPool); @@ -3297,10 +3299,10 @@ public void testCreateVolumeFromSnapshotCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(secondaryPool, times(1)).getPhysicalDisk(command.getSnapshotName()); verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), primaryUuid); @@ -3331,7 +3333,7 @@ public void testCreateVolumeFromSnapshotCommandCloudException() { final String primaryUuid = command.getPrimaryStoragePoolNameLabel(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(secondaryPool); when(secondaryPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot); when(storagePoolMgr.getStoragePool(command.getPool().getType(), primaryUuid)).thenThrow(CloudRuntimeException.class); @@ -3339,10 +3341,10 @@ public void testCreateVolumeFromSnapshotCommandCloudException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(secondaryPool, times(1)).getPhysicalDisk(command.getSnapshotName()); verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), primaryUuid); @@ -3361,16 +3363,16 @@ public void testFenceCommand() { final List pools = new ArrayList(); pools.add(storagePool); - when(libvirtComputingResource.getMonitor()).thenReturn(monitor); + when(libvirtComputingResourceMock.getMonitor()).thenReturn(monitor); when(monitor.getStoragePools()).thenReturn(pools); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getMonitor(); + verify(libvirtComputingResourceMock, times(1)).getMonitor(); verify(monitor, times(1)).getStoragePools(); } @@ -3398,8 +3400,8 @@ public void testSecurityGroupRulesCmdFalse() { final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class); nics.add(interfaceDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -3419,10 +3421,10 @@ public void testSecurityGroupRulesCmdFalse() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -3456,8 +3458,8 @@ public void testSecurityGroupRulesCmdTrue() { final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class); nics.add(interfaceDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); } catch (final LibvirtException e) { @@ -3480,17 +3482,17 @@ public void testSecurityGroupRulesCmdTrue() { when(egressRuleSet[0].getEndPort()).thenReturn(22); when(egressRuleSet[0].getAllowedCidrs()).thenReturn(cidrs); - when(libvirtComputingResource.applyDefaultNetworkRules(conn, vm, true)).thenReturn(true); - when(libvirtComputingResource.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getGuestIp6(), command.getSignature(), + when(libvirtComputingResourceMock.applyDefaultNetworkRules(conn, vm, true)).thenReturn(true); + when(libvirtComputingResourceMock.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getGuestIp6(), command.getSignature(), Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString())).thenReturn(true); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -3521,8 +3523,8 @@ public void testSecurityGroupRulesCmdException() { final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class); nics.add(interfaceDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -3532,10 +3534,10 @@ public void testSecurityGroupRulesCmdException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -3559,8 +3561,8 @@ public void testPlugNicCommandMatchMack() { final InterfaceDef intDef = Mockito.mock(InterfaceDef.class); nics.add(intDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); when(intDef.getDevName()).thenReturn("eth0"); when(intDef.getBrName()).thenReturn("br0"); @@ -3570,7 +3572,7 @@ public void testPlugNicCommandMatchMack() { try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); - when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm); + when(libvirtComputingResourceMock.getDomain(conn, instanceName)).thenReturn(vm); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -3578,13 +3580,13 @@ public void testPlugNicCommandMatchMack() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); - verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName); + verify(libvirtComputingResourceMock, times(1)).getDomain(conn, instanceName); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -3608,8 +3610,8 @@ public void testPlugNicCommandNoMatchMack() { final InterfaceDef intDef = Mockito.mock(InterfaceDef.class); nics.add(intDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); when(intDef.getDevName()).thenReturn("eth0"); when(intDef.getBrName()).thenReturn("br0"); @@ -3620,9 +3622,9 @@ public void testPlugNicCommandNoMatchMack() { try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); - when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm); + when(libvirtComputingResourceMock.getDomain(conn, instanceName)).thenReturn(vm); - when(libvirtComputingResource.getVifDriver(nic.getType(), nic.getName())).thenReturn(vifDriver); + when(libvirtComputingResourceMock.getVifDriver(nic.getType(), nic.getName())).thenReturn(vifDriver); when(vifDriver.plug(nic, "Other PV", "", null)).thenReturn(interfaceDef); when(interfaceDef.toString()).thenReturn("Interface"); @@ -3639,14 +3641,14 @@ public void testPlugNicCommandNoMatchMack() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); - verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName); - verify(libvirtComputingResource, times(1)).getVifDriver(nic.getType(), nic.getName()); + verify(libvirtComputingResourceMock, times(1)).getDomain(conn, instanceName); + verify(libvirtComputingResourceMock, times(1)).getVifDriver(nic.getType(), nic.getName()); verify(vifDriver, times(1)).plug(nic, "Other PV", "", null); } catch (final LibvirtException e) { fail(e.getMessage()); @@ -3666,7 +3668,7 @@ public void testPlugNicCommandLibvirtException() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); @@ -3677,10 +3679,10 @@ public void testPlugNicCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -3706,8 +3708,8 @@ public void testPlugNicCommandInternalError() { final InterfaceDef intDef = Mockito.mock(InterfaceDef.class); nics.add(intDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); when(intDef.getDevName()).thenReturn("eth0"); when(intDef.getBrName()).thenReturn("br0"); @@ -3717,9 +3719,9 @@ public void testPlugNicCommandInternalError() { try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); - when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm); + when(libvirtComputingResourceMock.getDomain(conn, instanceName)).thenReturn(vm); - when(libvirtComputingResource.getVifDriver(nic.getType(), nic.getName())).thenReturn(vifDriver); + when(libvirtComputingResourceMock.getVifDriver(nic.getType(), nic.getName())).thenReturn(vifDriver); when(vifDriver.plug(nic, "Other PV", "", null)).thenThrow(InternalErrorException.class); @@ -3732,14 +3734,14 @@ public void testPlugNicCommandInternalError() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); - verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName); - verify(libvirtComputingResource, times(1)).getVifDriver(nic.getType(), nic.getName()); + verify(libvirtComputingResourceMock, times(1)).getDomain(conn, instanceName); + verify(libvirtComputingResourceMock, times(1)).getVifDriver(nic.getType(), nic.getName()); verify(vifDriver, times(1)).plug(nic, "Other PV", "", null); } catch (final LibvirtException e) { fail(e.getMessage()); @@ -3768,8 +3770,8 @@ public void testUnPlugNicCommandMatchMack() { final List drivers = new ArrayList(); drivers.add(vifDriver); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); when(intDef.getDevName()).thenReturn("eth0"); when(intDef.getBrName()).thenReturn("br0"); @@ -3779,14 +3781,14 @@ public void testUnPlugNicCommandMatchMack() { try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); - when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm); + when(libvirtComputingResourceMock.getDomain(conn, instanceName)).thenReturn(vm); when(interfaceDef.toString()).thenReturn("Interface"); final String interfaceDefStr = interfaceDef.toString(); doNothing().when(vm).detachDevice(interfaceDefStr); - when(libvirtComputingResource.getAllVifDrivers()).thenReturn(drivers); + when(libvirtComputingResourceMock.getAllVifDrivers()).thenReturn(drivers); doNothing().when(vifDriver).unplug(intDef, true); @@ -3797,14 +3799,14 @@ public void testUnPlugNicCommandMatchMack() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); - verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName); - verify(libvirtComputingResource, times(1)).getAllVifDrivers(); + verify(libvirtComputingResourceMock, times(1)).getDomain(conn, instanceName); + verify(libvirtComputingResourceMock, times(1)).getAllVifDrivers(); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -3827,12 +3829,12 @@ public void testUnPlugNicCommandNoNics() { final List drivers = new ArrayList(); drivers.add(vifDriver); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getInterfaces(conn, command.getVmName())).thenReturn(nics); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn); - when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm); + when(libvirtComputingResourceMock.getDomain(conn, instanceName)).thenReturn(vm); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -3840,13 +3842,13 @@ public void testUnPlugNicCommandNoNics() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); - verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName); + verify(libvirtComputingResourceMock, times(1)).getDomain(conn, instanceName); } catch (final LibvirtException e) { fail(e.getMessage()); } @@ -3862,7 +3864,7 @@ public void testUnPlugNicCommandLibvirtException() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); @@ -3873,10 +3875,10 @@ public void testUnPlugNicCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -3893,18 +3895,18 @@ public void testNetworkUsageCommandNonVpc() { final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, forVpc, gatewayIP); - libvirtComputingResource.getNetworkStats(command.getPrivateIP()); + libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP()); - when(libvirtComputingResource.getNetworkStats(command.getPrivateIP())).thenReturn(new long[]{10l, 10l}); + when(libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP())).thenReturn(new long[]{10l, 10l}); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); //Being called twice, although I did not find the second place yet. - verify(libvirtComputingResource, times(2)).getNetworkStats(command.getPrivateIP()); + verify(libvirtComputingResourceMock, times(2)).getNetworkStats(command.getPrivateIP()); } @Test @@ -3915,17 +3917,17 @@ public void testNetworkUsageCommandNonVpcCreate() { final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, "create", forVpc); - libvirtComputingResource.getNetworkStats(command.getPrivateIP()); + libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP()); - when(libvirtComputingResource.networkUsage(command.getPrivateIP(), "create", null)).thenReturn("SUCCESS"); + when(libvirtComputingResourceMock.networkUsage(command.getPrivateIP(), "create", null)).thenReturn("SUCCESS"); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).networkUsage(command.getPrivateIP(), "create", null); + verify(libvirtComputingResourceMock, times(1)).networkUsage(command.getPrivateIP(), "create", null); } @Test @@ -3938,17 +3940,17 @@ public void testNetworkUsageCommandVpcCreate() { final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, forVpc, gatewayIP, vpcCidr); - libvirtComputingResource.getNetworkStats(command.getPrivateIP()); + libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP()); - when(libvirtComputingResource.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR())).thenReturn("SUCCESS"); + when(libvirtComputingResourceMock.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR())).thenReturn("SUCCESS"); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR()); + verify(libvirtComputingResourceMock, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR()); } @Test @@ -3960,17 +3962,17 @@ public void testNetworkUsageCommandVpcGet() { final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, forVpc, gatewayIP); - libvirtComputingResource.getNetworkStats(command.getPrivateIP()); + libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP()); - when(libvirtComputingResource.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption())).thenReturn(new long[]{10l, 10l}); + when(libvirtComputingResourceMock.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption())).thenReturn(new long[]{10l, 10l}); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption()); + verify(libvirtComputingResourceMock, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption()); } @Test @@ -3982,17 +3984,17 @@ public void testNetworkUsageCommandVpcVpn() { final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, "vpn", forVpc, gatewayIP); - libvirtComputingResource.getNetworkStats(command.getPrivateIP()); + libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP()); - when(libvirtComputingResource.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption())).thenReturn(new long[]{10l, 10l}); + when(libvirtComputingResourceMock.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption())).thenReturn(new long[]{10l, 10l}); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption()); + verify(libvirtComputingResourceMock, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption()); } @Test @@ -4004,17 +4006,17 @@ public void testNetworkUsageCommandVpcNoOption() { final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, null, forVpc, gatewayIP); - libvirtComputingResource.getNetworkStats(command.getPrivateIP()); + libvirtComputingResourceMock.getNetworkStats(command.getPrivateIP()); - when(libvirtComputingResource.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR())).thenReturn("FAILURE"); + when(libvirtComputingResourceMock.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR())).thenReturn("FAILURE"); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR()); + verify(libvirtComputingResourceMock, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR()); } @Test @@ -4038,17 +4040,17 @@ public void testCreatePrivateTemplateFromVolumeCommand() { final KVMStoragePool secondaryStorage = Mockito.mock(KVMStoragePool.class); //final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl)).thenReturn(secondaryStorage); when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel())).thenThrow(new CloudRuntimeException("error")); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(secondaryStorageUrl); verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel()); } @@ -4072,7 +4074,7 @@ public void testManageSnapshotCommandLibvirtException() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); //final Connect conn = Mockito.mock(Connect.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); @@ -4083,10 +4085,10 @@ public void testManageSnapshotCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -4118,16 +4120,16 @@ public void testManageSnapshotCommandLibvirt() { final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn); - when(libvirtComputingResource.getDomain(conn, command.getVmName())).thenReturn(vm); + when(libvirtComputingResourceMock.getDomain(conn, command.getVmName())).thenReturn(vm); when(vm.getInfo()).thenReturn(info); } catch (final LibvirtException e) { fail(e.getMessage()); } - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primaryPool); when(primaryPool.getPhysicalDisk(command.getVolumePath())).thenReturn(disk); when(primaryPool.isExternalSnapshot()).thenReturn(false); @@ -4141,11 +4143,11 @@ public void testManageSnapshotCommandLibvirt() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName); } catch (final LibvirtException e) { @@ -4182,7 +4184,7 @@ public void testBackupSnapshotCommandLibvirtException() { final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); //final Connect conn = Mockito.mock(Connect.class); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class); @@ -4193,10 +4195,10 @@ public void testBackupSnapshotCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName()); } catch (final LibvirtException e) { @@ -4234,7 +4236,7 @@ public void testCreatePrivateTemplateFromSnapshotCommand() { final Processor qcow2Processor = Mockito.mock(Processor.class); final FormatInfo info = Mockito.mock(FormatInfo.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); String snapshotPath = command.getSnapshotUuid(); final int index = snapshotPath.lastIndexOf("/"); @@ -4244,16 +4246,16 @@ public void testCreatePrivateTemplateFromSnapshotCommand() { when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool); when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot); when(secondaryPool.getLocalPath()).thenReturn(localPath); - when(libvirtComputingResource.getStorage()).thenReturn(storage); + when(libvirtComputingResourceMock.getStorage()).thenReturn(storage); - when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath); - when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1); + when(libvirtComputingResourceMock.createTmplPath()).thenReturn(templatePath); + when(libvirtComputingResourceMock.getCmdsTimeout()).thenReturn(1); final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId(); final String templateInstallFolder = "template/tmpl/" + templateFolder; final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder; - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName); @@ -4269,10 +4271,10 @@ public void testCreatePrivateTemplateFromSnapshotCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl()); } @@ -4308,7 +4310,7 @@ public void testCreatePrivateTemplateFromSnapshotCommandConfigurationException() final Processor qcow2Processor = Mockito.mock(Processor.class); final FormatInfo info = Mockito.mock(FormatInfo.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); String snapshotPath = command.getSnapshotUuid(); final int index = snapshotPath.lastIndexOf("/"); @@ -4318,16 +4320,16 @@ public void testCreatePrivateTemplateFromSnapshotCommandConfigurationException() when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool); when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot); when(secondaryPool.getLocalPath()).thenReturn(localPath); - when(libvirtComputingResource.getStorage()).thenReturn(storage); + when(libvirtComputingResourceMock.getStorage()).thenReturn(storage); - when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath); - when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1); + when(libvirtComputingResourceMock.createTmplPath()).thenReturn(templatePath); + when(libvirtComputingResourceMock.getCmdsTimeout()).thenReturn(1); final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId(); final String templateInstallFolder = "template/tmpl/" + templateFolder; final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder; - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName); @@ -4343,10 +4345,10 @@ public void testCreatePrivateTemplateFromSnapshotCommandConfigurationException() final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl()); } @@ -4381,7 +4383,7 @@ public void testCreatePrivateTemplateFromSnapshotCommandInternalErrorException() final TemplateLocation location = Mockito.mock(TemplateLocation.class); final Processor qcow2Processor = Mockito.mock(Processor.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); String snapshotPath = command.getSnapshotUuid(); final int index = snapshotPath.lastIndexOf("/"); @@ -4391,16 +4393,16 @@ public void testCreatePrivateTemplateFromSnapshotCommandInternalErrorException() when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool); when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot); when(secondaryPool.getLocalPath()).thenReturn(localPath); - when(libvirtComputingResource.getStorage()).thenReturn(storage); + when(libvirtComputingResourceMock.getStorage()).thenReturn(storage); - when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath); - when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1); + when(libvirtComputingResourceMock.createTmplPath()).thenReturn(templatePath); + when(libvirtComputingResourceMock.getCmdsTimeout()).thenReturn(1); final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId(); final String templateInstallFolder = "template/tmpl/" + templateFolder; final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder; - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName); @@ -4416,10 +4418,10 @@ public void testCreatePrivateTemplateFromSnapshotCommandInternalErrorException() final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl()); } @@ -4455,7 +4457,7 @@ public void testCreatePrivateTemplateFromSnapshotCommandIOException() { final Processor qcow2Processor = Mockito.mock(Processor.class); final FormatInfo info = Mockito.mock(FormatInfo.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); String snapshotPath = command.getSnapshotUuid(); final int index = snapshotPath.lastIndexOf("/"); @@ -4465,16 +4467,16 @@ public void testCreatePrivateTemplateFromSnapshotCommandIOException() { when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool); when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot); when(secondaryPool.getLocalPath()).thenReturn(localPath); - when(libvirtComputingResource.getStorage()).thenReturn(storage); + when(libvirtComputingResourceMock.getStorage()).thenReturn(storage); - when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath); - when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1); + when(libvirtComputingResourceMock.createTmplPath()).thenReturn(templatePath); + when(libvirtComputingResourceMock.getCmdsTimeout()).thenReturn(1); final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId(); final String templateInstallFolder = "template/tmpl/" + templateFolder; final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder; - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName); @@ -4495,10 +4497,10 @@ public void testCreatePrivateTemplateFromSnapshotCommandIOException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl()); } @@ -4527,13 +4529,13 @@ public void testCreatePrivateTemplateFromSnapshotCommandCloudRuntime() { final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); String snapshotPath = command.getSnapshotUuid(); final int index = snapshotPath.lastIndexOf("/"); snapshotPath = snapshotPath.substring(0, index); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName); when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool); @@ -4543,10 +4545,10 @@ public void testCreatePrivateTemplateFromSnapshotCommandCloudRuntime() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath); verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl()); } @@ -4575,10 +4577,10 @@ public void testCopyVolumeCommand() { final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(destVolumeName); when(primary.getPhysicalDisk(command.getVolumePath())).thenReturn(disk); when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL)).thenReturn(secondary); @@ -4592,10 +4594,10 @@ public void testCopyVolumeCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -4622,9 +4624,9 @@ public void testCopyVolumeCommandToSecFalse() { final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(destVolumeName); when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS); when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6"); @@ -4635,10 +4637,10 @@ public void testCopyVolumeCommandToSecFalse() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @SuppressWarnings("unchecked") @@ -4665,9 +4667,9 @@ public void testCopyVolumeCommandCloudRuntime() { final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(destVolumeName); when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS); when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6"); @@ -4677,10 +4679,10 @@ public void testCopyVolumeCommandCloudRuntime() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -4699,16 +4701,16 @@ public void testCopyVolumeCommandCloudRuntime2() { final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenThrow(new CloudRuntimeException("error")); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -4735,13 +4737,13 @@ public void testCopyVolumeCommandPrimaryNotFound() { final StorageFilerTO pool = command.getPool(); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenThrow(new CloudRuntimeException("not found")); when(storagePoolMgr.createStoragePool(pool.getUuid(), pool.getHost(), pool.getPort(), pool.getPath(), pool.getUserInfo(), pool.getType())).thenReturn(primary); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(destVolumeName); when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS); when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6"); @@ -4752,10 +4754,10 @@ public void testCopyVolumeCommandPrimaryNotFound() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -4770,16 +4772,16 @@ public void testPvlanSetupCommandDhcpAdd() { final PvlanSetupCommand command = PvlanSetupCommand.createDhcpSetup(op, uri, networkTag, dhcpName, dhcpMac, dhcpIp); final String guestBridgeName = "br0"; - when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getGuestBridgeName()).thenReturn(guestBridgeName); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final String ovsPvlanDhcpHostPath = "/pvlan"; - when(libvirtComputingResource.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath); + when(libvirtComputingResourceMock.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -4793,16 +4795,16 @@ public void testPvlanSetupCommandVm() { final PvlanSetupCommand command = PvlanSetupCommand.createVmSetup(op, uri, networkTag, vmMac); final String guestBridgeName = "br0"; - when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getGuestBridgeName()).thenReturn(guestBridgeName); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final String ovsPvlanVmPath = "/pvlan"; - when(libvirtComputingResource.getOvsPvlanVmPath()).thenReturn(ovsPvlanVmPath); + when(libvirtComputingResourceMock.getOvsPvlanVmPath()).thenReturn(ovsPvlanVmPath); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -4818,16 +4820,16 @@ public void testPvlanSetupCommandDhcpDelete() { final PvlanSetupCommand command = PvlanSetupCommand.createDhcpSetup(op, uri, networkTag, dhcpName, dhcpMac, dhcpIp); final String guestBridgeName = "br0"; - when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName); - when(libvirtComputingResource.getTimeout()).thenReturn(Duration.ZERO); + when(libvirtComputingResourceMock.getGuestBridgeName()).thenReturn(guestBridgeName); + when(libvirtComputingResourceMock.getTimeout()).thenReturn(Duration.ZERO); final String ovsPvlanDhcpHostPath = "/pvlan"; - when(libvirtComputingResource.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath); + when(libvirtComputingResourceMock.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -4849,15 +4851,15 @@ public void testResizeVolumeCommand() { final Connect conn = Mockito.mock(Connect.class); final StorageVol v = Mockito.mock(StorageVol.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool); when(storagePool.getPhysicalDisk(path)).thenReturn(vol); when(vol.getPath()).thenReturn(path); - when(libvirtComputingResource.getResizeScriptType(storagePool, vol)).thenReturn("FILE"); + when(libvirtComputingResourceMock.getResizeScriptType(storagePool, vol)).thenReturn("FILE"); when(storagePool.getType()).thenReturn(StoragePoolType.RBD); when(vol.getFormat()).thenReturn(PhysicalDiskFormat.FILE); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnection()).thenReturn(conn); when(conn.storageVolLookupByPath(path)).thenReturn(v); @@ -4871,12 +4873,12 @@ public void testResizeVolumeCommand() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnection(); } catch (final LibvirtException e) { @@ -4900,7 +4902,7 @@ public void testResizeVolumeCommandLinstorNotifyOnly() { final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class); final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool); when(storagePool.getPhysicalDisk(path)).thenReturn(vol); when(vol.getPath()).thenReturn(path); @@ -4910,13 +4912,13 @@ public void testResizeVolumeCommandLinstorNotifyOnly() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(0)).getResizeScriptType(storagePool, vol); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(0)).getResizeScriptType(storagePool, vol); - verify(libvirtComputingResource, times(0)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(0)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(0)).getConnection(); } catch (final LibvirtException e) { @@ -4938,7 +4940,7 @@ public void testResizeVolumeCommandSameSize() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -4957,16 +4959,16 @@ public void testResizeVolumeCommandShrink() { final KVMStoragePool storagePool = Mockito.mock(KVMStoragePool.class); final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool); when(storagePool.getPhysicalDisk(path)).thenReturn(vol); when(vol.getPath()).thenReturn(path); - when(libvirtComputingResource.getResizeScriptType(storagePool, vol)).thenReturn("QCOW2"); + when(libvirtComputingResourceMock.getResizeScriptType(storagePool, vol)).thenReturn("QCOW2"); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -4987,15 +4989,15 @@ public void testResizeVolumeCommandException() { final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class); final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool); when(storagePool.getPhysicalDisk(path)).thenReturn(vol); when(vol.getPath()).thenReturn(path); - when(libvirtComputingResource.getResizeScriptType(storagePool, vol)).thenReturn("FILE"); + when(libvirtComputingResourceMock.getResizeScriptType(storagePool, vol)).thenReturn("FILE"); when(storagePool.getType()).thenReturn(StoragePoolType.RBD); when(vol.getFormat()).thenReturn(PhysicalDiskFormat.FILE); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnection()).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -5005,12 +5007,12 @@ public void testResizeVolumeCommandException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnection(); } catch (final LibvirtException e) { @@ -5033,17 +5035,17 @@ public void testResizeVolumeCommandException2() { final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class); final KVMStoragePool storagePool = Mockito.mock(KVMStoragePool.class); - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool); when(storagePool.getPhysicalDisk(path)).thenThrow(CloudRuntimeException.class); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); } @Test @@ -5051,14 +5053,14 @@ public void testNetworkElementCommand() { final CheckRouterCommand command = new CheckRouterCommand(); final VirtualRoutingResource virtRouterResource = Mockito.mock(VirtualRoutingResource.class); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(virtRouterResource); when(virtRouterResource.executeRequest(command)).thenReturn(new CheckRouterAnswer(command, "mock_resource")); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -5069,14 +5071,14 @@ public void testStorageSubSystemCommand() { final AttachCommand command = new AttachCommand(disk, vmName); final StorageSubsystemCommandHandler handler = Mockito.mock(StorageSubsystemCommandHandler.class); - when(libvirtComputingResource.getStorageHandler()).thenReturn(handler); + when(libvirtComputingResourceMock.getStorageHandler()).thenReturn(handler); when(handler.handleStorageCommands(command)).thenReturn(new AttachAnswer(disk)); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -5098,16 +5100,16 @@ public void testStartCommandFailedConnect() { final String vmName = "Test"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter); when(vmSpec.getName()).thenReturn(vmName); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn); - doNothing().when(libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef); + doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final InternalErrorException e) { @@ -5121,11 +5123,11 @@ public void testStartCommandFailedConnect() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType()); } catch (final LibvirtException e) { @@ -5151,13 +5153,13 @@ public void testStartCommandLibvirtException() { final String vmName = "Test"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter); when(vmSpec.getName()).thenReturn(vmName); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenThrow(LibvirtException.class); } catch (final LibvirtException e) { @@ -5167,11 +5169,11 @@ public void testStartCommandLibvirtException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType()); } catch (final LibvirtException e) { @@ -5197,16 +5199,16 @@ public void testStartCommandInternalError() { final String vmName = "Test"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter); when(vmSpec.getName()).thenReturn(vmName); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn); - doThrow(InternalErrorException.class).when(libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef); + doThrow(InternalErrorException.class).when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final InternalErrorException e) { @@ -5218,11 +5220,11 @@ public void testStartCommandInternalError() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType()); } catch (final LibvirtException e) { @@ -5248,16 +5250,16 @@ public void testStartCommandUriException() { final String vmName = "Test"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter); when(vmSpec.getName()).thenReturn(vmName); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn); - doThrow(URISyntaxException.class).when(libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef); + doThrow(URISyntaxException.class).when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final InternalErrorException e) { @@ -5269,11 +5271,11 @@ public void testStartCommandUriException() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType()); } catch (final LibvirtException e) { @@ -5304,17 +5306,17 @@ public void testStartCommand() throws Exception { final String vmName = "Test"; final String controlIp = "127.0.0.1"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter); when(vmSpec.getName()).thenReturn(vmName); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn); when(conn.listDomains()).thenReturn(vms); - doNothing().when(libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef); + doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final InternalErrorException e) { @@ -5325,16 +5327,16 @@ public void testStartCommand() throws Exception { when(storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)).thenReturn(true); try { - doNothing().when(libvirtComputingResource).createVifs(vmSpec, vmDef); + doNothing().when(libvirtComputingResourceMock).createVifs(vmSpec, vmDef); - when(libvirtComputingResource.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS"); + when(libvirtComputingResourceMock.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS"); when(vmSpec.getBootArgs()).thenReturn("ls -lart"); - when(libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true); + when(libvirtComputingResourceMock.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true); when(nic.getIp()).thenReturn(controlIp); when(nic.getType()).thenReturn(TrafficType.Control); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(virtRouterResource); when(virtRouterResource.connect(controlIp, 1, 5000)).thenReturn(true); when(virtRouterResource.isSystemVMSetup(vmName, controlIp)).thenReturn(true); } catch (final InternalErrorException e) { @@ -5346,11 +5348,11 @@ public void testStartCommand() throws Exception { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType()); } catch (final LibvirtException e) { @@ -5381,17 +5383,17 @@ public void testStartCommandIsolationEc2() throws Exception { final String vmName = "Test"; final String controlIp = "127.0.0.1"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter); when(vmSpec.getName()).thenReturn(vmName); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn); when(conn.listDomains()).thenReturn(vms); - doNothing().when(libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef); + doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final InternalErrorException e) { @@ -5402,20 +5404,20 @@ public void testStartCommandIsolationEc2() throws Exception { when(storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)).thenReturn(true); try { - doNothing().when(libvirtComputingResource).createVifs(vmSpec, vmDef); + doNothing().when(libvirtComputingResourceMock).createVifs(vmSpec, vmDef); - when(libvirtComputingResource.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS"); + when(libvirtComputingResourceMock.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS"); when(nic.isSecurityGroupEnabled()).thenReturn(true); when(nic.getIsolationUri()).thenReturn(new URI("ec2://test")); when(vmSpec.getBootArgs()).thenReturn("ls -lart"); - when(libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true); + when(libvirtComputingResourceMock.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true); when(nic.getIp()).thenReturn(controlIp); when(nic.getType()).thenReturn(TrafficType.Control); - when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource); + when(libvirtComputingResourceMock.getVirtRouterResource()).thenReturn(virtRouterResource); when(virtRouterResource.connect(controlIp, 1, 5000)).thenReturn(true); when(virtRouterResource.isSystemVMSetup(vmName, controlIp)).thenReturn(true); } catch (final InternalErrorException e) { @@ -5429,11 +5431,11 @@ public void testStartCommandIsolationEc2() throws Exception { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); - verify(libvirtComputingResource, times(1)).getStoragePoolMgr(); - verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper(); + verify(libvirtComputingResourceMock, times(1)).getStoragePoolMgr(); + verify(libvirtComputingResourceMock, times(1)).getLibvirtUtilitiesHelper(); try { verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType()); } catch (final LibvirtException e) { @@ -5462,21 +5464,21 @@ public void testStartCommandHostMemory() { final String vmName = "Test"; - when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr); + when(libvirtComputingResourceMock.getStoragePoolMgr()).thenReturn(storagePoolMgr); when(vmSpec.getNics()).thenReturn(nics); when(vmSpec.getType()).thenReturn(VirtualMachine.Type.User); when(vmSpec.getName()).thenReturn(vmName); when(vmSpec.getMaxRam()).thenReturn(512L); - when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef); + when(libvirtComputingResourceMock.createVMFromSpec(vmSpec)).thenReturn(vmDef); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn); when(conn.listDomains()).thenReturn(vms); when(conn.domainLookupByID(vmId)).thenReturn(dm); when(dm.getMaxMemory()).thenReturn(1024L); when(dm.getName()).thenReturn(vmName); - doNothing().when(libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef); + doNothing().when(libvirtComputingResourceMock).createVbd(conn, vmSpec, vmName, vmDef); } catch (final LibvirtException e) { fail(e.getMessage()); } catch (final InternalErrorException e) { @@ -5490,7 +5492,7 @@ public void testStartCommandHostMemory() { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -5506,16 +5508,16 @@ public void testUpdateHostPasswordCommand() { final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword, hostIp); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getUpdateHostPasswdPath()).thenReturn("/tmp"); - when(libvirtUtilitiesHelper.buildScript(libvirtComputingResource.getUpdateHostPasswdPath())).thenReturn(script); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getUpdateHostPasswdPath()).thenReturn("/tmp"); + when(libvirtUtilitiesHelper.buildScript(libvirtComputingResourceMock.getUpdateHostPasswdPath())).thenReturn(script); when(script.execute()).thenReturn(null); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertTrue(answer.getResult()); } @@ -5531,16 +5533,16 @@ public void testUpdateHostPasswordCommandFail() { final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword, hostIp); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); - when(libvirtComputingResource.getUpdateHostPasswdPath()).thenReturn("/tmp"); - when(libvirtUtilitiesHelper.buildScript(libvirtComputingResource.getUpdateHostPasswdPath())).thenReturn(script); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getUpdateHostPasswdPath()).thenReturn("/tmp"); + when(libvirtUtilitiesHelper.buildScript(libvirtComputingResourceMock.getUpdateHostPasswdPath())).thenReturn(script); when(script.execute()).thenReturn("#FAIL"); final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); assertNotNull(wrapper); - final Answer answer = wrapper.execute(command, libvirtComputingResource); + final Answer answer = wrapper.execute(command, libvirtComputingResourceMock); assertFalse(answer.getResult()); } @@ -5655,44 +5657,44 @@ public void testSetQuotaAndPeriodMinQuota() { @Test public void testUnknownCommand() { - libvirtComputingResource = new LibvirtComputingResource(); + libvirtComputingResourceMock = new LibvirtComputingResource(); Command cmd = new Command() { @Override public boolean executeInSequence() { return false; } }; - Answer ans = libvirtComputingResource.executeRequest(cmd); + Answer ans = libvirtComputingResourceMock.executeRequest(cmd); assertTrue(ans instanceof UnsupportedAnswer); } @Test public void testKnownCommand() { - libvirtComputingResource = new LibvirtComputingResource(); + libvirtComputingResourceMock = new LibvirtComputingResource(); Command cmd = new PingTestCommand() { @Override public boolean executeInSequence() { throw new NullPointerException("test succeeded"); } }; - Answer ans = libvirtComputingResource.executeRequest(cmd); + Answer ans = libvirtComputingResourceMock.executeRequest(cmd); assertFalse(ans instanceof UnsupportedAnswer); assertTrue(ans instanceof Answer); } @Test public void testAddExtraConfigComponentEmptyExtraConfig() { - libvirtComputingResource = new LibvirtComputingResource(); - libvirtComputingResource.addExtraConfigComponent(new HashMap<>(), vmDef); + libvirtComputingResourceMock = new LibvirtComputingResource(); + libvirtComputingResourceMock.addExtraConfigComponent(new HashMap<>(), vmDef); Mockito.verify(vmDef, never()).addComp(any()); } @Test public void testAddExtraConfigComponentNotEmptyExtraConfig() { - libvirtComputingResource = new LibvirtComputingResource(); + libvirtComputingResourceMock = new LibvirtComputingResource(); Map extraConfig = new HashMap<>(); extraConfig.put("extraconfig-1", "value1"); extraConfig.put("extraconfig-2", "value2"); extraConfig.put("extraconfig-3", "value3"); - libvirtComputingResource.addExtraConfigComponent(extraConfig, vmDef); + libvirtComputingResourceMock.addExtraConfigComponent(extraConfig, vmDef); Mockito.verify(vmDef, times(1)).addComp(any()); } @@ -5864,39 +5866,36 @@ public void setCpuSharesTestSuccessfullySetCpuShares() throws LibvirtException { })); } - private void configLocalStorageTests(Map params) throws ConfigurationException { - LibvirtComputingResource libvirtComputingResourceSpy = Mockito.spy(new LibvirtComputingResource()); - libvirtComputingResourceSpy.configureLocalStorage(params); - } - @Test public void testConfigureLocalStorageWithEmptyParams() throws ConfigurationException { - Map params = new HashMap<>(); - configLocalStorageTests(params); + libvirtComputingResourceSpy.configureLocalStorage(); } @Test public void testConfigureLocalStorageWithMultiplePaths() throws ConfigurationException { - Map params = new HashMap<>(); - params.put(LibvirtComputingResource.LOCAL_STORAGE_PATH, "/var/lib/libvirt/images/,/var/lib/libvirt/images2/"); - params.put(LibvirtComputingResource.LOCAL_STORAGE_UUID, UUID.randomUUID().toString() + "," + UUID.randomUUID().toString()); - configLocalStorageTests(params); + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH))).thenReturn("/var/lib/libvirt/images/,/var/lib/libvirt/images2/"); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID))).thenReturn(UUID.randomUUID().toString() + "," + UUID.randomUUID().toString()); + + libvirtComputingResourceSpy.configureLocalStorage(); } @Test(expected = ConfigurationException.class) - public void testConfigureLocalStorageWithDifferentLength() throws ConfigurationException { - Map params = new HashMap<>(); - params.put(LibvirtComputingResource.LOCAL_STORAGE_PATH, "/var/lib/libvirt/images/,/var/lib/libvirt/images2/"); - params.put(LibvirtComputingResource.LOCAL_STORAGE_UUID, UUID.randomUUID().toString()); - configLocalStorageTests(params); + public void testConfigureLocalStorageWithDifferentLength() throws Exception { + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH))).thenReturn("/var/lib/libvirt/images/,/var/lib/libvirt/images2/"); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID))).thenReturn(UUID.randomUUID().toString()); + + libvirtComputingResourceSpy.configureLocalStorage(); } @Test(expected = ConfigurationException.class) public void testConfigureLocalStorageWithInvalidUUID() throws ConfigurationException { - Map params = new HashMap<>(); - params.put(LibvirtComputingResource.LOCAL_STORAGE_PATH, "/var/lib/libvirt/images/"); - params.put(LibvirtComputingResource.LOCAL_STORAGE_UUID, "111111"); - configLocalStorageTests(params); + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_PATH))).thenReturn("/var/lib/libvirt/images/"); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.eq(AgentProperties.LOCAL_STORAGE_UUID))).thenReturn("111111"); + + libvirtComputingResourceSpy.configureLocalStorage(); } } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java index 098352915a84..e3b74e84e1d7 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVifDriverTest.java @@ -36,15 +36,18 @@ import org.junit.Before; import org.junit.Test; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource.BridgeType; import com.cloud.network.Networks.TrafficType; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) -@PrepareForTest(value = {MemStat.class}) +@PrepareForTest(value = {MemStat.class, AgentPropertiesFileHandler.class}) public class LibvirtVifDriverTest { private LibvirtComputingResource res; @@ -132,40 +135,44 @@ public void testDefaults() throws ConfigurationException { } @Test - public void testDefaultsWhenExplicitlySet() throws ConfigurationException { + public void configureVifDriversTestWhenSetEqualToDefault() throws Exception { + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.doReturn(LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME).when(AgentPropertiesFileHandler.class, "getPropertyValue", Mockito.eq(AgentProperties.LIBVIRT_VIF_DRIVER)); Map params = new HashMap(); // Switch res' bridge type for test purposes - params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.NATIVE; configure(params); checkAllSame(bridgeVifDriver); - params.clear(); - params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.OPENVSWITCH; configure(params); checkAllSame(ovsVifDriver); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.times(2)); + AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER); } @Test - public void testWhenExplicitlySetDifferentDefault() throws ConfigurationException { + public void configureVifDriversTestWhenSetDifferentFromDefault() throws Exception { + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.doReturn(LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME).when(AgentPropertiesFileHandler.class, "getPropertyValue", Mockito.eq(AgentProperties.LIBVIRT_VIF_DRIVER)); // Tests when explicitly set vif driver to OVS when using regular bridges and vice versa Map params = new HashMap(); // Switch res' bridge type for test purposes - params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_OVS_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.NATIVE; configure(params); checkAllSame(ovsVifDriver); - params.clear(); - params.put(LibVirtVifDriver, LibvirtComputingResource.DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME); res._bridgeType = BridgeType.OPENVSWITCH; configure(params); checkAllSame(bridgeVifDriver); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.times(2)); + AgentPropertiesFileHandler.getPropertyValue(AgentProperties.LIBVIRT_VIF_DRIVER); } @Test From ad0f150b4bc5cf121d1b3b1a22106e708e0bc1ad Mon Sep 17 00:00:00 2001 From: Paula Zomignani Oliveira Date: Wed, 4 May 2022 14:45:20 -0300 Subject: [PATCH 02/23] Specify exception and remove unnecessary print --- agent/src/main/java/com/cloud/agent/AgentShell.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index f187626767a9..8b4ed1b3e88e 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -41,6 +41,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; @@ -440,7 +441,8 @@ private void launchAgentFromClassInfo(String resourceClassNames) throws Configur constructor.setAccessible(true); ServerResource resource = (ServerResource)constructor.newInstance(); launchNewAgent(resource); - } catch (final Exception e) { + } catch (final ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalArgumentException | InstantiationException | + IllegalAccessException | InvocationTargetException e) { ConfigurationException configurationException = new ConfigurationException(String.format("Error while creating Agent with class [%s].", name)); configurationException.setRootCause(e); throw configurationException; } @@ -529,7 +531,6 @@ public void start() { } catch (final Exception e) { s_logger.error("Unable to start agent: ", e); - System.out.println("Unable to start agent: " + e.getMessage()); System.exit(ExitStatus.Error.value()); } } From 48c3957c48a43e83022dbca18d0d297d534cf548 Mon Sep 17 00:00:00 2001 From: Paula Zomignani Oliveira Date: Thu, 19 May 2022 15:22:37 -0300 Subject: [PATCH 03/23] fixing indentation --- .../properties/AgentPropertiesFileHandler.java | 13 ++++++------- .../kvm/resource/LibvirtComputingResource.java | 4 ++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java b/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java index 7d213199c895..602aa1efcb0d 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentPropertiesFileHandler.java @@ -56,24 +56,23 @@ public static T getPropertyValue(AgentProperties.Property property) { String configValue = PropertiesUtil.loadFromFile(agentPropertiesFile).getProperty(name); if (StringUtils.isBlank(configValue)) { logger.debug(String.format("Property [%s] has empty or null value. Using default value [%s].", name, defaultValue)); - return defaultValue; - } + } if (defaultValue instanceof Integer) { ConvertUtils.register(new IntegerConverter(defaultValue), Integer.class); - } + } if (defaultValue instanceof Long) { ConvertUtils.register(new LongConverter(defaultValue), Long.class); - } + } logger.debug(String.format("Property [%s] was altered. Now using the value [%s].", name, configValue)); return (T)ConvertUtils.convert(configValue, property.getTypeClass()); - } catch (IOException ex) { - logger.debug(String.format("Failed to get property [%s]. Using default value [%s].", name, defaultValue), ex); - } + } catch (IOException ex) { + logger.debug(String.format("Failed to get property [%s]. Using default value [%s].", name, defaultValue), ex); + } return defaultValue; } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 3b37f06cc59c..483685109b15 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -963,11 +963,11 @@ public boolean configure(final String name, final Map params) th _videoRam = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_VIDEO_RAM); // Reserve 1GB unless admin overrides - _dom0MinMem = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB) * 1024 * 1024L; + _dom0MinMem = ByteScaleUtils.mibToBytes((long) AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB)); // Support overcommit memory for host if host uses ZSWAP, KSM and other memory // compressing technologies - _dom0OvercommitMem = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB) * 1024 * 1024L; + _dom0OvercommitMem = ByteScaleUtils.mibToBytes((long) AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB)); if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVMCLOCK_DISABLE)) { _noKvmClock = true; From ca80585158657d47ccda76e64b6dfad120731fc0 Mon Sep 17 00:00:00 2001 From: Paula Zomignani Oliveira Date: Fri, 24 Jun 2022 11:44:06 -0300 Subject: [PATCH 04/23] Pass public and private interface to super class on LibvirtComputingResource#configure --- .../cloud/resource/ServerResourceBase.java | 131 +++++----- .../resource/ServerResourceBaseTest.java | 225 ++++++++++++++++++ .../resource/LibvirtComputingResource.java | 25 +- .../LibvirtComputingResourceTest.java | 32 +++ .../java/com/cloud/utils/net/NetUtils.java | 58 ++++- .../com/cloud/utils/net/NetUtilsTest.java | 62 ++++- 6 files changed, 447 insertions(+), 86 deletions(-) create mode 100644 core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java diff --git a/core/src/main/java/com/cloud/resource/ServerResourceBase.java b/core/src/main/java/com/cloud/resource/ServerResourceBase.java index f68bcf409ef3..f3bad610998e 100644 --- a/core/src/main/java/com/cloud/resource/ServerResourceBase.java +++ b/core/src/main/java/com/cloud/resource/ServerResourceBase.java @@ -24,14 +24,17 @@ import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.Date; -import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.naming.ConfigurationException; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import com.cloud.agent.IAgentControl; @@ -67,60 +70,12 @@ protected String findScript(String script) { public boolean configure(final String name, Map params) throws ConfigurationException { _name = name; - String publicNic = (String)params.get("public.network.device"); - if (publicNic == null) { - publicNic = "xenbr1"; - } - String privateNic = (String)params.get("private.network.device"); - if (privateNic == null) { - privateNic = "xenbr0"; - } - final String storageNic = (String)params.get("storage.network.device"); - final String storageNic2 = (String)params.get("storage.network.device.2"); - - _privateNic = getNetworkInterface(privateNic); - _publicNic = getNetworkInterface(publicNic); - _storageNic = getNetworkInterface(storageNic); - _storageNic2 = getNetworkInterface(storageNic2); + defineResourceNetworkInterfaces(params); if (_privateNic == null) { - s_logger.warn("Nics are not specified in properties file/db, will try to autodiscover"); - - Enumeration nics = null; - try { - nics = NetworkInterface.getNetworkInterfaces(); - if (nics == null || !nics.hasMoreElements()) { - throw new ConfigurationException("Private NIC is not configured"); - } - } catch (final SocketException e) { - throw new ConfigurationException("Private NIC is not configured"); - } - - while (nics.hasMoreElements()) { - final NetworkInterface nic = nics.nextElement(); - final String nicName = nic.getName(); - // try { - if (//!nic.isLoopback() && - //nic.isUp() && - !nic.isVirtual() && !nicName.startsWith("vnif") && !nicName.startsWith("vnbr") && !nicName.startsWith("peth") && !nicName.startsWith("vif") && - !nicName.startsWith("virbr") && !nicName.contains(":")) { - final String[] info = NetUtils.getNicParams(nicName); - if (info != null && info[0] != null) { - _privateNic = nic; - s_logger.info("Designating private to be nic " + nicName); - break; - } - } - // } catch (final SocketException e) { - // s_logger.warn("Error looking at " + nicName, e); - // } - s_logger.debug("Skipping nic " + nicName); - } - - if (_privateNic == null) { - throw new ConfigurationException("Private NIC is not configured"); - } + tryToAutoDiscoverResourcePrivateNetworkInterface(); } + String infos[] = NetUtils.getNetworkParams(_privateNic); if (infos == null) { s_logger.warn("Incorrect details for private Nic during initialization of ServerResourceBase"); @@ -132,31 +87,67 @@ public boolean configure(final String name, Map params) throws C return true; } - protected NetworkInterface getNetworkInterface(String nicName) { - s_logger.debug("Retrieving network interface: " + nicName); - if (nicName == null) { - return null; - } + protected void defineResourceNetworkInterfaces(Map params) { + String privateNic = (String) params.get("private.network.device"); + privateNic = privateNic == null ? "xenbr0" : privateNic; - if (nicName.trim().length() == 0) { - return null; - } + String publicNic = (String) params.get("public.network.device"); + publicNic = publicNic == null ? "xenbr1" : publicNic; + + String storageNic = (String) params.get("storage.network.device"); + String storageNic2 = (String) params.get("storage.network.device.2"); + + _privateNic = NetUtils.getNetworkInterface(privateNic); + _publicNic = NetUtils.getNetworkInterface(publicNic); + _storageNic = NetUtils.getNetworkInterface(storageNic); + _storageNic2 = NetUtils.getNetworkInterface(storageNic2); + } - nicName = nicName.trim(); + protected void tryToAutoDiscoverResourcePrivateNetworkInterface() throws ConfigurationException { + s_logger.info("Trying to autodiscover this resource's private network interface."); - NetworkInterface nic; + List nics; try { - nic = NetworkInterface.getByName(nicName); - if (nic == null) { - s_logger.debug("Unable to get network interface for " + nicName); - return null; + nics = Collections.list(NetworkInterface.getNetworkInterfaces()); + if (CollectionUtils.isEmpty(nics)) { + throw new ConfigurationException("This resource has no NICs. Unable to configure it."); + } + } catch (SocketException e) { + throw new ConfigurationException(String.format("Could not retrieve the environment NICs due to [%s].", e.getMessage())); + } + + s_logger.debug(String.format("Searching the private NIC along the environment NICs [%s].", Arrays.toString(nics.toArray()))); + + for (NetworkInterface nic : nics) { + if (isValidNicToUseAsPrivateNic(nic)) { + s_logger.info(String.format("Using NIC [%s] as private NIC.", nic)); + _privateNic = nic; + return; } + } + + throw new ConfigurationException("It was not possible to define a private NIC for this resource."); + } - return nic; - } catch (final SocketException e) { - s_logger.warn("Unable to get network interface for " + nicName, e); - return null; + protected boolean isValidNicToUseAsPrivateNic(NetworkInterface nic) { + String nicName = nic.getName(); + + s_logger.debug(String.format("Verifying if NIC [%s] can be used as private NIC.", nic)); + + String[] nicNameStartsToAvoid = {"vnif", "vnbr", "peth", "vif", "virbr"}; + if (nic.isVirtual() || StringUtils.startsWithAny(nicName, nicNameStartsToAvoid) || nicName.contains(":")) { + s_logger.debug(String.format("Not using NIC [%s] because it is either virtual, starts with %s, or contains \":\"" + + " in its name.", Arrays.toString(nicNameStartsToAvoid), nic)); + return false; + } + + String[] info = NetUtils.getNicParams(nicName); + if (info == null || info[0] == null) { + s_logger.debug(String.format("Not using NIC [%s] because it does not have a valid IP to use as the private IP.", nic)); + return false; } + + return true; } protected void fillNetworkInformation(final StartupCommand cmd) { diff --git a/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java b/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java new file mode 100644 index 000000000000..eb7d5a573823 --- /dev/null +++ b/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java @@ -0,0 +1,225 @@ +package com.cloud.resource; + +import com.cloud.utils.net.NetUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import javax.naming.ConfigurationException; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +@RunWith(PowerMockRunner.class) +public class ServerResourceBaseTest { + + private static final String[] NIC_NAME_STARTS_TO_AVOID = {"vnif", "vnbr", "peth", "vif", "virbr"}; + + ServerResourceBase serverResourceBaseSpy = Mockito.spy(ServerResourceBase.class); + + NetworkInterface networkInterfaceMock1, networkInterfaceMock2, networkInterfaceMock3, networkInterfaceMock4; + + @Captor + ArgumentCaptor keyCaptor; + + @Before + public void setup() { + networkInterfaceMock1 = PowerMockito.mock(NetworkInterface.class); + networkInterfaceMock2 = PowerMockito.mock(NetworkInterface.class); + networkInterfaceMock3 = PowerMockito.mock(NetworkInterface.class); + networkInterfaceMock4 = PowerMockito.mock(NetworkInterface.class); + } + + @Test + @PrepareForTest(ServerResourceBase.class) + public void isValidNicToUseAsPrivateNicTestReturnFalseWhenNicIsVirtual() { + NetworkInterface networkInterfaceMock = PowerMockito.mock(NetworkInterface.class); + PowerMockito.when(networkInterfaceMock.isVirtual()).thenReturn(true); + + Assert.assertFalse(serverResourceBaseSpy.isValidNicToUseAsPrivateNic(networkInterfaceMock)); + } + + @Test + @PrepareForTest(ServerResourceBase.class) + public void isValidNicToUseAsPrivateNicTestReturnFalseWhenNicNameStartsWithOneOfTheAvoidList() { + NetworkInterface networkInterfaceMock = PowerMockito.mock(NetworkInterface.class); + PowerMockito.when(networkInterfaceMock.isVirtual()).thenReturn(false); + PowerMockito.when(networkInterfaceMock.getName()).thenReturn("vniftest", "vnbrtest", "pethtest", "viftest", "virbrtest"); + + Arrays.asList(NIC_NAME_STARTS_TO_AVOID).forEach(type -> Assert.assertFalse(serverResourceBaseSpy.isValidNicToUseAsPrivateNic(networkInterfaceMock))); + } + + @Test + @PrepareForTest(ServerResourceBase.class) + public void isValidNicToUseAsPrivateNicTestReturnFalseWhenNicNameContainsColon() { + NetworkInterface networkInterfaceMock = PowerMockito.mock(NetworkInterface.class); + PowerMockito.when(networkInterfaceMock.isVirtual()).thenReturn(false); + PowerMockito.when(networkInterfaceMock.getName()).thenReturn("te:st"); + + Assert.assertFalse(serverResourceBaseSpy.isValidNicToUseAsPrivateNic(networkInterfaceMock)); + } + + @Test + @PrepareForTest({ServerResourceBase.class, NetUtils.class}) + public void isValidNicToUseAsPrivateNicTestReturnFalseWhenNetUtilsGetNicParamsReturnsNull() { + NetworkInterface networkInterfaceMock = PowerMockito.mock(NetworkInterface.class); + PowerMockito.when(networkInterfaceMock.isVirtual()).thenReturn(false); + PowerMockito.when(networkInterfaceMock.getName()).thenReturn("testvnif", "testvnbr", "testpeth", "testvif", "testvirbr"); + + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNicParams(Mockito.anyString())).thenReturn(null); + + Arrays.asList(NIC_NAME_STARTS_TO_AVOID).forEach(type -> { + Assert.assertFalse(serverResourceBaseSpy.isValidNicToUseAsPrivateNic(networkInterfaceMock)); + }); + } + + @Test + @PrepareForTest({ServerResourceBase.class, NetUtils.class}) + public void isValidNicToUseAsPrivateNicTestReturnFalseWhenNetUtilsGetNicParamsReturnsFirstElementNull() { + NetworkInterface networkInterfaceMock = PowerMockito.mock(NetworkInterface.class); + PowerMockito.when(networkInterfaceMock.isVirtual()).thenReturn(false); + PowerMockito.when(networkInterfaceMock.getName()).thenReturn("testvnif", "testvnbr", "testpeth", "testvif", "testvirbr"); + + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNicParams(Mockito.anyString())).thenReturn(new String[]{null}); + + Arrays.asList(NIC_NAME_STARTS_TO_AVOID).forEach(type -> { + Assert.assertFalse(serverResourceBaseSpy.isValidNicToUseAsPrivateNic(networkInterfaceMock)); + }); + } + + @Test + @PrepareForTest({ServerResourceBase.class, NetUtils.class}) + public void isValidNicToUseAsPrivateNicTestReturnTrueWhenNetUtilsGetNicParamsReturnsAValidFirstElement() { + NetworkInterface networkInterfaceMock = PowerMockito.mock(NetworkInterface.class); + PowerMockito.when(networkInterfaceMock.isVirtual()).thenReturn(false); + PowerMockito.when(networkInterfaceMock.getName()).thenReturn("testvnif", "testvnbr", "testpeth", "testvif", "testvirbr"); + + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNicParams(Mockito.anyString())).thenReturn(new String[]{"test"}); + + Arrays.asList(NIC_NAME_STARTS_TO_AVOID).forEach(type -> { + Assert.assertTrue(serverResourceBaseSpy.isValidNicToUseAsPrivateNic(networkInterfaceMock)); + }); + } + + @Test(expected = ConfigurationException.class) + @PrepareForTest(ServerResourceBase.class) + public void tryToAutoDiscoverResourcePrivateNetworkInterfaceTestThrowConfigurationExceptionWhenNicsDoesNotHaveMoreElements() throws SocketException, ConfigurationException { + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getNetworkInterfaces()).thenReturn(Collections.enumeration(new ArrayList<>())); + + serverResourceBaseSpy.tryToAutoDiscoverResourcePrivateNetworkInterface(); + } + + @Test(expected = ConfigurationException.class) + @PrepareForTest(ServerResourceBase.class) + public void tryToAutoDiscoverResourcePrivateNetworkInterfaceTestThrowConfigurationExceptionWhenNicsGetNetworkInterfacesThrowsSocketException() throws SocketException, ConfigurationException { + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getNetworkInterfaces()).thenThrow(SocketException.class); + + serverResourceBaseSpy.tryToAutoDiscoverResourcePrivateNetworkInterface(); + } + + @Test(expected = ConfigurationException.class) + @PrepareForTest(ServerResourceBase.class) + public void tryToAutoDiscoverResourcePrivateNetworkInterfaceTestThrowConfigurationExceptionWhenThereIsNoValidNics() throws SocketException, ConfigurationException { + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getNetworkInterfaces()).thenReturn(Collections.enumeration(Arrays.asList(networkInterfaceMock1, networkInterfaceMock2))); + Mockito.doReturn(false).when(serverResourceBaseSpy).isValidNicToUseAsPrivateNic(Mockito.any()); + + serverResourceBaseSpy.tryToAutoDiscoverResourcePrivateNetworkInterface(); + + Mockito.verify(serverResourceBaseSpy, Mockito.times(2)).isValidNicToUseAsPrivateNic(Mockito.any()); + } + + @Test + @PrepareForTest(ServerResourceBase.class) + public void tryToAutoDiscoverResourcePrivateNetworkInterfaceTestReturnNic() throws SocketException, ConfigurationException { + Enumeration interfaces = Collections.enumeration(Arrays.asList(networkInterfaceMock1, networkInterfaceMock2)); + + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getNetworkInterfaces()).thenReturn(interfaces); + Mockito.doReturn(false, true).when(serverResourceBaseSpy).isValidNicToUseAsPrivateNic(Mockito.any()); + + serverResourceBaseSpy.tryToAutoDiscoverResourcePrivateNetworkInterface(); + + Assert.assertEquals(networkInterfaceMock2, serverResourceBaseSpy._privateNic); + Mockito.verify(serverResourceBaseSpy, Mockito.times(2)).isValidNicToUseAsPrivateNic(Mockito.any()); + } + + @Test + @PrepareForTest(NetUtils.class) + public void defineResourceNetworkInterfacesTestUseXenbr0WhenPrivateNetworkInterfaceNotConfigured() { + Map params = createParamsMap(null, "cloudbr1", "cloudbr2", "cloudbr3"); + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNetworkInterface(Mockito.anyString())).thenReturn(networkInterfaceMock1, networkInterfaceMock2, networkInterfaceMock3, networkInterfaceMock4); + + serverResourceBaseSpy.defineResourceNetworkInterfaces(params); + + verifyAndAssertNetworkInterfaces("xenbr0", "cloudbr1", "cloudbr2", "cloudbr3"); + } + + @Test + @PrepareForTest(NetUtils.class) + public void defineResourceNetworkInterfacesTestUseXenbr1WhenPublicNetworkInterfaceNotConfigured() { + Map params = createParamsMap("cloudbr0", null, "cloudbr2", "cloudbr3"); + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNetworkInterface(Mockito.anyString())).thenReturn(networkInterfaceMock1, networkInterfaceMock2, networkInterfaceMock3, networkInterfaceMock4); + + serverResourceBaseSpy.defineResourceNetworkInterfaces(params); + + verifyAndAssertNetworkInterfaces("cloudbr0", "xenbr1", "cloudbr2", "cloudbr3"); + } + + @Test + @PrepareForTest(NetUtils.class) + public void defineResourceNetworkInterfacesTestUseConfiguredNetworkInterfaces() { + Map params = createParamsMap("cloudbr0", "cloudbr1", "cloudbr2", "cloudbr3"); + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNetworkInterface(Mockito.anyString())).thenReturn(networkInterfaceMock1, networkInterfaceMock2, networkInterfaceMock3, networkInterfaceMock4); + + serverResourceBaseSpy.defineResourceNetworkInterfaces(params); + + verifyAndAssertNetworkInterfaces("cloudbr0", "cloudbr1", "cloudbr2", "cloudbr3"); + } + + private Map createParamsMap(String... params) { + Map result = new HashMap<>(); + result.put("private.network.device", params[0]); + result.put("public.network.device", params[1]); + result.put("storage.network.device", params[2]); + result.put("storage.network.device.2", params[3]); + return result; + } + + private void verifyAndAssertNetworkInterfaces(String... expectedResults) { + PowerMockito.verifyStatic(NetUtils.class, Mockito.times(4)); + NetUtils.getNetworkInterface(keyCaptor.capture()); + List keys = keyCaptor.getAllValues(); + + for (int i = 0; i < expectedResults.length; i++) { + Assert.assertEquals(expectedResults[i], keys.get(i)); + } + + Assert.assertEquals(networkInterfaceMock1, serverResourceBaseSpy._privateNic); + Assert.assertEquals(networkInterfaceMock2, serverResourceBaseSpy._publicNic); + Assert.assertEquals(networkInterfaceMock3, serverResourceBaseSpy._storageNic); + Assert.assertEquals(networkInterfaceMock4, serverResourceBaseSpy._storageNic2); + } +} diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 091673225f79..7c1574242c85 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.io.StringReader; import java.net.InetAddress; +import java.net.NetworkInterface; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; @@ -746,6 +747,26 @@ protected String getNetworkDirectDevice() { return _networkDirectDevice; } + /** + * Defines resource's public and private network interface according to what is configured in agent.properties. + */ + @Override + protected void defineResourceNetworkInterfaces(Map params) { + _privBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_NETWORK_DEVICE); + _publicBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PUBLIC_NETWORK_DEVICE); + + _privateNic = NetUtils.getNetworkInterface(_privBridgeName); + _publicNic = NetUtils.getNetworkInterface(_publicBridgeName); + } + + public NetworkInterface getPrivateNic() { + return _privateNic; + } + + public NetworkInterface getPublicNic() { + return _publicNic; + } + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { boolean success = super.configure(name, params); @@ -923,10 +944,6 @@ public boolean configure(final String name, final Map params) th } } - _publicBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PUBLIC_NETWORK_DEVICE); - - _privBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_NETWORK_DEVICE); - _guestBridgeName = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUEST_NETWORK_DEVICE); if (_guestBridgeName == null) { _guestBridgeName = _privBridgeName; diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java index b1427510f05c..628995502e7d 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java @@ -35,6 +35,7 @@ import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; +import java.net.NetworkInterface; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; @@ -54,6 +55,7 @@ import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SshHelper; import org.apache.cloudstack.storage.command.AttachAnswer; import org.apache.cloudstack.storage.command.AttachCommand; @@ -79,6 +81,7 @@ import org.libvirt.SchedUlongParameter; import org.libvirt.StorageVol; import org.libvirt.jna.virDomainMemoryStats; +import org.mockito.ArgumentCaptor; import org.mockito.BDDMockito; import org.mockito.Mock; import org.mockito.Mockito; @@ -5898,4 +5901,33 @@ public void testConfigureLocalStorageWithInvalidUUID() throws ConfigurationExcep libvirtComputingResourceSpy.configureLocalStorage(); } + @Test + @PrepareForTest({AgentPropertiesFileHandler.class, NetUtils.class}) + public void defineResourceNetworkInterfacesTestUseProperties() { + NetworkInterface networkInterfaceMock1 = PowerMockito.mock(NetworkInterface.class); + NetworkInterface networkInterfaceMock2 = PowerMockito.mock(NetworkInterface.class); + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn("cloudbr15", "cloudbr28"); + + PowerMockito.mockStatic(NetUtils.class); + PowerMockito.when(NetUtils.getNetworkInterface(Mockito.anyString())).thenReturn(networkInterfaceMock1, networkInterfaceMock2); + + libvirtComputingResourceSpy.defineResourceNetworkInterfaces(null); + + ArgumentCaptor keyCaptor = ArgumentCaptor.forClass(String.class); + PowerMockito.verifyStatic(NetUtils.class, Mockito.times(2)); + NetUtils.getNetworkInterface(keyCaptor.capture()); + + List keys = keyCaptor.getAllValues(); + Assert.assertEquals("cloudbr15", keys.get(0)); + Assert.assertEquals("cloudbr28", keys.get(1)); + + Assert.assertEquals("cloudbr15", libvirtComputingResourceSpy._privBridgeName); + Assert.assertEquals("cloudbr28", libvirtComputingResourceSpy._publicBridgeName); + + Assert.assertEquals(networkInterfaceMock1, libvirtComputingResourceSpy.getPrivateNic()); + Assert.assertEquals(networkInterfaceMock2, libvirtComputingResourceSpy.getPublicNic()); + } + } diff --git a/utils/src/main/java/com/cloud/utils/net/NetUtils.java b/utils/src/main/java/com/cloud/utils/net/NetUtils.java index 768dbff132cb..6ea8e5f4b0d3 100644 --- a/utils/src/main/java/com/cloud/utils/net/NetUtils.java +++ b/utils/src/main/java/com/cloud/utils/net/NetUtils.java @@ -32,6 +32,7 @@ import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Formatter; import java.util.Iterator; @@ -43,6 +44,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.net.util.SubnetUtils; @@ -420,30 +422,49 @@ public static String[] getNicParams(final String nicName) { } } - public static String[] getNetworkParams(final NetworkInterface nic) { + public static String[] getNetworkParams(NetworkInterface nic) { + s_logger.debug(String.format("Retrieving network params of NIC [%s].", nic)); + + s_logger.trace(String.format("Retrieving all NIC [%s] addresses.", nic)); List addrs = nic.getInterfaceAddresses(); - if (addrs == null || addrs.size() == 0) { + if (CollectionUtils.isEmpty(addrs)) { + s_logger.debug(String.format("NIC [%s] has no addresses, returning null.", nic)); return null; } - Collections.reverse(addrs); // reverse addresses because it has reverse order as "ip addr show" + + String addrsToString = Arrays.toString(addrs.toArray()); + s_logger.trace(String.format("Found [%s] as NIC [%s] addresses. Reversing the list order because it has reverse order in \"ip addr show\".", + addrsToString, nic)); + + Collections.reverse(addrs); InterfaceAddress addr = null; - for (final InterfaceAddress iaddr : addrs) { - final InetAddress inet = iaddr.getAddress(); + + s_logger.trace(String.format("Iterating through the NIC [%s] addresses [%s] to find a valid address.", nic, addrsToString)); + for (InterfaceAddress iaddr : addrs) { + InetAddress inet = iaddr.getAddress(); + s_logger.trace(String.format("Validating address [%s].", inet)); if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) { addr = iaddr; break; } + s_logger.trace(String.format("Address [%s] is link local [%s], loopback [%s], multicast [%s], or does not have 4 octets [%s]; therefore we will not retrieve its" + + " interface params.", inet, inet.isLinkLocalAddress(), inet.isLoopbackAddress(), inet.isMulticastAddress(), inet.getAddress().length)); } if (addr == null) { + s_logger.debug(String.format("Could not find a valid address in NIC [%s], returning null.", nic)); return null; } - final String[] result = new String[3]; + + s_logger.debug(String.format("Retrieving params of address [%s] of NIC [%s].", addr, nic)); + + String[] result = new String[3]; result[0] = addr.getAddress().getHostAddress(); + try { final byte[] mac = nic.getHardwareAddress(); result[1] = byte2Mac(mac); } catch (final SocketException e) { - s_logger.debug("Caught exception when trying to get the mac address ", e); + s_logger.warn(String.format("Unable to get NIC's [%s] MAC address due to [%s].", nic, e.getMessage()), e); } result[2] = prefix2Netmask(addr.getNetworkPrefixLength()); @@ -1727,4 +1748,27 @@ public static boolean ipv6NetworksOverlap(IPv6Network n1, IPv6Network n2) { return false; } + public static NetworkInterface getNetworkInterface(String nicName) { + s_logger.debug(String.format("Retrieving network interface [%s].", nicName)); + nicName = StringUtils.trimToNull(nicName); + + if (nicName == null) { + return null; + } + + NetworkInterface nic; + try { + nic = NetworkInterface.getByName(nicName); + if (nic == null) { + s_logger.debug(String.format("Unable to get network interface for NIC [%s].", nicName)); + return null; + } + + return nic; + } catch (final SocketException e) { + s_logger.warn(String.format("Unable to get network interface for NIC [%s] due to [%s].", nicName, e.getMessage()), e); + return null; + } + } + } diff --git a/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java index 1eff484a2785..2fa8496a235b 100644 --- a/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java +++ b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java @@ -33,11 +33,13 @@ import java.math.BigInteger; import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; import java.net.UnknownHostException; import java.util.SortedSet; import java.util.TreeSet; -import org.apache.log4j.Logger; +import org.junit.Assert; import org.junit.Test; import com.cloud.utils.exception.CloudRuntimeException; @@ -45,9 +47,17 @@ import com.googlecode.ipv6.IPv6Address; import com.googlecode.ipv6.IPv6Network; -public class NetUtilsTest { +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + - private static final Logger s_logger = Logger.getLogger(NetUtilsTest.class); +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"jdk.xml.internal.*", "javax.xml.parsers.*", "org.xml.sax.*", "org.w3c.dom.*"}) +public class NetUtilsTest { @Test public void testGetRandomIpFromCidrWithSize24() throws Exception { @@ -135,14 +145,12 @@ public void testGetIp6FromRange() { for (int i = 0; i < 5; i++) { final String ip = NetUtils.getIp6FromRange("1234:5678::1-1234:5678::2"); assertThat(ip, anyOf(equalTo("1234:5678::1"), equalTo("1234:5678::2"))); - s_logger.info("IP is " + ip); } String ipString = null; final IPv6Address ipStart = IPv6Address.fromString("1234:5678::1"); final IPv6Address ipEnd = IPv6Address.fromString("1234:5678::ffff:ffff:ffff:ffff"); for (int i = 0; i < 10; i++) { ipString = NetUtils.getIp6FromRange(ipStart.toString() + "-" + ipEnd.toString()); - s_logger.info("IP is " + ipString); final IPv6Address ip = IPv6Address.fromString(ipString); assertThat(ip, greaterThanOrEqualTo(ipStart)); assertThat(ip, lessThanOrEqualTo(ipEnd)); @@ -741,4 +749,48 @@ public void testCidrNetmask() { assertEquals("255.255.0.0", NetUtils.cidr2Netmask("169.254.0.0/16")); assertEquals("255.255.240.0", NetUtils.cidr2Netmask("169.254.240.0/20")); } + + @Test + public void getNetworkInterfaceTestReturnNullWhenStringIsNull() { + NetworkInterface result = NetUtils.getNetworkInterface(null); + Assert.assertNull(result); + } + + @Test + public void getNetworkInterfaceTestReturnNullWhenStringIsEmpty() { + NetworkInterface result = NetUtils.getNetworkInterface(" "); + Assert.assertNull(result); + } + + @Test + @PrepareForTest(NetUtils.class) + public void getNetworkInterfaceTestReturnNullWhenGetByNameReturnsNull() throws SocketException { + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getByName(Mockito.anyString())).thenReturn(null); + NetworkInterface result = NetUtils.getNetworkInterface(" test "); + + Assert.assertNull(result); + } + + @Test + @PrepareForTest(NetUtils.class) + public void getNetworkInterfaceTestReturnNullWhenGetByNameThrowsException() throws SocketException { + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getByName(Mockito.anyString())).thenThrow(SocketException.class); + NetworkInterface result = NetUtils.getNetworkInterface(" test "); + + Assert.assertNull(result); + } + + @Test + @PrepareForTest(NetUtils.class) + public void getNetworkInterfaceTestReturnInterfaceReturnedByGetByName() throws SocketException { + NetworkInterface expected = PowerMockito.mock(NetworkInterface.class); + PowerMockito.mockStatic(NetworkInterface.class); + PowerMockito.when(NetworkInterface.getByName(Mockito.anyString())).thenReturn(expected); + + NetworkInterface result = NetUtils.getNetworkInterface(" test "); + + Assert.assertEquals(expected, result); + } } From 6022d8dd3edba6a54525068f5a27bb56475801be Mon Sep 17 00:00:00 2001 From: Paula Zomignani Oliveira Date: Fri, 1 Jul 2022 10:58:22 -0300 Subject: [PATCH 05/23] Removing code smells --- .../agent/properties/AgentProperties.java | 163 +++++++++--------- .../resource/LibvirtComputingResource.java | 16 +- 2 files changed, 89 insertions(+), 90 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index cbf2f6e5c8ce..02cb882c6472 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -24,6 +24,7 @@ * @param type of the default value. */ public class AgentProperties{ + private static final String DEFAULT = "default"; /** * MANDATORY: The GUID to identify the agent with.
@@ -31,28 +32,28 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property GUID = new Property("guid", null, String.class); + public static final Property GUID = new Property<>("guid", null, String.class); /** * The java class which the agent loads to execute.
* Data type: String.
* Default value: com.cloud.hypervisor.kvm.resource.LibvirtComputingResource */ - public static final Property RESOURCE = new Property("resource", "com.cloud.hypervisor.kvm.resource.LibvirtComputingResource"); + public static final Property RESOURCE = new Property<>("resource", "com.cloud.hypervisor.kvm.resource.LibvirtComputingResource"); /** * The number of threads running in the agent.
* Data type: Integer.
* Default value: 5 */ - public static final Property WORKERS = new Property("workers", 5); + public static final Property WORKERS = new Property<>("workers", 5); /** * The IP address of the management server.
* Data type: String.
* Default value: localhost */ - public static final Property HOST = new Property("host", "localhost"); + public static final Property HOST = new Property<>("host", "localhost"); /** * The time interval (in seconds) after which the agent will check if the connected host is the preferred host.
@@ -61,56 +62,56 @@ public class AgentProperties{ * Data type: Integer.
* Default value: null */ - public static final Property HOST_LB_CHECK_INTERVAL = new Property("host.lb.check.interval", null, Integer.class); + public static final Property HOST_LB_CHECK_INTERVAL = new Property<>("host.lb.check.interval", null, Integer.class); /** * The port that the management server is listening on.
* Data type: Integer.
* Default value: 8250 */ - public static final Property PORT = new Property("port", 8250); + public static final Property PORT = new Property<>("port", 8250); /** * The cluster which the agent belongs to.
* Data type: String.
* Default value: default */ - public static final Property CLUSTER = new Property("cluster", "default"); + public static final Property CLUSTER = new Property<>("cluster", DEFAULT); /** * The pod which the agent belongs to.
* Data type: String.
* Default value: default */ - public static final Property POD = new Property("pod", "default"); + public static final Property POD = new Property<>("pod", DEFAULT); /** * The zone which the agent belongs to.
* Data type: String.
* Default value: default */ - public static final Property ZONE = new Property("zone", "default"); + public static final Property ZONE = new Property<>("zone", DEFAULT); /** * Public NIC device. If this property is commented, it will be autodetected on service startup.
* Data type: String.
* Default value: cloudbr0 */ - public static final Property PUBLIC_NETWORK_DEVICE = new Property("public.network.device", "cloudbr0"); + public static final Property PUBLIC_NETWORK_DEVICE = new Property<>("public.network.device", "cloudbr0"); /** * Private NIC device. If this property is commented, it will be autodetected on service startup.
* Data type: String.
* Default value: cloudbr1 */ - public static final Property PRIVATE_NETWORK_DEVICE = new Property("private.network.device", "cloudbr1"); + public static final Property PRIVATE_NETWORK_DEVICE = new Property<>("private.network.device", "cloudbr1"); /** * Guest NIC device. If this property is commented, the value of the private NIC device will be used.
* Data type: String.
* Default value: the private NIC device value. */ - public static final Property GUEST_NETWORK_DEVICE = new Property("guest.network.device", null, String.class); + public static final Property GUEST_NETWORK_DEVICE = new Property<>("guest.network.device", null, String.class); /** * Local storage path.
@@ -118,7 +119,7 @@ public class AgentProperties{ * Data type: String.
* Default value: /var/lib/libvirt/images/ */ - public static final Property LOCAL_STORAGE_PATH = new Property("local.storage.path", "/var/lib/libvirt/images/"); + public static final Property LOCAL_STORAGE_PATH = new Property<>("local.storage.path", "/var/lib/libvirt/images/"); /** * Directory where Qemu sockets are placed.
@@ -127,7 +128,7 @@ public class AgentProperties{ * Data type: String.
* Default value: /var/lib/libvirt/qemu */ - public static final Property QEMU_SOCKETS_PATH = new Property("qemu.sockets.path", "/var/lib/libvirt/qemu"); + public static final Property QEMU_SOCKETS_PATH = new Property<>("qemu.sockets.path", "/var/lib/libvirt/qemu"); /** * MANDATORY: The UUID for the local storage pool.
@@ -135,7 +136,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property LOCAL_STORAGE_UUID = new Property("local.storage.uuid", null, String.class); + public static final Property LOCAL_STORAGE_UUID = new Property<>("local.storage.uuid", null, String.class); /** * Location for KVM virtual router scripts.
@@ -143,14 +144,14 @@ public class AgentProperties{ * Data type: String.
* Default value: scripts/network/domr */ - public static final Property DOMR_SCRIPTS_DIR = new Property("domr.scripts.dir", "scripts/network/domr"); + public static final Property DOMR_SCRIPTS_DIR = new Property<>("domr.scripts.dir", "scripts/network/domr"); /** * The timeout (in ms) for time-consuming operations, such as create/copy a snapshot.
* Data type: Integer.
* Default value: 7200 */ - public static final Property CMDS_TIMEOUT = new Property("cmds.timeout", 7200); + public static final Property CMDS_TIMEOUT = new Property<>("cmds.timeout", 7200); /** * This parameter sets the VM migration speed (in mbps). The default value is -1,
@@ -159,7 +160,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: -1 */ - public static final Property VM_MIGRATE_SPEED = new Property("vm.migrate.speed", -1); + public static final Property VM_MIGRATE_SPEED = new Property<>("vm.migrate.speed", -1); /** * Sets target downtime (in ms) at end of livemigration, the 'hiccup' for final copy.
@@ -168,7 +169,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: -1 */ - public static final Property VM_MIGRATE_DOWNTIME = new Property("vm.migrate.downtime", -1); + public static final Property VM_MIGRATE_DOWNTIME = new Property<>("vm.migrate.downtime", -1); /** * Busy VMs may never finish migrating, depending on the environment.
@@ -177,7 +178,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: -1 */ - public static final Property VM_MIGRATE_PAUSEAFTER = new Property("vm.migrate.pauseafter", -1); + public static final Property VM_MIGRATE_PAUSEAFTER = new Property<>("vm.migrate.pauseafter", -1); /** * Time (in seconds) to wait for VM migration to finish. Less than 1 means disabled.
@@ -185,7 +186,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: -1 */ - public static final Property VM_MIGRATE_WAIT = new Property("vm.migrate.wait", -1); + public static final Property VM_MIGRATE_WAIT = new Property<>("vm.migrate.wait", -1); /** * Agent Hooks is the way to override default agent behavior to extend the functionality without excessive coding for a custom deployment.
@@ -197,7 +198,7 @@ public class AgentProperties{ * Data type: String.
* Default value: /etc/cloudstack/agent/hooks */ - public static final Property AGENT_HOOKS_BASEDIR = new Property("agent.hooks.basedir", "/etc/cloudstack/agent/hooks"); + public static final Property AGENT_HOOKS_BASEDIR = new Property<>("agent.hooks.basedir", "/etc/cloudstack/agent/hooks"); /** * This property is used with the agent.hooks.basedir property to define the Libvirt VM XML transformer script.
@@ -208,7 +209,7 @@ public class AgentProperties{ * Data type: String.
* Default value: libvirt-vm-xml-transformer.groovy */ - public static final Property AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_SCRIPT = new Property("agent.hooks.libvirt_vm_xml_transformer.script", "libvirt-vm-xml-transformer.groovy"); + public static final Property AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_SCRIPT = new Property<>("agent.hooks.libvirt_vm_xml_transformer.script", "libvirt-vm-xml-transformer.groovy"); /** * This property is used with the agent.hooks.basedir and agent.hooks.libvirt_vm_xml_transformer.script properties to define the Libvirt VM XML transformer method.
@@ -218,7 +219,7 @@ public class AgentProperties{ * Data type: String.
* Default value: transform */ - public static final Property AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_METHOD = new Property("agent.hooks.libvirt_vm_xml_transformer.method", "transform"); + public static final Property AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_METHOD = new Property<>("agent.hooks.libvirt_vm_xml_transformer.method", "transform"); /** * This property is used with the agent.hooks.basedir property to define the Libvirt VM on start script.
@@ -228,7 +229,7 @@ public class AgentProperties{ * Data type: String.
* Default value: libvirt-vm-state-change.groovy */ - public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_START_SCRIPT = new Property("agent.hooks.libvirt_vm_on_start.script", "libvirt-vm-state-change.groovy"); + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_START_SCRIPT = new Property<>("agent.hooks.libvirt_vm_on_start.script", "libvirt-vm-state-change.groovy"); /** * This property is used with the agent.hooks.basedir and agent.hooks.libvirt_vm_on_start.script properties to define the Libvirt VM on start method.
@@ -237,7 +238,7 @@ public class AgentProperties{ * Data type: String.
* Default value: onStart */ - public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_START_METHOD = new Property("agent.hooks.libvirt_vm_on_start.method", "onStart"); + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_START_METHOD = new Property<>("agent.hooks.libvirt_vm_on_start.method", "onStart"); /** * This property is used with the agent.hooks.basedir property to define the Libvirt VM on stop script.
@@ -247,7 +248,7 @@ public class AgentProperties{ * Data type: String.
* Default value: libvirt-vm-state-change.groovy */ - public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_STOP_SCRIPT = new Property("agent.hooks.libvirt_vm_on_stop.script", "libvirt-vm-state-change.groovy"); + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_STOP_SCRIPT = new Property<>("agent.hooks.libvirt_vm_on_stop.script", "libvirt-vm-state-change.groovy"); /** * This property is used with the agent.hooks.basedir and agent.hooks.libvirt_vm_on_stop.script properties to define the Libvirt VM on stop method.
@@ -256,7 +257,7 @@ public class AgentProperties{ * Data type: String.
* Default value: onStop */ - public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_STOP_METHOD = new Property("agent.hooks.libvirt_vm_on_stop.method", "onStop"); + public static final Property AGENT_HOOKS_LIBVIRT_VM_ON_STOP_METHOD = new Property<>("agent.hooks.libvirt_vm_on_stop.method", "onStop"); /** * Sets the type of bridge used on the hypervisor. This defines what commands the resource will use to setup networking.
@@ -264,21 +265,21 @@ public class AgentProperties{ * Data type: String.
* Default value: native */ - public static final Property NETWORK_BRIDGE_TYPE = new Property("network.bridge.type", "native"); + public static final Property NETWORK_BRIDGE_TYPE = new Property<>("network.bridge.type", "native"); /** * Sets DPDK Support on OpenVSwitch.
* Data type: Boolean.
* Default value: false */ - public static final Property OPENVSWITCH_DPDK_ENABLED = new Property("openvswitch.dpdk.enabled", false); + public static final Property OPENVSWITCH_DPDK_ENABLED = new Property<>("openvswitch.dpdk.enabled", false); /** * Sets DPDK Support on OpenVSwitch (path).
* Data type: String.
* Default value: null */ - public static final Property OPENVSWITCH_DPDK_OVS_PATH = new Property("openvswitch.dpdk.ovs.path", null, String.class); + public static final Property OPENVSWITCH_DPDK_OVS_PATH = new Property<>("openvswitch.dpdk.ovs.path", null, String.class); /** * Sets the hypervisor type.
@@ -286,14 +287,14 @@ public class AgentProperties{ * Data type: String.
* Default value: kvm */ - public static final Property HYPERVISOR_TYPE = new Property("hypervisor.type", "kvm"); + public static final Property HYPERVISOR_TYPE = new Property<>("hypervisor.type", "kvm"); /** * Specifies a directory on the host local storage for temporary storing direct download templates.
* Data type: String.
* Default value: /var/lib/libvirt/images */ - public static final Property DIRECT_DOWNLOAD_TEMPORARY_DOWNLOAD_LOCATION = new Property("direct.download.temporary.download.location", + public static final Property DIRECT_DOWNLOAD_TEMPORARY_DOWNLOAD_LOCATION = new Property<>("direct.download.temporary.download.location", "/var/lib/libvirt/images"); /** @@ -301,21 +302,21 @@ public class AgentProperties{ * Data type: String.
* Default value: /var/cache/cloud */ - public static final Property HOST_CACHE_LOCATION = new Property("host.cache.location", "/var/cache/cloud"); + public static final Property HOST_CACHE_LOCATION = new Property<>("host.cache.location", "/var/cache/cloud"); /** * Sets the rolling maintenance hook scripts directory.
* Data type: String.
* Default value: null */ - public static final Property ROLLING_MAINTENANCE_HOOKS_DIR = new Property("rolling.maintenance.hooks.dir", null, String.class); + public static final Property ROLLING_MAINTENANCE_HOOKS_DIR = new Property<>("rolling.maintenance.hooks.dir", null, String.class); /** * Disables the rolling maintenance service execution.
* Data type: Boolean.
* Default value: false */ - public static final Property ROLLING_MAINTENANCE_SERVICE_EXECUTOR_DISABLED = new Property("rolling.maintenance.service.executor.disabled", false); + public static final Property ROLLING_MAINTENANCE_SERVICE_EXECUTOR_DISABLED = new Property<>("rolling.maintenance.service.executor.disabled", false); /** * Sets the hypervisor URI.
@@ -324,7 +325,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property HYPERVISOR_URI = new Property("hypervisor.uri", null, String.class); + public static final Property HYPERVISOR_URI = new Property<>("hypervisor.uri", null, String.class); /** * Sets the driver used to plug and unplug NICs from the bridges.
@@ -336,7 +337,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property LIBVIRT_VIF_DRIVER = new Property("libvirt.vif.driver", null, String.class); + public static final Property LIBVIRT_VIF_DRIVER = new Property<>("libvirt.vif.driver", null, String.class); /** * Setting to enable direct networking in libvirt.
@@ -346,7 +347,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property NETWORK_DIRECT_SOURCE_MODE = new Property("network.direct.source.mode", null, String.class); + public static final Property NETWORK_DIRECT_SOURCE_MODE = new Property<>("network.direct.source.mode", null, String.class); /** * Setting to enable direct networking in libvirt.
@@ -355,7 +356,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property NETWORK_DIRECT_DEVICE = new Property("network.direct.device", null, String.class); + public static final Property NETWORK_DIRECT_DEVICE = new Property<>("network.direct.device", null, String.class); /** * Setting to enable the CPU model to KVM guest globally.
@@ -364,7 +365,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property GUEST_CPU_MODE = new Property("guest.cpu.mode", null, String.class); + public static final Property GUEST_CPU_MODE = new Property<>("guest.cpu.mode", null, String.class); /** * Custom CPU model. This param is only valid if property guest.cpu.mode=custom.
@@ -372,7 +373,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property GUEST_CPU_MODEL = new Property("guest.cpu.model", null, String.class); + public static final Property GUEST_CPU_MODEL = new Property<>("guest.cpu.model", null, String.class); /** * This param will set the CPU architecture for the domain to override what the management server would send.
@@ -381,7 +382,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null (will set as the default of the host's OS). */ - public static final Property GUEST_CPU_ARCH = new Property("guest.cpu.arch", null, String.class); + public static final Property GUEST_CPU_ARCH = new Property<>("guest.cpu.arch", null, String.class); /** * This param will require CPU features on the CPU section.
@@ -390,7 +391,7 @@ public class AgentProperties{ * Data type: String.
* Default value: null */ - public static final Property GUEST_CPU_FEATURES = new Property("guest.cpu.features", null, String.class); + public static final Property GUEST_CPU_FEATURES = new Property<>("guest.cpu.features", null, String.class); /** * Disables memory ballooning on VM guests for overcommit.
@@ -398,7 +399,7 @@ public class AgentProperties{ * Data type: Boolean.
* Default value: false */ - public static final Property VM_MEMBALLOON_DISABLE = new Property("vm.memballoon.disable", false); + public static final Property VM_MEMBALLOON_DISABLE = new Property<>("vm.memballoon.disable", false); /** * Set to true to check disk activity on VM's disks before starting a VM.
@@ -407,7 +408,7 @@ public class AgentProperties{ * Data type: Boolean.
* Default value: false */ - public static final Property VM_DISKACTIVITY_CHECKENABLED = new Property("vm.diskactivity.checkenabled", false); + public static final Property VM_DISKACTIVITY_CHECKENABLED = new Property<>("vm.diskactivity.checkenabled", false); /** * Timeout (in seconds) for giving up on waiting for VM's disk files to become inactive.
@@ -416,7 +417,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 120 */ - public static final Property VM_DISKACTIVITY_CHECKTIMEOUT_S = new Property("vm.diskactivity.checktimeout_s", 120); + public static final Property VM_DISKACTIVITY_CHECKTIMEOUT_S = new Property<>("vm.diskactivity.checktimeout_s", 120); /** * The length of time (in ms) that the disk needs to be inactive in order to pass the check.
@@ -426,7 +427,7 @@ public class AgentProperties{ * Data type: Long.
* Default value: 30000L */ - public static final Property VM_DISKACTIVITY_INACTIVETIME_MS = new Property("vm.diskactivity.inactivetime_ms", 30000L); + public static final Property VM_DISKACTIVITY_INACTIVETIME_MS = new Property<>("vm.diskactivity.inactivetime_ms", 30000L); /** * Some newer linux kernels are incapable of reliably migrating VMs with KVMclock.
@@ -434,14 +435,14 @@ public class AgentProperties{ * Data type: Boolean.
* Default value: false */ - public static final Property KVMCLOCK_DISABLE = new Property("kvmclock.disable", false); + public static final Property KVMCLOCK_DISABLE = new Property<>("kvmclock.disable", false); /** * This enables the VirtIO Random Number Generator device for guests.
* Data type: Boolean.
* Default value: false */ - public static final Property VM_RNG_ENABLE = new Property("vm.rng.enable", false); + public static final Property VM_RNG_ENABLE = new Property<>("vm.rng.enable", false); /** * The model of VirtIO Random Number Generator (RNG) to present to the Guest.
@@ -449,7 +450,7 @@ public class AgentProperties{ * Data type: String.
* Default value: random */ - public static final Property VM_RNG_MODEL = new Property("vm.rng.model", "random"); + public static final Property VM_RNG_MODEL = new Property<>("vm.rng.model", "random"); /** * Local Random Number Device Generator to use for VirtIO RNG for Guests.
@@ -457,28 +458,28 @@ public class AgentProperties{ * Data type: String.
* Default value: /dev/random */ - public static final Property VM_RNG_PATH = new Property("vm.rng.path", "/dev/random"); + public static final Property VM_RNG_PATH = new Property<>("vm.rng.path", "/dev/random"); /** * The amount of bytes the Guest may request/obtain from the RNG in the period specified in the property vm.rng.rate.period.
* Data type: Integer.
* Default value: 2048 */ - public static final Property VM_RNG_RATE_BYTES = new Property("vm.rng.rate.bytes", 2048); + public static final Property VM_RNG_RATE_BYTES = new Property<>("vm.rng.rate.bytes", 2048); /** * The number of milliseconds in which the guest is allowed to obtain the bytes specified in vm.rng.rate.bytes.
* Data type: Integer.
* Default value: 1000 */ - public static final Property VM_RNG_RATE_PERIOD = new Property("vm.rng.rate.period", 1000); + public static final Property VM_RNG_RATE_PERIOD = new Property<>("vm.rng.rate.period", 1000); /** * Timeout value for aggregation commands to be sent to the virtual router (in seconds).
* Data type: Long.
* Default value: null */ - public static final Property ROUTER_AGGREGATION_COMMAND_EACH_TIMEOUT = new Property("router.aggregation.command.each.timeout", null, Long.class); + public static final Property ROUTER_AGGREGATION_COMMAND_EACH_TIMEOUT = new Property<>("router.aggregation.command.each.timeout", null, Long.class); /** * Allows to virtually increase the amount of RAM (in MB) available on the host.
@@ -487,7 +488,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 0 */ - public static final Property HOST_OVERCOMMIT_MEM_MB = new Property("host.overcommit.mem.mb", 0); + public static final Property HOST_OVERCOMMIT_MEM_MB = new Property<>("host.overcommit.mem.mb", 0); /** * How much host memory (in MB) to reserve for non-allocation.
@@ -496,7 +497,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 1024 */ - public static final Property HOST_RESERVED_MEM_MB = new Property("host.reserved.mem.mb", 1024); + public static final Property HOST_RESERVED_MEM_MB = new Property<>("host.reserved.mem.mb", 1024); /** * The model of Watchdog timer to present to the Guest.
@@ -504,7 +505,7 @@ public class AgentProperties{ * Data type: String.
* Default value: i6300esb */ - public static final Property VM_WATCHDOG_MODEL = new Property("vm.watchdog.model", "i6300esb"); + public static final Property VM_WATCHDOG_MODEL = new Property<>("vm.watchdog.model", "i6300esb"); /** * Action to take when the Guest/Instance is no longer notifiying the Watchdog timer.
@@ -512,7 +513,7 @@ public class AgentProperties{ * Data type: String.
* Default value: none */ - public static final Property VM_WATCHDOG_ACTION = new Property("vm.watchdog.action", "none"); + public static final Property VM_WATCHDOG_ACTION = new Property<>("vm.watchdog.action", "none"); /** * Automatically clean up iSCSI sessions not attached to any VM.
@@ -521,7 +522,7 @@ public class AgentProperties{ * Data type: Boolean.
* Default value: false */ - public static final Property ISCSI_SESSION_CLEANUP_ENABLED = new Property("iscsi.session.cleanup.enabled", false); + public static final Property ISCSI_SESSION_CLEANUP_ENABLED = new Property<>("iscsi.session.cleanup.enabled", false); /** * Heartbeat update timeout (in ms).
@@ -529,14 +530,14 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 60000 */ - public static final Property HEARTBEAT_UPDATE_TIMEOUT = new Property("heartbeat.update.timeout", 60000); + public static final Property HEARTBEAT_UPDATE_TIMEOUT = new Property<>("heartbeat.update.timeout", 60000); /** * The timeout (in seconds) to retrieve the target's domain ID when migrating a VM with KVM.
* Data type: Integer.
* Default value: 10 */ - public static final Property VM_MIGRATE_DOMAIN_RETRIEVE_TIMEOUT = new Property("vm.migrate.domain.retrieve.timeout", 10); + public static final Property VM_MIGRATE_DOMAIN_RETRIEVE_TIMEOUT = new Property<>("vm.migrate.domain.retrieve.timeout", 10); /** * This parameter specifies if the host must be rebooted when something goes wrong with the heartbeat.
@@ -544,28 +545,28 @@ public class AgentProperties{ * Default value: true */ public static final Property REBOOT_HOST_AND_ALERT_MANAGEMENT_ON_HEARTBEAT_TIMEOUT - = new Property("reboot.host.and.alert.management.on.heartbeat.timeout", true); + = new Property<>("reboot.host.and.alert.management.on.heartbeat.timeout", true); /** * Enables manually setting CPU's topology on KVM's VM.
* Data type: Boolean.
* Default value: true */ - public static final Property ENABLE_MANUALLY_SETTING_CPU_TOPOLOGY_ON_KVM_VM = new Property("enable.manually.setting.cpu.topology.on.kvm.vm", true); + public static final Property ENABLE_MANUALLY_SETTING_CPU_TOPOLOGY_ON_KVM_VM = new Property<>("enable.manually.setting.cpu.topology.on.kvm.vm", true); /** * Manually sets the host CPU speed (in MHz), in cases where CPU scaling support detects the value is wrong.
* Data type: Integer.
* Default value: 0 */ - public static final Property HOST_CPU_MANUAL_SPEED_MHZ = new Property("host.cpu.manual.speed.mhz", 0); + public static final Property HOST_CPU_MANUAL_SPEED_MHZ = new Property<>("host.cpu.manual.speed.mhz", 0); /** * Enable manually IO driver on KVM's VM.
* Data type: Boolean.
* Default value: null */ - public static final Property ENABLE_IO_URING = new Property("enable.io.uring", null, Boolean.class); + public static final Property ENABLE_IO_URING = new Property<>("enable.io.uring", null, Boolean.class); /** * Defines the location for Hypervisor scripts.
@@ -577,7 +578,7 @@ public class AgentProperties{ * Data type: String.
* Default value: scripts/vm/hypervisor */ - public static final Property HYPERVISOR_SCRIPTS_DIR = new Property("hypervisor.scripts.dir", "scripts/vm/hypervisor"); + public static final Property HYPERVISOR_SCRIPTS_DIR = new Property<>("hypervisor.scripts.dir", "scripts/vm/hypervisor"); /** * Defines the location for KVM scripts.
@@ -589,35 +590,35 @@ public class AgentProperties{ * Data type: String.
* Default value: scripts/vm/hypervisor/kvm */ - public static final Property KVM_SCRIPTS_DIR = new Property("kvm.scripts.dir", "scripts/vm/hypervisor/kvm"); + public static final Property KVM_SCRIPTS_DIR = new Property<>("kvm.scripts.dir", "scripts/vm/hypervisor/kvm"); /** * Specifies start MAC address for private IP range.
* Data type: String.
* Default value: 00:16:3e:77:e2:a0 */ - public static final Property PRIVATE_MACADDR_START = new Property("private.macaddr.start", "00:16:3e:77:e2:a0"); + public static final Property PRIVATE_MACADDR_START = new Property<>("private.macaddr.start", "00:16:3e:77:e2:a0"); /** * Specifies start IP for private IP range.
* Data type: String.
* Default value: 192.168.166.128 */ - public static final Property PRIVATE_IPADDR_START = new Property("private.ipaddr.start", "192.168.166.128"); + public static final Property PRIVATE_IPADDR_START = new Property<>("private.ipaddr.start", "192.168.166.128"); /** * Defines Local Bridge Name.
* Data type: String.
* Default value: null */ - public static final Property PRIVATE_BRIDGE_NAME = new Property("private.bridge.name", null, String.class); + public static final Property PRIVATE_BRIDGE_NAME = new Property<>("private.bridge.name", null, String.class); /** * Defines private network name.
* Data type: String.
* Default value: null */ - public static final Property PRIVATE_NETWORK_NAME = new Property("private.network.name", null, String.class); + public static final Property PRIVATE_NETWORK_NAME = new Property<>("private.network.name", null, String.class); /** * Defines the location for network scripts.
@@ -629,7 +630,7 @@ public class AgentProperties{ * Data type: String.
* Default value: scripts/vm/network/vnet */ - public static final Property NETWORK_SCRIPTS_DIR = new Property("network.scripts.dir", "scripts/vm/network/vnet"); + public static final Property NETWORK_SCRIPTS_DIR = new Property<>("network.scripts.dir", "scripts/vm/network/vnet"); /** * Defines the location for storage scripts.
@@ -641,7 +642,7 @@ public class AgentProperties{ * Data type: String.
* Default value: scripts/storage/qcow2 */ - public static final Property STORAGE_SCRIPTS_DIR = new Property("storage.scripts.dir", "scripts/storage/qcow2"); + public static final Property STORAGE_SCRIPTS_DIR = new Property<>("storage.scripts.dir", "scripts/storage/qcow2"); /** * Time (in seconds) to wait for the VM to shutdown gracefully.
@@ -649,49 +650,49 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 120 */ - public static final Property STOP_SCRIPT_TIMEOUT = new Property("stop.script.timeout", 120); + public static final Property STOP_SCRIPT_TIMEOUT = new Property<>("stop.script.timeout", 120); /** * Definition of VMs video model type.
* Data type: String.
* Default value: null */ - public static final Property VM_VIDEO_HARDWARE = new Property("vm.video.hardware", null, String.class); + public static final Property VM_VIDEO_HARDWARE = new Property<>("vm.video.hardware", null, String.class); /** * Definition of VMs video, specifies the amount of RAM in kibibytes (blocks of 1024 bytes).
* Data type: Integer.
* Default value: 0 */ - public static final Property VM_VIDEO_RAM = new Property("vm.video.ram", 0); + public static final Property VM_VIDEO_RAM = new Property<>("vm.video.ram", 0); /** * System VM ISO path.
* Data type: String.
* Default value: null */ - public static final Property SYSTEMVM_ISO_PATH = new Property("systemvm.iso.path", null, String.class); + public static final Property SYSTEMVM_ISO_PATH = new Property<>("systemvm.iso.path", null, String.class); /** * If set to "true", allows override of the properties: private.macaddr.start, private.ipaddr.start, private.ipaddr.end.
* Data type: Boolean.
* Default value: false */ - public static final Property DEVELOPER = new Property("developer", false); + public static final Property DEVELOPER = new Property<>("developer", false); /** * Can only be used if developer = true. This property is used to define the local bridge name and private network name.
* Data type: String.
* Default value: null */ - public static final Property INSTANCE = new Property("instance", null, String.class); + public static final Property INSTANCE = new Property<>("instance", null, String.class); /** * Shows the path to the base directory in which NFS servers are going to be mounted.
* Data type: String.
* Default value: /mnt */ - public static final Property MOUNT_PATH = new Property("mount.path", "/mnt"); + public static final Property MOUNT_PATH = new Property<>("mount.path", "/mnt"); public static class Property { private String name; diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 6f94029519ef..016caf1b5aad 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -325,7 +325,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv public final static String CONFIG_DIR = "config"; private boolean enableIoUring; - private final static String ENABLE_IO_URING_PROPERTY = "enable.io.uring"; public static final String BASH_SCRIPT_PATH = "/bin/bash"; @@ -982,11 +981,11 @@ public boolean configure(final String name, final Map params) th _videoRam = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_VIDEO_RAM); // Reserve 1GB unless admin overrides - _dom0MinMem = ByteScaleUtils.mibToBytes((long) AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB)); + _dom0MinMem = ByteScaleUtils.mibToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB)); // Support overcommit memory for host if host uses ZSWAP, KSM and other memory // compressing technologies - _dom0OvercommitMem = ByteScaleUtils.mibToBytes((long) AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB)); + _dom0OvercommitMem = ByteScaleUtils.mibToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB)); if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVMCLOCK_DISABLE)) { _noKvmClock = true; @@ -1055,7 +1054,7 @@ public boolean configure(final String name, final Map params) th } // Enable/disable IO driver for Qemu (in case it is not set CloudStack can also detect if its supported by qemu) - boolean enableIoUringConfig = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ENABLE_IO_URING); + Boolean enableIoUringConfig = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ENABLE_IO_URING); enableIoUring = isIoUringEnabled(enableIoUringConfig); s_logger.info("IO uring driver for Qemu: " + (enableIoUring ? "enabled" : "disabled")); @@ -1146,7 +1145,7 @@ public boolean configure(final String name, final Map params) th _migrateWait = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_WAIT); - configureAgentHooks(params); + configureAgentHooks(); _migrateSpeed = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_SPEED); if (_migrateSpeed == -1) { @@ -1174,7 +1173,7 @@ public boolean configure(final String name, final Map params) th getVifDriver(TrafficType.Control).createControlNetwork(_linkLocalBridgeName); - configureDiskActivityChecks(params); + configureDiskActivityChecks(); final KVMStorageProcessor storageProcessor = new KVMStorageProcessor(_storagePoolMgr, this); storageProcessor.configure(name, params); @@ -1272,11 +1271,10 @@ public boolean configureHostParams(final Map params) { return true; } - private void configureAgentHooks(final Map params) { + private void configureAgentHooks() { _agentHooksBasedir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_BASEDIR); s_logger.debug("agent.hooks.basedir is " + _agentHooksBasedir); - _agentHooksLibvirtXmlScript = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.AGENT_HOOKS_LIBVIRT_VM_XML_TRANSFORMER_SCRIPT); s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.script is " + _agentHooksLibvirtXmlScript); @@ -1325,7 +1323,7 @@ private void loadUefiProperties() throws FileNotFoundException { } } - protected void configureDiskActivityChecks(final Map params) { + protected void configureDiskActivityChecks() { _diskActivityCheckEnabled = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_DISKACTIVITY_CHECKENABLED); if (_diskActivityCheckEnabled) { final int timeout = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_DISKACTIVITY_CHECKTIMEOUT_S); From c3b717bd5b3cd52c9869780c839e583ca2606a63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Jandre?= <48719461+JoaoJandre@users.noreply.github.com> Date: Mon, 4 Jul 2022 12:33:41 -0300 Subject: [PATCH 06/23] Address review --- agent/src/main/java/com/cloud/agent/Agent.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent/src/main/java/com/cloud/agent/Agent.java b/agent/src/main/java/com/cloud/agent/Agent.java index 3379c439ba97..01d74ae9b1f8 100644 --- a/agent/src/main/java/com/cloud/agent/Agent.java +++ b/agent/src/main/java/com/cloud/agent/Agent.java @@ -180,7 +180,7 @@ public Agent(final IAgentShell shell, final int localAgentId, final ServerResour _id = value != null ? Long.parseLong(value) : null; s_logger.info("id is " + (_id != null ? _id : "")); - final Map params = new HashMap(); + final Map params = new HashMap<>(); // merge with properties from command line to let resource access command line parameters for (final Map.Entry cmdLineProp : _shell.getCmdLineProperties().entrySet()) { From 948212d250c4b5c1278c1596a81718b238aea802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Jandre?= <48719461+JoaoJandre@users.noreply.github.com> Date: Wed, 6 Jul 2022 12:12:37 -0300 Subject: [PATCH 07/23] Address some code smells. --- .../main/java/com/cloud/agent/properties/AgentProperties.java | 4 +++- .../hypervisor/kvm/resource/LibvirtComputingResource.java | 4 ---- .../java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java | 2 -- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 02cb882c6472..e601159e6071 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -14,6 +14,8 @@ */ package com.cloud.agent.properties; +import com.cloud.utils.exception.CloudRuntimeException; + /** * Class of constant agent's properties available to configure on * "agent.properties". @@ -717,7 +719,7 @@ private void init(String name, T defaultValue) { } if (this.typeClass == null) { - throw new RuntimeException("Could not \"discover\" the type class. If you are using \"Null\" as the default value, you must enter the Type class."); + throw new CloudRuntimeException("Could not \"discover\" the type class. If you are using \"Null\" as the default value, you must enter the Type class."); } } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 016caf1b5aad..e74ce06ddec6 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -925,10 +925,6 @@ public boolean configure(final String name, final Map params) th _networkDirectSourceMode = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_DIRECT_SOURCE_MODE); _networkDirectDevice = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_DIRECT_DEVICE); - String startMac = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_MACADDR_START); - - String startIp = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PRIVATE_IPADDR_START); - _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh"); if (_pingTestPath == null) { throw new ConfigurationException("Unable to find the pingtest.sh"); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index b97cfd5ab905..236e7d47edaf 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -55,8 +55,6 @@ public void configure(Map params) throws ConfigurationException getPifs(); - String networkScriptsDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.NETWORK_SCRIPTS_DIR); - if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_ENABLED)) { dpdkDriver = new DpdkDriverImpl(); } From ad433ef0bddaf92f888d66bd6ee9c01818b33c81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Jandre?= <48719461+JoaoJandre@users.noreply.github.com> Date: Wed, 6 Jul 2022 12:41:55 -0300 Subject: [PATCH 08/23] Address more code smells --- .../kvm/resource/LibvirtComputingResource.java | 17 ++++------------- .../hypervisor/kvm/resource/OvsVifDriver.java | 3 ++- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index e74ce06ddec6..0a4c57bfc561 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -300,9 +300,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv private String _ovsPvlanVmPath; private String _routerProxyPath; private String _ovsTunnelPath; - private String _host; private String _dcId; - private String _pod; private String _clusterId; private final Properties _uefiProperties = new Properties(); @@ -328,7 +326,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv public static final String BASH_SCRIPT_PATH = "/bin/bash"; - private String _mountPoint = "/mnt"; private StorageLayer _storage; private KVMStoragePoolManager _storagePoolMgr; @@ -795,7 +792,7 @@ public boolean configure(final String name, final Map params) th _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); Boolean dpdk = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_ENABLED); - if (_bridgeType == BridgeType.OPENVSWITCH && dpdk) { + if (_bridgeType == BridgeType.OPENVSWITCH && BooleanUtils.isTrue(dpdk)) { dpdkSupport = true; dpdkOvsPath = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_OVS_PATH); if (dpdkOvsPath != null && !dpdkOvsPath.endsWith("/")) { @@ -816,12 +813,8 @@ public boolean configure(final String name, final Map params) th return false; } - _host = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST); - _dcId = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ZONE); - _pod = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.POD); - _clusterId = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CLUSTER); _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, VRScripts.UPDATE_HOST_PASSWD); @@ -914,7 +907,7 @@ public boolean configure(final String name, final Map params) th _hypervisorType = HypervisorType.getType(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HYPERVISOR_TYPE)); String hooksDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROLLING_MAINTENANCE_HOOKS_DIR); - rollingMaintenanceExecutor = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROLLING_MAINTENANCE_SERVICE_EXECUTOR_DISABLED) ? new RollingMaintenanceAgentExecutor(hooksDir) : + rollingMaintenanceExecutor = BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROLLING_MAINTENANCE_SERVICE_EXECUTOR_DISABLED)) ? new RollingMaintenanceAgentExecutor(hooksDir) : new RollingMaintenanceServiceExecutor(hooksDir); _hypervisorURI = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HYPERVISOR_URI); @@ -983,11 +976,11 @@ public boolean configure(final String name, final Map params) th // compressing technologies _dom0OvercommitMem = ByteScaleUtils.mibToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB)); - if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVMCLOCK_DISABLE)) { + if (BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVMCLOCK_DISABLE))) { _noKvmClock = true; } - if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_ENABLE)) { + if (BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_ENABLE))) { _rngEnable = true; _rngBackendModel = RngBackendModel.valueOf(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_RNG_MODEL).toUpperCase()); @@ -1133,8 +1126,6 @@ public boolean configure(final String name, final Map params) th s_logger.warn("No default IPv4 gateway found"); } - _mountPoint = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.MOUNT_PATH); - _migrateDowntime = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_DOWNTIME); _migratePauseAfter = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_MIGRATE_PAUSEAFTER); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java index 236e7d47edaf..c6867b3c1463 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java @@ -28,6 +28,7 @@ import com.cloud.hypervisor.kvm.dpdk.DpdkDriverImpl; import com.cloud.hypervisor.kvm.dpdk.DpdkHelper; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.libvirt.LibvirtException; @@ -55,7 +56,7 @@ public void configure(Map params) throws ConfigurationException getPifs(); - if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_ENABLED)) { + if (BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.OPENVSWITCH_DPDK_ENABLED))) { dpdkDriver = new DpdkDriverImpl(); } From 0afd273b3cfc476158c1d56638e2d073745e09c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Jandre?= <48719461+JoaoJandre@users.noreply.github.com> Date: Wed, 6 Jul 2022 12:44:16 -0300 Subject: [PATCH 09/23] Addressed rename variables code smells --- .../hypervisor/kvm/resource/LibvirtComputingResource.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 0a4c57bfc561..e91983ee1029 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -950,8 +950,8 @@ public boolean configure(final String name, final Map params) th configureLocalStorage(); /* Directory to use for Qemu sockets like for the Qemu Guest Agent */ - String _qemuSocketsPathVar = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.QEMU_SOCKETS_PATH); - _qemuSocketsPath = new File(_qemuSocketsPathVar); + String qemuSocketsPathVar = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.QEMU_SOCKETS_PATH); + _qemuSocketsPath = new File(qemuSocketsPathVar); // This value is never set. Default value is always used. String value = (String)params.get("scripts.timeout"); @@ -1166,9 +1166,9 @@ public boolean configure(final String name, final Map params) th storageProcessor.configure(name, params); storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor); - Boolean _iscsiCleanUpEnabled = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ISCSI_SESSION_CLEANUP_ENABLED); + Boolean iscsiCleanUpEnabled = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ISCSI_SESSION_CLEANUP_ENABLED); - if (BooleanUtils.isTrue(_iscsiCleanUpEnabled)) { + if (BooleanUtils.isTrue(iscsiCleanUpEnabled)) { IscsiStorageCleanupMonitor isciCleanupMonitor = new IscsiStorageCleanupMonitor(); final Thread cleanupMonitor = new Thread(isciCleanupMonitor); cleanupMonitor.start(); From dd8dd6bea74228f0e4b045251b255694b603670a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Jandre?= <48719461+JoaoJandre@users.noreply.github.com> Date: Fri, 8 Jul 2022 13:12:30 -0300 Subject: [PATCH 10/23] address reviews --- .../cloud/resource/ServerResourceBaseTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java b/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java index eb7d5a573823..d9df73fb9b14 100644 --- a/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java +++ b/core/src/test/java/com/cloud/resource/ServerResourceBaseTest.java @@ -1,3 +1,19 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. package com.cloud.resource; import com.cloud.utils.net.NetUtils; From 951b181464c3e4dd29158228a8d995f3e219b695 Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Wed, 10 Aug 2022 17:21:40 -0300 Subject: [PATCH 11/23] Add unit test to validate class initialization --- .../agent/properties/AgentProperties.java | 7 ---- .../agent/properties/AgentPropertiesTest.java | 41 +++++++++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index e601159e6071..7c874d22a526 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -14,8 +14,6 @@ */ package com.cloud.agent.properties; -import com.cloud.utils.exception.CloudRuntimeException; - /** * Class of constant agent's properties available to configure on * "agent.properties". @@ -717,11 +715,6 @@ private void init(String name, T defaultValue) { if (defaultValue != null) { this.typeClass = (Class)defaultValue.getClass(); } - - if (this.typeClass == null) { - throw new CloudRuntimeException("Could not \"discover\" the type class. If you are using \"Null\" as the default value, you must enter the Type class."); - } - } public String getName() { diff --git a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java new file mode 100644 index 000000000000..d2cdc231df84 --- /dev/null +++ b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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. + */ + +package com.cloud.agent.properties; + +import org.junit.Test; + +import java.lang.reflect.Field; + +public class AgentPropertiesTest { + + @Test + public void initTestBlockInstanceWithNullValueAndWithoutType() throws IllegalAccessException { + Field[] fields = AgentProperties.class.getDeclaredFields(); + for (Field field : fields) { + if (field.getType().equals(AgentProperties.Property.class)) { + AgentProperties.Property property = (AgentProperties.Property) field.get(null); + + if (property.getDefaultValue() == null && property.getTypeClass() == null) { + throw new AssertionError(String.format("Either inform the default value or the class of property [%s], field [%s].", property.getName(), field.getName())); + } + } + } + } +} From 601cac9e84e3e7f45a04f1232bff9c8d2113c19a Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Thu, 11 Aug 2022 16:50:35 -0300 Subject: [PATCH 12/23] Use AgentPropertiesFileHandler in AgentShell --- agent/conf/agent.properties | 7 + .../main/java/com/cloud/agent/AgentShell.java | 106 +++--- .../java/com/cloud/agent/IAgentShell.java | 1 - .../agent/properties/AgentProperties.java | 17 +- .../java/com/cloud/agent/AgentShellTest.java | 311 ++++++++++++++++++ 5 files changed, 389 insertions(+), 53 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index b06b90dc61a6..9f26ca6e1ac5 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -445,3 +445,10 @@ iscsi.session.cleanup.enabled=false # Shows the path to the base directory in which NFS servers are going to be mounted. # Default value: /mnt #mount.path=/mnt + +# Port listened by the console proxy. +# Default value: 443 +#consoleproxy.httpListenPort=443 + +# Default value: 5 +#ping.retries=5 diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index 4973cd745df2..126a5dcaf385 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -19,9 +19,10 @@ import com.cloud.agent.Agent.ExitStatus; import com.cloud.agent.dao.StorageComponent; import com.cloud.agent.dao.impl.PropertiesStorage; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import com.cloud.resource.ServerResource; import com.cloud.utils.LogUtils; -import com.cloud.utils.NumbersUtil; import com.cloud.utils.ProcessUtil; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.backoff.BackoffAlgorithm; @@ -265,75 +266,80 @@ protected boolean parseCommand(final String[] args) throws ConfigurationExceptio } } - if (port == null) { - port = getProperty(null, "port"); - } - - _port = NumberUtils.toInt(port, 8250); + setHost(host); - _proxyPort = NumberUtils.toInt(getProperty(null, "consoleproxy.httpListenPort"), 443); + _guid = getGuid(guid); + _port = getPortOrWorkers(port, AgentProperties.PORT); + _workers = getWorkers(workers); + _zone = getZoneOrPod(zone, AgentProperties.ZONE); + _pod = getZoneOrPod(pod, AgentProperties.POD); - if (workers == null) { - workers = getProperty(null, "workers"); - } + _proxyPort = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CONSOLEPROXY_HTTPLISTENPORT); + _pingRetries = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.PING_RETRIES); + preferredHostCheckInterval = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_LB_CHECK_INTERVAL); - _workers = NumberUtils.toInt(workers, 5); - if (_workers <= 0) { - _workers = 5; - } + return true; + } + protected void setHost(String host) throws ConfigurationException { if (host == null) { - host = getProperty(null, "host"); + host = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST); } - if (host == null) { - host = "localhost"; + if (isValueStartingAndEndingWithAtSign(host)) { + throw new ConfigurationException(String.format("Host [%s] is not configured correctly.", host)); } setHosts(host); + } - if (zone != null) - _zone = zone; - else - _zone = getProperty(null, "zone"); - if (_zone == null || (_zone.startsWith("@") && _zone.endsWith("@"))) { - _zone = "default"; + protected boolean isValueStartingAndEndingWithAtSign(String value) { + return value.startsWith("@") && value.endsWith("@"); + } + + protected String getGuid(String guid) throws ConfigurationException { + guid = StringUtils.defaultString(guid, AgentPropertiesFileHandler.getPropertyValue(AgentProperties.GUID)); + if (guid != null) { + return guid; } - if (pod != null) - _pod = pod; - else - _pod = getProperty(null, "pod"); - if (_pod == null || (_pod.startsWith("@") && _pod.endsWith("@"))) { - _pod = "default"; + if (!AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER)) { + throw new ConfigurationException("Unable to find the guid"); } - if (_host == null || (_host.startsWith("@") && _host.endsWith("@"))) { - throw new ConfigurationException("Host is not configured correctly: " + _host); + return UUID.randomUUID().toString(); + } + + protected String getZoneOrPod(String zoneOrPod, AgentProperties.Property property) { + String value = zoneOrPod; + + if (value == null) { + value = AgentPropertiesFileHandler.getPropertyValue(property); } - final String retries = getProperty(null, "ping.retries"); - _pingRetries = NumbersUtil.parseInt(retries, 5); + if (isValueStartingAndEndingWithAtSign(value)) { + value = property.getDefaultValue(); + } - String value = getProperty(null, "developer"); - boolean developer = Boolean.parseBoolean(value); + return value; + } - if (guid != null) - _guid = guid; - else - _guid = getProperty(null, "guid"); - if (_guid == null) { - if (!developer) { - throw new ConfigurationException("Unable to find the guid"); - } - _guid = UUID.randomUUID().toString(); - _properties.setProperty("guid", _guid); + protected int getWorkers(String workersString) { + int workers = getPortOrWorkers(workersString, AgentProperties.WORKERS); + + if (workers <= 0) { + workers = AgentProperties.WORKERS.getDefaultValue(); } - String val = getProperty(null, preferredHostIntervalKey); - preferredHostCheckInterval = StringUtils.isEmpty(val) ? null : Long.valueOf(val); + return workers; + } + + protected int getPortOrWorkers(String portOrWorkers, AgentProperties.Property property) { + if (portOrWorkers == null) { + return AgentPropertiesFileHandler.getPropertyValue(property); + } - return true; + return NumberUtils.toInt(portOrWorkers, property.getDefaultValue()); } @Override @@ -398,7 +404,7 @@ public void init(String[] args) throws ConfigurationException { } private void launchAgent() throws ConfigurationException { - String resourceClassNames = getProperty(null, "resource"); + String resourceClassNames = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.RESOURCE); s_logger.trace("resource=" + resourceClassNames); if (resourceClassNames != null) { launchAgentFromClassInfo(resourceClassNames); @@ -482,7 +488,7 @@ public void start() { String instance = getProperty(null, "instance"); if (instance == null) { - if (Boolean.parseBoolean(getProperty(null, "developer"))) { + if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER)) { instance = UUID.randomUUID().toString(); } else { instance = ""; diff --git a/agent/src/main/java/com/cloud/agent/IAgentShell.java b/agent/src/main/java/com/cloud/agent/IAgentShell.java index 5d389a07041b..2dd08fffd459 100644 --- a/agent/src/main/java/com/cloud/agent/IAgentShell.java +++ b/agent/src/main/java/com/cloud/agent/IAgentShell.java @@ -26,7 +26,6 @@ public interface IAgentShell { String hostLbAlgorithmSeparator = "@"; - String preferredHostIntervalKey = "host.lb.check.interval"; Map getCmdLineProperties(); diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 7c874d22a526..dcb50d266ed6 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -46,7 +46,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 5 */ - public static final Property WORKERS = new Property<>("workers", 5); + public static Property WORKERS = new Property<>("workers", 5); /** * The IP address of the management server.
@@ -62,7 +62,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: null */ - public static final Property HOST_LB_CHECK_INTERVAL = new Property<>("host.lb.check.interval", null, Integer.class); + public static final Property HOST_LB_CHECK_INTERVAL = new Property<>("host.lb.check.interval", null, Long.class); /** * The port that the management server is listening on.
@@ -694,6 +694,19 @@ public class AgentProperties{ */ public static final Property MOUNT_PATH = new Property<>("mount.path", "/mnt"); + /** + * Port listened by the console proxy. + * Data type: Integer.
+ * Default value: 443 + */ + public static final Property CONSOLEPROXY_HTTPLISTENPORT = new Property<>("consoleproxy.httpListenPort", 443); + + /** + * Data type: Integer.
+ * Default value: 5 + */ + public static final Property PING_RETRIES = new Property<>("ping.retries", 5); + public static class Property { private String name; private T defaultValue; diff --git a/agent/src/test/java/com/cloud/agent/AgentShellTest.java b/agent/src/test/java/com/cloud/agent/AgentShellTest.java index 868293c8977b..53159a191721 100644 --- a/agent/src/test/java/com/cloud/agent/AgentShellTest.java +++ b/agent/src/test/java/com/cloud/agent/AgentShellTest.java @@ -17,17 +17,42 @@ package com.cloud.agent; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import javax.naming.ConfigurationException; +import com.cloud.agent.properties.AgentProperties; +import com.cloud.agent.properties.AgentPropertiesFileHandler; import org.junit.Assert; import org.junit.Test; import com.cloud.utils.StringUtils; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +@RunWith(PowerMockRunner.class) public class AgentShellTest { + + @Spy + AgentShell agentShellSpy = new AgentShell(); + + @Mock + AgentProperties.Property propertyIntegerMock; + + @Mock + AgentProperties.Property propertyStringMock; + + @Mock + UUID uuidMock; + @Test public void parseCommand() throws ConfigurationException { AgentShell shell = new AgentShell(); @@ -59,4 +84,290 @@ public void testGetHost() { } Assert.assertEquals(shell.getNextHost(), hosts.get(0)); } + + @Test + public void isValueStartingAndEndingWithAtSignTestValues() { + Map valuesAndExpects = new HashMap<>(); + valuesAndExpects.put("@test@", true); + valuesAndExpects.put("test@", false); + valuesAndExpects.put("@test", false); + valuesAndExpects.put("test", false); + valuesAndExpects.put("te@st", false); + + valuesAndExpects.forEach((value, expected) -> { + boolean result = agentShellSpy.isValueStartingAndEndingWithAtSign(value); + if (expected != result) { + throw new AssertionError(String.format("Test with value [%s] does not returned as expected. Expected: [%s], Result: [%s].", value, expected, result)); + } + }); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getPortOrWorkersTestValueIsNullGetFromProperty() { + int expected = 195; + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn(expected); + + int result = agentShellSpy.getPortOrWorkers(null, propertyIntegerMock); + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getPortOrWorkersTestValueIsNotAValidIntegerReturnDefaultFromProperty() { + int expected = 42; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + Mockito.doReturn(expected).when(propertyIntegerMock).getDefaultValue(); + + int result = agentShellSpy.getPortOrWorkers("test", propertyIntegerMock); + Assert.assertEquals(expected, result); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.never()); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getPortOrWorkersTestValueIsAValidIntegerReturnValue() { + int expected = 42; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + Mockito.doReturn(79).when(propertyIntegerMock).getDefaultValue(); + + int result = agentShellSpy.getPortOrWorkers(String.valueOf(expected), propertyIntegerMock); + Assert.assertEquals(expected, result); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.never()); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + } + + @Test + @PrepareForTest(AgentProperties.class) + public void getWorkersTestWorkersLessThan0ReturnDefault() { + int expected = 42; + + PowerMockito.mockStatic(AgentProperties.class); + AgentProperties.WORKERS = propertyIntegerMock; + + Mockito.doReturn(-1).when(agentShellSpy).getPortOrWorkers(Mockito.any(), Mockito.any()); + Mockito.doReturn(expected).when(propertyIntegerMock).getDefaultValue(); + + int result = agentShellSpy.getWorkers(""); + + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest(AgentProperties.class) + public void getWorkersTestWorkersEqualTo0ReturnDefault() { + int expected = 42; + + PowerMockito.mockStatic(AgentProperties.class); + AgentProperties.WORKERS = propertyIntegerMock; + + Mockito.doReturn(0).when(agentShellSpy).getPortOrWorkers(Mockito.any(), Mockito.any()); + Mockito.doReturn(expected).when(propertyIntegerMock).getDefaultValue(); + + int result = agentShellSpy.getWorkers(""); + + Assert.assertEquals(expected, result); + } + + @Test + public void getWorkersTestWorkersHigherThan0ReturnValue() { + int expected = 1; + Mockito.doReturn(expected).when(agentShellSpy).getPortOrWorkers(Mockito.any(), Mockito.any()); + + int result = agentShellSpy.getWorkers(""); + + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getZoneOrPodTestValueIsNullAndPropertyStartsAndEndsWithAtSignReturnPropertyDefaultValue() { + String expected = "default"; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn("test"); + + Mockito.doReturn(true).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + Mockito.doReturn(expected).when(propertyStringMock).getDefaultValue(); + + String result = agentShellSpy.getZoneOrPod(null, propertyStringMock); + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getZoneOrPodTestValueIsNullAndPropertyDoesNotStartAndEndWithAtSignReturnPropertyDefaultValue() { + String expected = "test"; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn(expected); + + Mockito.doReturn(false).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + Mockito.doReturn("default").when(propertyStringMock).getDefaultValue(); + + String result = agentShellSpy.getZoneOrPod(null, propertyStringMock); + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getZoneOrPodTestValueIsNotNullAndStartsAndEndsWithAtSignReturnPropertyDefaultValue() { + String expected = "default"; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + + Mockito.doReturn(true).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + Mockito.doReturn(expected).when(propertyStringMock).getDefaultValue(); + + String result = agentShellSpy.getZoneOrPod("test", propertyStringMock); + Assert.assertEquals(expected, result); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.never()); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getZoneOrPodTestValueIsNotNullAndDoesNotStartAndEndWithAtSignReturnPropertyDefaultValue() { + String expected = "test"; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + + Mockito.doReturn(false).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + Mockito.doReturn("default").when(propertyStringMock).getDefaultValue(); + + String result = agentShellSpy.getZoneOrPod(expected, propertyStringMock); + Assert.assertEquals(expected, result); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.never()); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + } + + @Test + public void getGuidTestGuidNotNullReturnIt() throws ConfigurationException { + String expected = "test"; + String result = agentShellSpy.getGuid(expected); + + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getGuidTestGuidIsNullReturnProperty() throws ConfigurationException { + String expected = "test"; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn(expected); + + String result = agentShellSpy.getGuid(null); + + Assert.assertEquals(expected, result); + } + + @Test + @PrepareForTest({AgentShell.class, AgentPropertiesFileHandler.class}) + public void getGuidTestGuidAndPropertyAreNullIsDeveloperGenerateNewUuid() throws ConfigurationException { + String expected = "test"; + + PowerMockito.mockStatic(AgentPropertiesFileHandler.class, UUID.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn(null, true); + PowerMockito.when(UUID.randomUUID()).thenReturn(uuidMock); + Mockito.doReturn(expected).when(uuidMock).toString(); + + String result = agentShellSpy.getGuid(null); + + Assert.assertEquals(expected, result); + } + + @Test(expected = ConfigurationException.class) + @PrepareForTest(AgentPropertiesFileHandler.class) + public void getGuidTestGuidAndPropertyAreNullIsNotDeveloperThrowConfigurationException() throws ConfigurationException { + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn(null, false); + + agentShellSpy.getGuid(null); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void setHostTestValueIsNotNullAndStartsAndEndsWithAtSignThrowConfigurationException(){ + Mockito.doReturn(true).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + + boolean error = false; + + try { + agentShellSpy.setHost("test"); + } catch (ConfigurationException e) { + error = true; + } + + if (!error) { + throw new AssertionError("This test expects a ConfigurationException."); + } + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.never()); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void setHostTestValueIsNullPropertyStartsAndEndsWithAtSignThrowConfigurationException(){ + Mockito.doReturn(true).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn("test"); + + boolean error = false; + + try { + agentShellSpy.setHost(null); + } catch (ConfigurationException e) { + error = true; + } + + if (!error) { + throw new AssertionError("This test expects a ConfigurationException."); + } + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void setHostTestValueIsNotNullAndDoesNotStartAndEndWithAtSignSetHosts() throws ConfigurationException { + String expected = "test"; + Mockito.doReturn(false).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + + agentShellSpy.setHost(expected); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class, Mockito.never()); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + + Mockito.verify(agentShellSpy).setHosts(expected); + } + + @Test + @PrepareForTest(AgentPropertiesFileHandler.class) + public void setHostTestValueIsNullPropertyDoesNotStartAndEndWithAtSignSetHosts() throws ConfigurationException { + String expected = "test"; + + Mockito.doReturn(false).when(agentShellSpy).isValueStartingAndEndingWithAtSign(Mockito.any()); + PowerMockito.mockStatic(AgentPropertiesFileHandler.class); + PowerMockito.when(AgentPropertiesFileHandler.getPropertyValue(Mockito.any())).thenReturn(expected); + + agentShellSpy.setHost(null); + + PowerMockito.verifyStatic(AgentPropertiesFileHandler.class); + AgentPropertiesFileHandler.getPropertyValue(Mockito.any()); + + Mockito.verify(agentShellSpy).setHosts(expected); + } } From 3d0f3cf9c143a25efc2c6704dd8157ed360a951d Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Fri, 12 Aug 2022 16:56:48 -0300 Subject: [PATCH 13/23] Improve tests --- agent/src/test/java/com/cloud/agent/AgentShellTest.java | 4 +--- .../com/cloud/agent/properties/AgentPropertiesTest.java | 6 +++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/agent/src/test/java/com/cloud/agent/AgentShellTest.java b/agent/src/test/java/com/cloud/agent/AgentShellTest.java index 53159a191721..29fb6c5ab7b3 100644 --- a/agent/src/test/java/com/cloud/agent/AgentShellTest.java +++ b/agent/src/test/java/com/cloud/agent/AgentShellTest.java @@ -96,9 +96,7 @@ public void isValueStartingAndEndingWithAtSignTestValues() { valuesAndExpects.forEach((value, expected) -> { boolean result = agentShellSpy.isValueStartingAndEndingWithAtSign(value); - if (expected != result) { - throw new AssertionError(String.format("Test with value [%s] does not returned as expected. Expected: [%s], Result: [%s].", value, expected, result)); - } + Assert.assertEquals(String.format("Test with value [%s] does not return as expected.", value), expected, result); }); } diff --git a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java index d2cdc231df84..a0a4f7702aec 100644 --- a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java +++ b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java @@ -19,6 +19,7 @@ package com.cloud.agent.properties; +import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Field; @@ -32,9 +33,8 @@ public void initTestBlockInstanceWithNullValueAndWithoutType() throws IllegalAcc if (field.getType().equals(AgentProperties.Property.class)) { AgentProperties.Property property = (AgentProperties.Property) field.get(null); - if (property.getDefaultValue() == null && property.getTypeClass() == null) { - throw new AssertionError(String.format("Either inform the default value or the class of property [%s], field [%s].", property.getName(), field.getName())); - } + Assert.assertTrue(String.format("Either inform the default value or the class of property [%s], field [%s].", property.getName(), field.getName()), + property.getDefaultValue() != null || property.getTypeClass() != null); } } } From 217e289a3d2082e28665e48d928f2ad8bf32804a Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Fri, 12 Aug 2022 17:01:30 -0300 Subject: [PATCH 14/23] Remove unnecessary comments on agent.properties --- agent/conf/agent.properties | 60 ------------------------------------- 1 file changed, 60 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index 9f26ca6e1ac5..b6bb79160c27 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -22,15 +22,12 @@ guid= # The java class which the agent loads to execute. -# Default value: com.cloud.hypervisor.kvm.resource.LibvirtComputingResource resource=com.cloud.hypervisor.kvm.resource.LibvirtComputingResource # The number of threads running in the agent. -# Default value: 5 workers=5 # The IP address of the management server. -# Default value: localhost host=localhost # The time interval (in seconds) after which agent will check if the connected host @@ -43,48 +40,38 @@ host=localhost # the agent as the preferred host check interval, however, if the following setting # is defined it will override the received value. The value 0 and lb algorithm 'shuffle' # disables this background task. -# Default value: 0 #host.lb.check.interval=0 # The port that the management server is listening on. -# Default value = 8250 port=8250 # The cluster which the agent belongs to. -# Default value: default cluster=default # The pod which the agent belongs to. -# Default value: default pod=default # The zone which the agent belongs to. -# Default value: default zone=default # The public NIC device. # If this is commented, it will be autodetected on service startup. -# Default value: cloudbr0 #public.network.device=cloudbr0 # The private NIC device. # If this is commented, it will be autodetected on service startup. -# Default value: cloudbr1 #private.network.device=cloudbr1 # The guest NIC device. # If this is commented, the value of the private NIC device will be used. -# Default value: the private NIC device value #guest.network.device= # Local storage path. Multiple values can be entered and separated by commas. -# Default value: /var/lib/libvirt/images/ #local.storage.path=/var/lib/libvirt/images/ # Directory where Qemu sockets are placed. # These sockets are for the Qemu Guest Agent and SSVM provisioning. # Make sure that AppArmor or SELinux allow libvirt to write there. -# Default value: /var/lib/libvirt/qemu #qemu.sockets.path=/var/lib/libvirt/qemu # MANDATORY: The UUID for the local storage pool. Multiple values can be entered and separated by commas. @@ -93,37 +80,31 @@ local.storage.uuid= # Location for KVM virtual router scripts. # The path defined in this property is relative to the directory "/usr/share/cloudstack-common/". -# Default value: scripts/network/domr/kvm domr.scripts.dir=scripts/network/domr/kvm # The timeout (in ms) for time-consuming operations, such as create/copy a snapshot. -# Default value: 7200 #cmds.timeout=7200 # This parameter sets the VM migration speed. # By default, it will try to guess the speed of the guest network and consume all possible bandwidth. # The default value is -1, which means that the agent will use all possible bandwidth. # When entering a value, make sure to enter it in megabytes per second. -# Default value: -1 #vm.migrate.speed=-1 # Sets target downtime (in ms) at end of livemigration, the 'hiccup' for final copy. # Higher numbers make livemigration easier, lower numbers may cause migration to never complete. # Less than 1 means hypervisor default (20ms). -# Default value: -1 #vm.migrate.downtime=-1 # Busy VMs may never finish migrating, depending on environment. # Therefore, if configured, this option will pause the VM after the time entered (in ms) to force the migration to finish. # Less than 1 means disabled. -# Default value: -1 #vm.migrate.pauseafter=-1 # Time (in seconds) to wait for VM migraton to finish. Less than 1 means disabled. # If the VM migration is not finished in the time, the VM job will be cancelled by libvirt. # It will be configured by cloudstack management server when cloudstack agent connects. # please change the global setting 'migratewait' if needed (migratewait default value: 3600). -# Default value: -1 #vm.migrate.wait=-1 # ---------------- AGENT HOOKS ----------------- @@ -137,7 +118,6 @@ domr.scripts.dir=scripts/network/domr/kvm # that keeps default CS behavior if something goes wrong. # All hooks are located in a special directory defined in 'agent.hooks.basedir'. -# Default value: /etc/cloudstack/agent/hooks # agent.hooks.basedir=/etc/cloudstack/agent/hooks # Every hook has two major attributes - script name, specified in 'agent.hooks.*.script' and method name @@ -146,20 +126,14 @@ domr.scripts.dir=scripts/network/domr/kvm # Libvirt XML transformer hook does XML-to-XML transformation, which allows the provider to modify # VM XML specification before is sent to libvirt. # The provider can use this to add/remove/modify some sort of attributes in Libvirt XML domain specification. -# Default value script: libvirt-vm-xml-transformer.groovy -# Default value method: transform #agent.hooks.libvirt_vm_xml_transformer.script=libvirt-vm-xml-transformer.groovy #agent.hooks.libvirt_vm_xml_transformer.method=transform # The hook is called right after libvirt successfully launched the VM. -# Default value script: libvirt-vm-state-change.groovy -# Default value method: onStart #agent.hooks.libvirt_vm_on_start.script=libvirt-vm-state-change.groovy #agent.hooks.libvirt_vm_on_start.method=onStart # The hook is called right after libvirt successfully stopped the VM. -# Default value script: libvirt-vm-state-change.groovy -# Default value method: onStop #agent.hooks.libvirt_vm_on_stop.script=libvirt-vm-state-change.groovy #agent.hooks.libvirt_vm_on_stop.method=onStop # ---------------- END AGENT HOOKS --------------- @@ -167,7 +141,6 @@ domr.scripts.dir=scripts/network/domr/kvm # Sets the type of bridge used on the hypervisor. This defines what commands the resource # will use to setup networking. # Possible Values: native | openvswitch -# Default value: native. #network.bridge.type=native # Sets the driver used to plug and unplug NICs from the bridges. @@ -186,7 +159,6 @@ domr.scripts.dir=scripts/network/domr/kvm #network.direct.device=eth0 # Sets DPDK Support on OpenVswitch. -# Default value for openvswitch.dpdk.enabled: false. #openvswitch.dpdk.enabled=false #openvswitch.dpdk.ovs.path=/var/run/openvswitch @@ -195,18 +167,15 @@ domr.scripts.dir=scripts/network/domr/kvm hypervisor.type=kvm # This parameter specifies a directory on the host local storage for temporary storing direct download templates. -# Default value: /var/lib/libvirt/images #direct.download.temporary.download.location=/var/lib/libvirt/images # This parameter specifies a directory on the host local storage for creating and hosting the config drives. -# Default value: /var/cache/cloud #host.cache.location=/var/cache/cloud # Sets the rolling maintenance hook scripts directory. #rolling.maintenance.hooks.dir=/etc/cloudstack/agent/hooks.d # Disables the rolling maintenance service execution. -# Default value: false #rolling.maintenance.service.executor.disabled=false # Sets the hypervisor URI. @@ -247,7 +216,6 @@ hypervisor.type=kvm # Disables memory ballooning on VM guests for overcommit. # By default overcommit feature enables balloon and sets currentMemory to a minimum value. -# Default value: false #vm.memballoon.disable=false @@ -255,29 +223,24 @@ hypervisor.type=kvm # to QCOW2 files, and ensures that there is no other running instance accessing # the file before starting. It works by checking the modified time against the current time, # so care must be taken to ensure that the cluster's time is synchronized, otherwise VMs may fail to start. -# Default value: false #vm.diskactivity.checkenabled=false # Timeout (in seconds) for giving up on waiting for VM's disk files to become inactive. # Hitting this timeout will result in failure to start VM. # Value must be > 0. -# Default value: 120 #vm.diskactivity.checktimeout_s=120 # This is the length of time (in ms) that the disk needs to be inactive in order to pass the check. # This means current time minus time of disk file needs to be greater than this number. # It also has the side effect of setting the minimum threshold between a stop and start of # a given VM. -# Default value: 30000 #vm.diskactivity.inactivetime_ms=30000 # Some newer linux kernels are incapable of reliably migrating VMs with KVMclock. # This is a workaround for the bug, admin can set this to true per-host. -# Default value: false. #kvmclock.disable=false # This enables the VirtIO Random Number Generator (RNG) device for guests. -# Default value: false. #vm.rng.enable=false # The model of VirtIO Random Number Generator (RNG) to present to the Guest. @@ -286,17 +249,14 @@ hypervisor.type=kvm # Local Random Number Device Generator to use for VirtIO RNG for Guests. # This is usually /dev/random, but it might be different per platform. -# Default value: /dev/random #vm.rng.path=/dev/random # The amount of bytes the Guest may request/obtain from the RNG in the period # specified in the property vm.rng.rate.period. -# Default value: 2048 #vm.rng.rate.bytes=2048 # The number of milliseconds in which the guest is allowed to obtain the bytes # specified in the property vm.rng.rate.bytes. -# Default value: 1000 #vm.rng.rate.period=1000 # Timeout value for aggregation commands to be sent to the virtual router (in seconds). @@ -305,25 +265,21 @@ hypervisor.type=kvm # Allows virtually increase the amount of RAM (in MB) available on the host. # This property can be useful if the host uses Zswap, KSM features and other memory compressing technologies. # For example: if the host has 2GB of RAM and this property is set to 2048, the amount of RAM of the host will be read as 4GB. -# Default value: 0 #host.overcommit.mem.mb=0 # How much host memory (in MB) to reserve for non-allocation. # A useful parameter if a node uses some other software that requires memory, # or in case that OOM Killer kicks in. # If this parameter is used, property host.overcommit.mem.mb must be set to 0. -# Default value: 1024 #host.reserved.mem.mb=1024 # The model of Watchdog timer to present to the Guest. # For all models refer to the libvirt documentation. -# Default value: i6300esb #vm.watchdog.model=i6300esb # Action to take when the Guest/Instance is no longer notifying the Watchdog timer. # For all actions refer to the libvirt documentation. # Possible values: none | reset | poweroff -# Default value: none #vm.watchdog.action=none # Automatically clean up iSCSI sessions not attached to any VM. @@ -333,19 +289,15 @@ iscsi.session.cleanup.enabled=false # The heartbeat update timeout (in ms). # Depending on the use case, this timeout might need increasing/decreasing. -# Default value: 60000 #heartbeat.update.timeout=60000 # The timeout (in seconds) to retrieve the target's domain id when migrating a VM with KVM. -# # Default value: 10 #vm.migrate.domain.retrieve.timeout=10 # This parameter specifies if the host must be rebooted when something goes wrong with the heartbeat. -# Default value: true #reboot.host.and.alert.management.on.heartbeat.timeout=true # Enables manually setting CPU's topology on KVM's VM. -# Default value: true #enable.manually.setting.cpu.topology.on.kvm.vm=true # Manually sets the host CPU MHz, in cases where CPU scaling support detects the value is wrong. @@ -364,7 +316,6 @@ iscsi.session.cleanup.enabled=false # steps concatenating the property path with "/usr/share/cloudstack-common/". # The path defined in this property is relative # to the directory "/usr/share/cloudstack-common/". -# Default value: scripts/vm/hypervisor #hypervisor.scripts.dir=scripts/vm/hypervisor # Defines the location for KVM scripts. @@ -377,15 +328,12 @@ iscsi.session.cleanup.enabled=false # steps concatenating the property path with "/usr/share/cloudstack-common/". # The path defined in this property is relative # to the directory "/usr/share/cloudstack-common/". -# Default value: scripts/vm/hypervisor/kvm #kvm.scripts.dir=scripts/vm/hypervisor/kvm # Specifies start MAC address for private IP range. -# Default value: 00:16:3e:77:e2:a0 #private.macaddr.start=00:16:3e:77:e2:a0 # Specifies start IP address for private IP range. -# Default value: 192.168.166.128 #private.ipaddr.start=192.168.166.128 # Defines Local Bridge Name. @@ -404,7 +352,6 @@ iscsi.session.cleanup.enabled=false # steps concatenating the property path with "/usr/share/cloudstack-common/". # The path defined in this property is relative # to the directory "/usr/share/cloudstack-common/". -# Default value: scripts/vm/network/vnet #network.scripts.dir=scripts/vm/network/vnet # Defines the location for storage scripts. @@ -417,38 +364,31 @@ iscsi.session.cleanup.enabled=false # steps concatenating the property path with "/usr/share/cloudstack-common/". # The path defined in this property is relative # to the directory "/usr/share/cloudstack-common/". -# Default value: scripts/storage/qcow2 #storage.scripts.dir=scripts/storage/qcow2 # Time (in seconds) to wait for the VM to shutdown gracefully. # If the time is exceeded shutdown will be forced. -# Default value: 120 #stop.script.timeout=120 # Definition of VMs video model type. #vm.video.hardware= # Definition of VMs video, specifies the amount of RAM in kibibytes (blocks of 1024 bytes). -# Default value: 0 #vm.video.ram=0 # System VM ISO path. #systemvm.iso.path= # If set to "true", allows override of the properties: private.macaddr.start, private.ipaddr.start, private.ipaddr.end. -# Default value: false #developer=false # Can only be used if property developer = true. This property is used to define the link local bridge name and private network name. #instance= # Shows the path to the base directory in which NFS servers are going to be mounted. -# Default value: /mnt #mount.path=/mnt # Port listened by the console proxy. -# Default value: 443 #consoleproxy.httpListenPort=443 -# Default value: 5 #ping.retries=5 From c32cda9da635dece21cc05147182e06307818cbf Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Fri, 12 Aug 2022 17:05:45 -0300 Subject: [PATCH 15/23] Null-safe validations --- agent/src/main/java/com/cloud/agent/AgentShell.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index 126a5dcaf385..4ceb26622843 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -32,6 +32,7 @@ import org.apache.commons.daemon.DaemonContext; import org.apache.commons.daemon.DaemonInitException; import org.apache.commons.lang.math.NumberUtils; +import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; @@ -303,7 +304,7 @@ protected String getGuid(String guid) throws ConfigurationException { return guid; } - if (!AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER)) { + if (BooleanUtils.isFalse(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER))) { throw new ConfigurationException("Unable to find the guid"); } @@ -488,7 +489,7 @@ public void start() { String instance = getProperty(null, "instance"); if (instance == null) { - if (AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER)) { + if (BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.DEVELOPER))) { instance = UUID.randomUUID().toString(); } else { instance = ""; From e9d76c97ca4dbc19c66005f2368c2991a6fa7049 Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Fri, 12 Aug 2022 17:21:47 -0300 Subject: [PATCH 16/23] Fix access to property 'workers' --- .../src/main/java/com/cloud/agent/AgentShell.java | 6 ++++-- .../cloud/agent/properties/AgentProperties.java | 9 ++++++++- .../test/java/com/cloud/agent/AgentShellTest.java | 15 +++++++-------- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index 4ceb26622843..38878b850929 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -76,6 +76,7 @@ public class AgentShell implements IAgentShell, Daemon { private String hostToConnect; private String connectedHost; private Long preferredHostCheckInterval; + protected AgentProperties agentProperties = new AgentProperties(); public AgentShell() { } @@ -326,10 +327,11 @@ protected String getZoneOrPod(String zoneOrPod, AgentProperties.Property } protected int getWorkers(String workersString) { - int workers = getPortOrWorkers(workersString, AgentProperties.WORKERS); + AgentProperties.Property propertyWorkers = agentProperties.getWorkers(); + int workers = getPortOrWorkers(workersString, propertyWorkers); if (workers <= 0) { - workers = AgentProperties.WORKERS.getDefaultValue(); + workers = propertyWorkers.getDefaultValue(); } return workers; diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index dcb50d266ed6..2e122a1659cb 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -46,7 +46,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 5 */ - public static Property WORKERS = new Property<>("workers", 5); + private final Property workers = new Property<>("workers", 5); /** * The IP address of the management server.
@@ -707,6 +707,13 @@ public class AgentProperties{ */ public static final Property PING_RETRIES = new Property<>("ping.retries", 5); + /** + * Returns {@link AgentProperties#workers}. + */ + public Property getWorkers() { + return workers; + } + public static class Property { private String name; private T defaultValue; diff --git a/agent/src/test/java/com/cloud/agent/AgentShellTest.java b/agent/src/test/java/com/cloud/agent/AgentShellTest.java index 29fb6c5ab7b3..27bc3dcbde33 100644 --- a/agent/src/test/java/com/cloud/agent/AgentShellTest.java +++ b/agent/src/test/java/com/cloud/agent/AgentShellTest.java @@ -31,6 +31,7 @@ import com.cloud.utils.StringUtils; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; @@ -41,9 +42,13 @@ @RunWith(PowerMockRunner.class) public class AgentShellTest { + @InjectMocks @Spy AgentShell agentShellSpy = new AgentShell(); + @Mock + AgentProperties agentPropertiesMock; + @Mock AgentProperties.Property propertyIntegerMock; @@ -142,13 +147,10 @@ public void getPortOrWorkersTestValueIsAValidIntegerReturnValue() { } @Test - @PrepareForTest(AgentProperties.class) public void getWorkersTestWorkersLessThan0ReturnDefault() { int expected = 42; - PowerMockito.mockStatic(AgentProperties.class); - AgentProperties.WORKERS = propertyIntegerMock; - + Mockito.doReturn(propertyIntegerMock).when(agentPropertiesMock).getWorkers(); Mockito.doReturn(-1).when(agentShellSpy).getPortOrWorkers(Mockito.any(), Mockito.any()); Mockito.doReturn(expected).when(propertyIntegerMock).getDefaultValue(); @@ -158,13 +160,10 @@ public void getWorkersTestWorkersLessThan0ReturnDefault() { } @Test - @PrepareForTest(AgentProperties.class) public void getWorkersTestWorkersEqualTo0ReturnDefault() { int expected = 42; - PowerMockito.mockStatic(AgentProperties.class); - AgentProperties.WORKERS = propertyIntegerMock; - + Mockito.doReturn(propertyIntegerMock).when(agentPropertiesMock).getWorkers(); Mockito.doReturn(0).when(agentShellSpy).getPortOrWorkers(Mockito.any(), Mockito.any()); Mockito.doReturn(expected).when(propertyIntegerMock).getDefaultValue(); From 35af64ace7546bb7541f5b337e22cf6749055b33 Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Fri, 12 Aug 2022 17:50:09 -0300 Subject: [PATCH 17/23] Fix AgentPropertiesTest --- .../java/com/cloud/agent/properties/AgentProperties.java | 2 +- .../com/cloud/agent/properties/AgentPropertiesTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 2e122a1659cb..63bd1fbd30b5 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -46,7 +46,7 @@ public class AgentProperties{ * Data type: Integer.
* Default value: 5 */ - private final Property workers = new Property<>("workers", 5); + protected final Property workers = new Property<>("workers", 5); /** * The IP address of the management server.
diff --git a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java index a0a4f7702aec..9f40feef96e8 100644 --- a/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java +++ b/agent/src/test/java/com/cloud/agent/properties/AgentPropertiesTest.java @@ -28,10 +28,12 @@ public class AgentPropertiesTest { @Test public void initTestBlockInstanceWithNullValueAndWithoutType() throws IllegalAccessException { - Field[] fields = AgentProperties.class.getDeclaredFields(); + AgentProperties agentProperties = new AgentProperties(); + Field[] fields = agentProperties.getClass().getDeclaredFields(); + for (Field field : fields) { if (field.getType().equals(AgentProperties.Property.class)) { - AgentProperties.Property property = (AgentProperties.Property) field.get(null); + AgentProperties.Property property = (AgentProperties.Property) field.get(agentProperties); Assert.assertTrue(String.format("Either inform the default value or the class of property [%s], field [%s].", property.getName(), field.getName()), property.getDefaultValue() != null || property.getTypeClass() != null); From 39fed9d60d2b0220929a1ac387220d2d79bb7a0b Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Thu, 3 Nov 2022 09:25:33 -0300 Subject: [PATCH 18/23] Fix build failure --- .../hypervisor/kvm/resource/LibvirtComputingResourceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java index fd656034b1f1..96250b26cbc3 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java @@ -4926,7 +4926,7 @@ public void testResizeVolumeCommandLinstorNotifyOnly() { when(storagePool.getType()).thenReturn(StoragePoolType.Linstor); when(vol.getFormat()).thenReturn(PhysicalDiskFormat.RAW); - when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); + when(libvirtComputingResourceMock.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); try { when(libvirtUtilitiesHelper.getConnectionByVmName(vmInstance)).thenReturn(conn); when(conn.domainLookupByName(vmInstance)).thenReturn(vm); From 43716d821b3e1df85107c7d90f4195951b68e763 Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Sat, 5 Nov 2022 12:27:09 -0300 Subject: [PATCH 19/23] Adjusts and review addressing --- agent/conf/agent.properties | 33 +++++----- .../main/java/com/cloud/agent/AgentShell.java | 2 + .../agent/properties/AgentProperties.java | 64 +++++++++---------- .../resource/LibvirtComputingResource.java | 8 ++- 4 files changed, 57 insertions(+), 50 deletions(-) diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index b6bb79160c27..d7f92d854406 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -40,7 +40,7 @@ host=localhost # the agent as the preferred host check interval, however, if the following setting # is defined it will override the received value. The value 0 and lb algorithm 'shuffle' # disables this background task. -#host.lb.check.interval=0 +#host.lb.check.interval= # The port that the management server is listening on. port=8250 @@ -147,9 +147,9 @@ domr.scripts.dir=scripts/network/domr/kvm # A sensible default value will be selected based on the network.bridge.type but can # be overridden here. # Also used to enable direct networking in libvirt (see properties below). -# Value for native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver -# Value for openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver -#libvirt.vif.driver=com.cloud.hypervisor.kvm.resource.BridgeVifDriver +# Default value when network.bridge.type as native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver +# Default value when network.bridge.type as openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver +#libvirt.vif.driver= # Settings to enable direct networking in libvirt. # Should not be used on hosts that run system VMs. @@ -160,7 +160,7 @@ domr.scripts.dir=scripts/network/domr/kvm # Sets DPDK Support on OpenVswitch. #openvswitch.dpdk.enabled=false -#openvswitch.dpdk.ovs.path=/var/run/openvswitch +#openvswitch.dpdk.ovs.path= # Sets the hypervisor type. # Possible values: kvm | lxc @@ -173,15 +173,16 @@ hypervisor.type=kvm #host.cache.location=/var/cache/cloud # Sets the rolling maintenance hook scripts directory. -#rolling.maintenance.hooks.dir=/etc/cloudstack/agent/hooks.d +# Default is null, however, can be used as /etc/cloudstack/agent/hooks.d +#rolling.maintenance.hooks.dir= # Disables the rolling maintenance service execution. #rolling.maintenance.service.executor.disabled=false -# Sets the hypervisor URI. +# Sets the hypervisor URI. If null (default), the value defaults according the hypervisor.type: # For KVM: qemu:///system # For LXC: lxc:/// -#hypervisor.uri=qemu:///system +#hypervisor.uri= # Setting to enable the CPU model to KVM guest globally. # Possible values: custom | host-model | host-passthrough @@ -196,7 +197,8 @@ hypervisor.type=kvm # and can be important to some apps which check low level CPU details, # but it comes at a cost with migration. The guest can only be migrated to # an exactly matching host CPU. -#guest.cpu.mode=host-model +# If null (default), libvirt defaults to custom +#guest.cpu.mode= # Custom CPU model. This param is only valid if guest.cpu.mode=custom. # Possible values:"Conroe" | "Penryn" | "Nehalem" | "Westmere" | "pentiumpro" etc. @@ -208,11 +210,12 @@ hypervisor.type=kvm # In case of arm64 (aarch64), this will change the machine type to 'virt' and # adds a SCSI and a USB controller in the domain xml. # Possible values: x86_64 | aarch64 -#guest.cpu.arch=x86_64 +# If null (default), defaults to the VM's OS architecture +#guest.cpu.arch= # This param will require CPU features on the CPU section. -# The features listed in this property must be separated by a blank space (see example below). -#guest.cpu.features=vmx vme +# The features listed in this property must be separated by a blank space (e.g.: vmx vme) +#guest.cpu.features= # Disables memory ballooning on VM guests for overcommit. # By default overcommit feature enables balloon and sets currentMemory to a minimum value. @@ -260,7 +263,7 @@ hypervisor.type=kvm #vm.rng.rate.period=1000 # Timeout value for aggregation commands to be sent to the virtual router (in seconds). -#router.aggregation.command.each.timeout=600 +#router.aggregation.command.each.timeout= # Allows virtually increase the amount of RAM (in MB) available on the host. # This property can be useful if the host uses Zswap, KSM features and other memory compressing technologies. @@ -303,8 +306,8 @@ iscsi.session.cleanup.enabled=false # Manually sets the host CPU MHz, in cases where CPU scaling support detects the value is wrong. #host.cpu.manual.speed.mhz=0 -# Enables/disables the IO driver for Qemu (in case it is not set CloudStack can also detect if its supported by Qemu). -#enable.io.uring=true +# Enables/disables the IO driver for Qemu (in case it is not set CloudStack can also detect if it is supported by Qemu). +#enable.io.uring= # Defines the location for Hypervisor scripts. # The path defined in this property is relative. diff --git a/agent/src/main/java/com/cloud/agent/AgentShell.java b/agent/src/main/java/com/cloud/agent/AgentShell.java index 1eda30d0ca9c..ef042496a372 100644 --- a/agent/src/main/java/com/cloud/agent/AgentShell.java +++ b/agent/src/main/java/com/cloud/agent/AgentShell.java @@ -271,6 +271,8 @@ protected boolean parseCommand(final String[] args) throws ConfigurationExceptio setHost(host); _guid = getGuid(guid); + _properties.setProperty(AgentProperties.GUID.getName(), _guid); + _port = getPortOrWorkers(port, AgentProperties.PORT); _workers = getWorkers(workers); _zone = getZoneOrPod(zone, AgentProperties.ZONE); diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 63bd1fbd30b5..6d77d74ea56d 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -267,6 +267,37 @@ public class AgentProperties{ */ public static final Property NETWORK_BRIDGE_TYPE = new Property<>("network.bridge.type", "native"); + /** + * Sets the driver used to plug and unplug NICs from the bridges.
+ * A sensible default value will be selected based on the network.bridge.type but can be overridden here.
+ * Value for native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver
+ * Value for openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver
+ * Value to enable direct networking in libvirt = com.cloud.hypervisor.kvm.resource.DirectVifDriver (should not be used on hosts that run system VMs)
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: null + */ + public static final Property LIBVIRT_VIF_DRIVER = new Property<>("libvirt.vif.driver", null, String.class); + + /** + * Setting to enable direct networking in libvirt.
+ * Should not be used on hosts that run system VMs.
+ * For more information see the agent.properties file.
+ * Possible values: private | bridge | vepa
+ * Data type: String.
+ * Default value: null + */ + public static final Property NETWORK_DIRECT_SOURCE_MODE = new Property<>("network.direct.source.mode", null, String.class); + + /** + * Setting to enable direct networking in libvirt.
+ * Should not be used on hosts that run system VMs.
+ * For more information see the agent.properties file.
+ * Data type: String.
+ * Default value: null + */ + public static final Property NETWORK_DIRECT_DEVICE = new Property<>("network.direct.device", null, String.class); + /** * Sets DPDK Support on OpenVSwitch.
* Data type: Boolean.
@@ -327,37 +358,6 @@ public class AgentProperties{ */ public static final Property HYPERVISOR_URI = new Property<>("hypervisor.uri", null, String.class); - /** - * Sets the driver used to plug and unplug NICs from the bridges.
- * A sensible default value will be selected based on the network.bridge.type but can be overridden here.
- * Value for native = com.cloud.hypervisor.kvm.resource.BridgeVifDriver
- * Value for openvswitch = com.cloud.hypervisor.kvm.resource.OvsVifDriver
- * Value to enable direct networking in libvirt = com.cloud.hypervisor.kvm.resource.DirectVifDriver (should not be used on hosts that run system VMs)
- * For more information see the agent.properties file.
- * Data type: String.
- * Default value: null - */ - public static final Property LIBVIRT_VIF_DRIVER = new Property<>("libvirt.vif.driver", null, String.class); - - /** - * Setting to enable direct networking in libvirt.
- * Should not be used on hosts that run system VMs.
- * For more information see the agent.properties file.
- * Possible values: private | bridge | vepa
- * Data type: String.
- * Default value: null - */ - public static final Property NETWORK_DIRECT_SOURCE_MODE = new Property<>("network.direct.source.mode", null, String.class); - - /** - * Setting to enable direct networking in libvirt.
- * Should not be used on hosts that run system VMs.
- * For more information see the agent.properties file.
- * Data type: String.
- * Default value: null - */ - public static final Property NETWORK_DIRECT_DEVICE = new Property<>("network.direct.device", null, String.class); - /** * Setting to enable the CPU model to KVM guest globally.
* Possible values: custom | host-model | host-passthrough
@@ -380,7 +380,7 @@ public class AgentProperties{ * In case of arm64 (aarch64), this will change the machine type to 'virt' and add a SCSI and a USB controller in the domain XML.
* Possible values: x86_64 | aarch64
* Data type: String.
- * Default value: null (will set as the default of the host's OS). + * Default value: null (will set use the architecture of the VM's OS). */ public static final Property GUEST_CPU_ARCH = new Property<>("guest.cpu.arch", null, String.class); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 2f3f4ae9a840..02adf1ccf9c6 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -1219,8 +1219,10 @@ protected void configureLocalStorage() throws ConfigurationException { String[] localStorageRelativePaths = localStoragePath.split(CONFIG_VALUES_SEPARATOR); String[] localStorageUUIDStrings = localStorageUUIDString.split(CONFIG_VALUES_SEPARATOR); if (localStorageRelativePaths.length != localStorageUUIDStrings.length) { - s_logger.error(String.format("The path and UUID of the local storage pools have different length. Path: [%s], UUID: [%s].", localStoragePath, localStorageUUIDString)); - throw new ConfigurationException(String.format("The path and UUID of the local storage pools have different length. Path: [%s], UUID: [%s].", localStoragePath, localStorageUUIDString)); + String errorMessage = String.format("The path and UUID of the local storage pools have different length. Path: [%s], UUID: [%s].", localStoragePath, + localStorageUUIDString); + s_logger.error(errorMessage); + throw new ConfigurationException(errorMessage); } for (String localStorageRelativePath : localStorageRelativePaths) { final File storagePath = new File(localStorageRelativePath); @@ -1255,7 +1257,7 @@ public boolean configureHostParams(final Map params) { storage.configure("Storage", new HashMap()); Long longValue = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.ROUTER_AGGREGATION_COMMAND_EACH_TIMEOUT); if (longValue != null) { - storage.persist("router.aggregation.command.each.timeout", String.valueOf(longValue)); + storage.persist(AgentProperties.ROUTER_AGGREGATION_COMMAND_EACH_TIMEOUT.getName(), String.valueOf(longValue)); } if (params.get(Config.MigrateWait.toString()) != null) { From b448f83deaa8f8bcf3d71532654b3d1581770f90 Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Wed, 9 Nov 2022 18:32:20 -0300 Subject: [PATCH 20/23] Fix merge main --- .../java/com/cloud/agent/properties/AgentProperties.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 41a17b019e3f..f7c9f1a9025b 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -714,14 +714,6 @@ public Property getWorkers() { return workers; } - /** - * Disables memory ballooning on VM guests for overcommit.
- * By default overcommit feature enables balloon and sets currentMemory to a minimum value.
- * Data type: Boolean.
- * Default value: false - */ - public static final Property VM_MEMBALLOON_DISABLE = new Property<>("vm.memballoon.disable", false); - /** * The time interval (in seconds) at which the balloon driver will get memory stats updates. This is equivalent to Libvirt's --period parameter when using the dommemstat command. * Data type: Integer.
From 57adcb66c1c0d26c96efc5a05022c771d8c85100 Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Mon, 12 Dec 2022 12:19:30 -0300 Subject: [PATCH 21/23] Fix call to method --- .../hypervisor/kvm/resource/LibvirtComputingResource.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index 17f50e669f87..1d355d58f3dd 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -990,11 +990,11 @@ public boolean configure(final String name, final Map params) th _videoRam = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VM_VIDEO_RAM); // Reserve 1GB unless admin overrides - _dom0MinMem = ByteScaleUtils.mibToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB)); + _dom0MinMem = ByteScaleUtils.mebibytesToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_RESERVED_MEM_MB)); // Support overcommit memory for host if host uses ZSWAP, KSM and other memory // compressing technologies - _dom0OvercommitMem = ByteScaleUtils.mibToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB)); + _dom0OvercommitMem = ByteScaleUtils.mebibytesToBytes(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.HOST_OVERCOMMIT_MEM_MB)); if (BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.KVMCLOCK_DISABLE))) { _noKvmClock = true; From c03dc60ae824f84bc639915dbb67f8900c04f8aa Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Mon, 12 Dec 2022 12:36:37 -0300 Subject: [PATCH 22/23] Remove duplicated import --- .../hypervisor/kvm/resource/LibvirtComputingResourceTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java index 80b9a4acf7d3..7d2a9ea6b84d 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java @@ -59,7 +59,6 @@ import javax.xml.xpath.XPathFactory; import com.cloud.utils.net.NetUtils; -import com.cloud.utils.ssh.SshHelper; import org.apache.cloudstack.storage.command.AttachAnswer; import org.apache.cloudstack.storage.command.AttachCommand; import org.apache.cloudstack.utils.bytescale.ByteScaleUtils; From ad94cb36733d809c60c7c25ba43670162806423b Mon Sep 17 00:00:00 2001 From: GutoVeronezi Date: Thu, 15 Dec 2022 10:51:08 -0300 Subject: [PATCH 23/23] Parse cmdline to agent.properties in system VMs bootstrap --- .../debian/opt/cloud/bin/setup/bootstrap.sh | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/systemvm/debian/opt/cloud/bin/setup/bootstrap.sh b/systemvm/debian/opt/cloud/bin/setup/bootstrap.sh index 3670010c5e93..05edc3fbf61f 100755 --- a/systemvm/debian/opt/cloud/bin/setup/bootstrap.sh +++ b/systemvm/debian/opt/cloud/bin/setup/bootstrap.sh @@ -18,6 +18,7 @@ set -x PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin" CMDLINE=/var/cache/cloud/cmdline +PROPERTIES=usr/local/cloud/systemvm/conf/agent.properties rm -f /var/cache/cloud/enabled_svcs rm -f /var/cache/cloud/disabled_svcs @@ -42,7 +43,21 @@ patch_systemvm() { mkdir -p /usr/local/cloud/systemvm ls -lrt $patchfile - echo "All" | unzip $patchfile -d /usr/local/cloud/systemvm >$logfile 2>&1 + log_it "Unziping $patchfile" + echo "All" | unzip $patchfile -d /usr/local/cloud/systemvm >>$logfile 2>&1 + + if [ "$TYPE" = "secstorage" ]; then + log_it "As system VM type is $TYPE, we will remove the default properties 'instance' and 'resource' from $PROPERTIES" + sed -i '/instance=/d' $PROPERTIES + sed -i '/resource=/d' $PROPERTIES + fi + + log_it "Copying content of $CMDLINE to $PROPERTIES" + for element in $(cat $CMDLINE) + do + echo $element >> $PROPERTIES + done + find /usr/local/cloud/systemvm/ -name \*.sh | xargs chmod 555 if [ -f $backupfolder/cloud.jks ]; then cp -r $backupfolder/* /usr/local/cloud/systemvm/conf/