From ded7900e91aed34f0457fac84c0f5b1042fb8393 Mon Sep 17 00:00:00 2001 From: Damian Guppy Date: Fri, 15 May 2026 14:48:18 +0800 Subject: [PATCH 001/423] Remove 19 dead plugins, insecure auth modules, and abandoned tooling (~143K lines) Deleted plugins targeting discontinued products/companies: - Network: BigSwitch BCF, Brocade VCS, Cisco VNMC, Stratosphere SSP, GloboDNS, Nicira NVP (replaced by NSX), Juniper Contrail (replaced by Tungsten) - Storage: CloudByte, Datera, SolidFire, Nexenta - Hypervisors: OVM (Oracle VM 2), OVM3 (Oracle VM 3), UCS (Cisco) - Auth: MD5 (cryptographically broken), Plain-text (insecure) - Tools: ngui (abandoned Angular UI), cloud-cli, quickcloud Cleaned cross-references across ~50 core files including provider constants, config keys, API parameters, Spring XML, Marvin test framework, and role permission SQL. Preserved HypervisorType enum values for DB compatibility and SQL migration history. Kept OpenDaylight, Baremetal, and Hyper-V for continued support. Co-Authored-By: Claude Opus 4.6 --- .../java/com/cloud/hypervisor/Hypervisor.java | 2 + .../main/java/com/cloud/network/Network.java | 13 - .../com/cloud/network/NetworkService.java | 4 +- .../network/PhysicalNetworkTrafficType.java | 2 - .../apache/cloudstack/api/ApiConstants.java | 4 - .../command/admin/cluster/AddClusterCmd.java | 19 +- .../admin/usage/AddTrafficTypeCmd.java | 11 +- .../admin/usage/UpdateTrafficTypeCmd.java | 11 +- .../api/response/ClusterResponse.java | 20 - .../api/response/TrafficTypeResponse.java | 12 - .../network/ExternalNetworkDeviceManager.java | 4 - client/pom.xml | 70 - cloud-cli/bindir/cloud-tool | 29 - cloud-cli/cloudapis/__init__.py | 42 - cloud-cli/cloudapis/cloud.py | 196 - cloud-cli/cloudtool/__init__.py | 71 - cloud-cli/cloudtool/utils.py | 169 - .../spring-core-registry-core-context.xml | 2 +- docs/AUDIT.md | 315 + .../orchestration/NetworkOrchestrator.java | 3 +- .../orchestration/VolumeOrchestrator.java | 2 - .../PhysicalNetworkTrafficTypeDaoImpl.java | 17 - .../dao/PhysicalNetworkTrafficTypeVO.java | 9 +- .../upgrade/SystemVmTemplateRegistration.java | 7 +- .../upgrade/dao/Upgrade41500to41510.java | 7 - .../db/create-default-role-api-mappings.sql | 12 - .../framework/config/ConfigKey.java | 1 - .../jobs/src/test/resources/log4j.properties | 1 - plugins/api/solidfire-intg-test/pom.xml | 51 - .../admin/solidfire/GetPathForVolumeCmd.java | 59 - .../solidfire/GetSolidFireAccountIdCmd.java | 64 - .../GetSolidFireVolumeAccessGroupIdsCmd.java | 73 - .../solidfire/GetSolidFireVolumeSizeCmd.java | 62 - .../GetVolumeSnapshotDetailsCmd.java | 65 - .../solidfire/GetVolumeiScsiNameCmd.java | 60 - .../solidfire/ApiPathForVolumeResponse.java | 33 - .../ApiSolidFireAccountIdResponse.java | 33 - ...SolidFireVolumeAccessGroupIdsResponse.java | 33 - .../ApiSolidFireVolumeSizeResponse.java | 33 - .../ApiVolumeSnapshotDetailsResponse.java | 43 - .../solidfire/ApiVolumeiScsiNameResponse.java | 33 - .../ApiSolidFireIntegrationTestService.java | 22 - ...piSolidFireIntegrationTestServiceImpl.java | 47 - .../SolidFireIntegrationTestManager.java | 23 - .../SolidFireIntegrationTestManagerImpl.java | 107 - .../SolidFireIntegrationTestUtil.java | 145 - .../solidfire-intg-test/module.properties | 18 - .../spring-solidfire-intg-test-context.xml | 34 - plugins/hypervisors/ovm/pom.xml | 37 - .../cloud/ovm/hypervisor/OvmDiscoverer.java | 259 - .../com/cloud/ovm/hypervisor/OvmFencer.java | 117 - .../com/cloud/ovm/hypervisor/OvmGuru.java | 67 - .../com/cloud/ovm/hypervisor/OvmHelper.java | 65 - .../cloud/ovm/hypervisor/OvmResourceBase.java | 1268 -- .../main/java/com/cloud/ovm/object/Coder.java | 84 - .../java/com/cloud/ovm/object/Connection.java | 140 - .../java/com/cloud/ovm/object/OvmBridge.java | 70 - .../java/com/cloud/ovm/object/OvmDisk.java | 30 - .../java/com/cloud/ovm/object/OvmHost.java | 92 - .../java/com/cloud/ovm/object/OvmObject.java | 20 - .../cloud/ovm/object/OvmSecurityGroup.java | 56 - .../com/cloud/ovm/object/OvmStoragePool.java | 107 - .../java/com/cloud/ovm/object/OvmVif.java | 30 - .../java/com/cloud/ovm/object/OvmVlan.java | 43 - .../main/java/com/cloud/ovm/object/OvmVm.java | 110 - .../java/com/cloud/ovm/object/OvmVolume.java | 53 - .../main/java/com/cloud/ovm/object/Test.java | 122 - .../cloudstack/ovm-compute/module.properties | 18 - .../spring-ovm-compute-context.xml | 39 - .../ovm-discoverer/module.properties | 18 - .../spring-ovm-discoverer-context.xml | 34 - .../vm/hypervisor/ovm/ConfigFileOps.py | 174 - .../vm/hypervisor/ovm/OvmCommonModule.py | 158 - .../vm/hypervisor/ovm/OvmDiskModule.py | 65 - .../vm/hypervisor/ovm/OvmDispatcher.py | 62 - .../vm/hypervisor/ovm/OvmFaultConstants.py | 99 - .../vm/hypervisor/ovm/OvmHaHeartBeatModule.py | 104 - .../vm/hypervisor/ovm/OvmHostModule.py | 307 - .../vm/hypervisor/ovm/OvmLoggerModule.py | 54 - .../vm/hypervisor/ovm/OvmNetworkModule.py | 433 - .../vm/hypervisor/ovm/OvmOCFS2Module.py | 79 - .../vm/hypervisor/ovm/OvmObjectModule.py | 23 - .../hypervisor/ovm/OvmSecurityGroupModule.py | 440 - .../vm/hypervisor/ovm/OvmStoragePoolModule.py | 429 - .../scripts/vm/hypervisor/ovm/OvmVifModule.py | 65 - .../scripts/vm/hypervisor/ovm/OvmVmModule.py | 541 - .../vm/hypervisor/ovm/OvmVolumeModule.py | 155 - .../scripts/vm/hypervisor/ovm/configureOvm.sh | 130 - plugins/hypervisors/ovm3/.gitignore | 1 - plugins/hypervisors/ovm3/pom.xml | 88 - .../hypervisors/ovm3/sonar-project.properties | 36 - .../java/com/cloud/ha/Ovm3Investigator.java | 81 - .../ovm3/objects/CloudstackPlugin.java | 183 - .../hypervisor/ovm3/objects/Cluster.java | 126 - .../cloud/hypervisor/ovm3/objects/Common.java | 60 - .../hypervisor/ovm3/objects/Connection.java | 196 - .../cloud/hypervisor/ovm3/objects/Linux.java | 454 - .../hypervisor/ovm3/objects/Network.java | 329 - .../cloud/hypervisor/ovm3/objects/Ntp.java | 119 - .../ovm3/objects/Ovm3ResourceException.java | 39 - .../hypervisor/ovm3/objects/OvmObject.java | 248 - .../cloud/hypervisor/ovm3/objects/Pool.java | 270 - .../hypervisor/ovm3/objects/PoolOCFS2.java | 139 - .../cloud/hypervisor/ovm3/objects/Remote.java | 33 - .../hypervisor/ovm3/objects/Repository.java | 334 - .../ovm3/objects/RpcTypeFactory.java | 87 - .../ovm3/objects/StoragePlugin.java | 884 - .../cloud/hypervisor/ovm3/objects/Xen.java | 996 -- .../ovm3/resources/Ovm3Discoverer.java | 414 - .../ovm3/resources/Ovm3FenceBuilder.java | 115 - .../ovm3/resources/Ovm3HypervisorGuru.java | 69 - .../resources/Ovm3HypervisorResource.java | 536 - .../ovm3/resources/Ovm3StorageProcessor.java | 872 - .../resources/Ovm3VirtualRoutingResource.java | 180 - .../resources/helpers/Ovm3Configuration.java | 465 - .../helpers/Ovm3HypervisorNetwork.java | 250 - .../helpers/Ovm3HypervisorSupport.java | 752 - .../resources/helpers/Ovm3StoragePool.java | 748 - .../helpers/Ovm3VirtualRoutingSupport.java | 201 - .../resources/helpers/Ovm3VmGuestTypes.java | 81 - .../ovm3/resources/helpers/Ovm3VmSupport.java | 467 - .../cloudstack/ovm3-compute/module.properties | 18 - .../spring-ovm3-compute-context.xml | 41 - .../ovm3-discoverer/module.properties | 18 - .../spring-ovm3-discoverer-context.xml | 34 - .../ovm3/objects/CloudStackPluginTest.java | 322 - .../hypervisor/ovm3/objects/CommonTest.java | 53 - .../ovm3/objects/ConnectionTest.java | 161 - .../hypervisor/ovm3/objects/LinuxTest.java | 642 - .../hypervisor/ovm3/objects/NetworkTest.java | 345 - .../hypervisor/ovm3/objects/NtpTest.java | 97 - .../ovm3/objects/PoolOCFS2Test.java | 110 - .../hypervisor/ovm3/objects/PoolTest.java | 180 - .../hypervisor/ovm3/objects/RemoteTest.java | 36 - .../ovm3/objects/RepositoryTest.java | 182 - .../ovm3/objects/StoragePluginTest.java | 356 - .../hypervisor/ovm3/objects/XenTest.java | 781 - .../ovm3/objects/XmlTestResultTest.java | 134 - .../resources/Ovm3HypervisorResourceTest.java | 364 - .../resources/Ovm3StorageProcessorTest.java | 342 - .../Ovm3VirtualRoutingResourceTest.java | 233 - .../helpers/Ovm3ConfigurationTest.java | 111 - .../resources/helpers/Ovm3GuestTypesTest.java | 33 - .../helpers/Ovm3HypervisorNetworkTest.java | 127 - .../helpers/Ovm3HypervisorSupportTest.java | 280 - .../Ovm3VirtualRoutingSupportTest.java | 88 - .../resources/helpers/Ovm3VmSupportTest.java | 128 - .../ovm3/support/Ovm3SupportTest.java | 112 - .../ovm3/src/test/resources/log4j.properties | 25 - .../test/resources/scripts/clean_primary.sh | 43 - .../test/resources/scripts/clean_secondary.sh | 32 - .../resources/scripts/create_pool_cluster.py | 270 - .../ovm3/src/test/resources/scripts/info.py | 111 - .../src/test/resources/scripts/password.py | 57 - .../src/test/resources/scripts/repo_pool.py | 186 - .../src/test/resources/scripts/simple_pool.py | 209 - .../ovm3/src/test/resources/scripts/socat.sh | 21 - .../ovm3/src/test/resources/scripts/tail.sh | 21 - plugins/hypervisors/ucs/pom.xml | 44 - .../com/cloud/ucs/database/UcsBladeDao.java | 24 - .../cloud/ucs/database/UcsBladeDaoImpl.java | 27 - .../com/cloud/ucs/database/UcsBladeVO.java | 102 - .../com/cloud/ucs/database/UcsManagerDao.java | 23 - .../cloud/ucs/database/UcsManagerDaoImpl.java | 26 - .../com/cloud/ucs/database/UcsManagerVO.java | 116 - .../com/cloud/ucs/manager/StringTemplate.java | 39 - .../com/cloud/ucs/manager/UcsCommands.java | 107 - .../com/cloud/ucs/manager/UcsHttpClient.java | 78 - .../com/cloud/ucs/manager/UcsManager.java | 45 - .../com/cloud/ucs/manager/UcsManagerImpl.java | 512 - .../com/cloud/ucs/structure/ComputeBlade.java | 220 - .../com/cloud/ucs/structure/UcsCookie.java | 38 - .../com/cloud/ucs/structure/UcsProfile.java | 56 - .../cloudstack/api/AddUcsManagerCmd.java | 120 - .../api/AssociateUcsProfileToBladeCmd.java | 100 - .../cloudstack/api/DeleteUcsManagerCmd.java | 76 - .../cloudstack/api/ListUcsBladeCmd.java | 83 - .../cloudstack/api/ListUcsManagerCmd.java | 95 - .../cloudstack/api/ListUcsProfileCmd.java | 81 - .../api/response/UcsBladeResponse.java | 86 - .../api/response/UcsManagerResponse.java | 78 - .../api/response/UcsProfileResponse.java | 39 - .../core/spring-ucs-core-context.xml | 35 - .../hypervisor/guru/VmwareVmImplementer.java | 12 +- .../vmware/resource/VmwareResource.java | 40 +- .../bigswitch/findbugsExcludeFilter.xml | 25 - plugins/network-elements/bigswitch/pom.xml | 30 - .../java/com/cloud/agent/api/BcfAnswer.java | 43 - .../java/com/cloud/agent/api/BcfCommand.java | 48 - .../agent/api/CacheBcfTopologyCommand.java | 39 - .../agent/api/CreateBcfAttachmentCommand.java | 75 - .../agent/api/CreateBcfRouterCommand.java | 32 - .../api/CreateBcfRouterInterfaceCommand.java | 57 - .../agent/api/CreateBcfSegmentCommand.java | 57 - .../agent/api/CreateBcfStaticNatCommand.java | 57 - .../agent/api/DeleteBcfAttachmentCommand.java | 45 - .../agent/api/DeleteBcfSegmentCommand.java | 39 - .../agent/api/DeleteBcfStaticNatCommand.java | 44 - .../agent/api/GetControllerDataAnswer.java | 46 - .../agent/api/GetControllerDataCommand.java | 23 - .../agent/api/GetControllerHostsAnswer.java | 40 - .../agent/api/GetControllerHostsCommand.java | 23 - .../agent/api/StartupBigSwitchBcfCommand.java | 30 - .../agent/api/SyncBcfTopologyCommand.java | 38 - .../agent/api/UpdateBcfAttachmentCommand.java | 51 - .../agent/api/UpdateBcfRouterCommand.java | 61 - .../commands/AddBigSwitchBcfDeviceCmd.java | 136 - .../com/cloud/api/commands/BcfConstants.java | 37 - .../commands/DeleteBigSwitchBcfDeviceCmd.java | 105 - .../commands/ListBigSwitchBcfDevicesCmd.java | 112 - .../response/BigSwitchBcfDeviceResponse.java | 99 - .../cloud/network/BigSwitchBcfDeviceVO.java | 153 - .../com/cloud/network/bigswitch/AclData.java | 118 - .../network/bigswitch/AttachmentData.java | 143 - .../network/bigswitch/BigSwitchBcfApi.java | 463 - .../bigswitch/BigSwitchBcfApiException.java | 55 - .../network/bigswitch/BigSwitchBcfUtils.java | 572 - .../network/bigswitch/BigSwitchStatus.java | 32 - .../cloud/network/bigswitch/Capabilities.java | 34 - .../network/bigswitch/ControlClusterData.java | 43 - .../bigswitch/ControlClusterStatus.java | 32 - .../network/bigswitch/ControllerData.java | 39 - .../network/bigswitch/FloatingIpData.java | 93 - .../cloud/network/bigswitch/NetworkData.java | 217 - .../cloud/network/bigswitch/RouterData.java | 131 - .../bigswitch/RouterInterfaceData.java | 67 - .../cloud/network/bigswitch/TopologyData.java | 249 - .../TrustingProtocolSocketFactory.java | 114 - .../cloud/network/dao/BigSwitchBcfDao.java | 35 - .../network/dao/BigSwitchBcfDaoImpl.java | 51 - .../network/element/BigSwitchBcfElement.java | 783 - .../element/BigSwitchBcfElementService.java | 41 - .../guru/BigSwitchBcfGuestNetworkGuru.java | 418 - .../resource/BigSwitchBcfResource.java | 587 - .../cloudstack/bigswitch/module.properties | 21 - .../bigswitch/spring-bigswitch-context.xml | 41 - .../network/bigswitch/BigSwitchApiTest.java | 433 - .../bigswitch/BigSwitchBcfUtilsTest.java | 100 - .../resource/BigSwitchBcfResourceTest.java | 431 - plugins/network-elements/brocade-vcs/pom.xml | 83 - .../api/AssociateMacToNetworkAnswer.java | 30 - .../api/AssociateMacToNetworkCommand.java | 48 - .../cloud/agent/api/CreateNetworkAnswer.java | 30 - .../cloud/agent/api/CreateNetworkCommand.java | 48 - .../cloud/agent/api/DeleteNetworkAnswer.java | 30 - .../cloud/agent/api/DeleteNetworkCommand.java | 43 - .../api/DisassociateMacFromNetworkAnswer.java | 30 - .../DisassociateMacFromNetworkCommand.java | 42 - .../agent/api/StartupBrocadeVcsCommand.java | 27 - .../api/commands/AddBrocadeVcsDeviceCmd.java | 122 - .../commands/DeleteBrocadeVcsDeviceCmd.java | 99 - .../ListBrocadeVcsDeviceNetworksCmd.java | 102 - .../commands/ListBrocadeVcsDevicesCmd.java | 108 - .../response/BrocadeVcsDeviceResponse.java | 94 - .../com/cloud/network/BrocadeVcsDeviceVO.java | 99 - .../BrocadeVcsNetworkVlanMappingVO.java | 72 - .../cloud/network/brocade/BrocadeVcsApi.java | 543 - .../brocade/BrocadeVcsApiException.java | 36 - .../com/cloud/network/brocade/Constants.java | 37 - .../com/cloud/network/dao/BrocadeVcsDao.java | 35 - .../cloud/network/dao/BrocadeVcsDaoImpl.java | 51 - .../dao/BrocadeVcsNetworkVlanMappingDao.java | 32 - .../BrocadeVcsNetworkVlanMappingDaoImpl.java | 47 - .../network/element/BrocadeVcsElement.java | 461 - .../element/BrocadeVcsElementService.java | 45 - .../guru/BrocadeVcsGuestNetworkGuru.java | 263 - .../network/resource/BrocadeVcsResource.java | 311 - .../main/resources/BrocadeInterfaceSchema.xsd | 51 - .../resources/BrocadePortProfileSchema.xsd | 118 - .../main/resources/BrocadeShowVcsSchema.xsd | 108 - .../META-INF/cloudstack/vcs/module.properties | 18 - .../cloudstack/vcs/spring-vcs-context.xml | 29 - .../network/brocade/BrocadeVcsApiTest.java | 185 - .../guru/BrocadeVcsGuestNetworkGuruTest.java | 593 - .../resource/BrocadeVcsResourceTest.java | 261 - plugins/network-elements/cisco-vnmc/pom.xml | 42 - ...iateAsaWithLogicalEdgeFirewallCommand.java | 53 - .../CleanupLogicalEdgeFirewallCommand.java | 43 - .../api/ConfigureNexusVsmForAsaCommand.java | 97 - .../api/CreateLogicalEdgeFirewallCommand.java | 92 - .../commands/AddCiscoAsa1000vResourceCmd.java | 125 - .../api/commands/AddCiscoVnmcResourceCmd.java | 121 - .../DeleteCiscoAsa1000vResourceCmd.java | 99 - .../commands/DeleteCiscoVnmcResourceCmd.java | 99 - .../ListCiscoAsa1000vResourcesCmd.java | 115 - .../commands/ListCiscoVnmcResourcesCmd.java | 109 - .../CiscoAsa1000vResourceResponse.java | 97 - .../response/CiscoVnmcResourceResponse.java | 85 - .../network/cisco/CiscoAsa1000vDevice.java | 41 - .../network/cisco/CiscoAsa1000vDeviceVO.java | 100 - .../network/cisco/CiscoVnmcConnection.java | 133 - .../cisco/CiscoVnmcConnectionImpl.java | 1330 -- .../network/cisco/CiscoVnmcController.java | 42 - .../network/cisco/CiscoVnmcControllerVO.java | 109 - .../network/cisco/NetworkAsa1000vMap.java | 32 - .../network/cisco/NetworkAsa1000vMapVO.java | 73 - .../cloud/network/dao/CiscoAsa1000vDao.java | 33 - .../network/dao/CiscoAsa1000vDaoImpl.java | 60 - .../com/cloud/network/dao/CiscoVnmcDao.java | 32 - .../cloud/network/dao/CiscoVnmcDaoImpl.java | 48 - .../network/dao/NetworkAsa1000vMapDao.java | 28 - .../dao/NetworkAsa1000vMapDaoImpl.java | 58 - .../network/element/CiscoAsa1000vService.java | 42 - .../network/element/CiscoVnmcElement.java | 932 - .../element/CiscoVnmcElementService.java | 39 - .../network/resource/CiscoVnmcResource.java | 759 - .../cloudstack/cisco-vnmc/module.properties | 18 - .../cisco-vnmc/spring-cisco-vnmc-context.xml | 40 - .../scripts/network/cisco/assoc-asa1000v.xml | 34 - .../cisco/associate-acl-policy-set.xml | 37 - .../network/cisco/associate-dhcp-policy.xml | 34 - .../network/cisco/associate-dhcp-server.xml | 32 - .../cisco/associate-nat-policy-set.xml | 35 - .../network/cisco/associate-route-policy.xml | 33 - .../network/cisco/create-acl-policy-ref.xml | 38 - .../network/cisco/create-acl-policy-set.xml | 36 - .../network/cisco/create-acl-policy.xml | 35 - .../cisco/create-acl-rule-for-dnat.xml | 82 - .../network/cisco/create-acl-rule-for-pf.xml | 156 - .../network/cisco/create-dhcp-policy.xml | 72 - .../network/cisco/create-dnat-rule.xml | 91 - .../cisco/create-edge-device-profile.xml | 32 - .../cisco/create-edge-device-route-policy.xml | 30 - .../cisco/create-edge-device-route.xml | 35 - .../network/cisco/create-edge-firewall.xml | 89 - .../cisco/create-edge-security-profile.xml | 41 - .../network/cisco/create-egress-acl-rule.xml | 168 - ...te-generic-egress-acl-no-protocol-rule.xml | 94 - .../cisco/create-generic-egress-acl-rule.xml | 121 - .../cisco/create-generic-ingress-acl-rule.xml | 121 - .../network/cisco/create-ingress-acl-rule.xml | 168 - .../scripts/network/cisco/create-ip-pool.xml | 58 - .../network/cisco/create-nat-policy-ref.xml | 38 - .../network/cisco/create-nat-policy-set.xml | 37 - .../network/cisco/create-nat-policy.xml | 33 - .../scripts/network/cisco/create-pf-rule.xml | 166 - .../network/cisco/create-port-pool.xml | 72 - .../network/cisco/create-source-nat-pool.xml | 58 - .../network/cisco/create-source-nat-rule.xml | 103 - .../scripts/network/cisco/create-tenant.xml | 29 - .../main/scripts/network/cisco/create-vdc.xml | 30 - .../network/cisco/delete-acl-policy-set.xml | 30 - .../network/cisco/delete-acl-policy.xml | 33 - .../network/cisco/delete-edge-firewall.xml | 30 - .../cisco/delete-edge-security-profile.xml | 38 - .../network/cisco/delete-nat-policy-set.xml | 30 - .../network/cisco/delete-nat-policy.xml | 33 - .../scripts/network/cisco/delete-rule.xml | 31 - .../scripts/network/cisco/delete-tenant.xml | 30 - .../main/scripts/network/cisco/delete-vdc.xml | 30 - .../network/cisco/disassoc-asa1000v.xml | 30 - .../network/cisco/list-acl-policies.xml | 31 - .../scripts/network/cisco/list-children.xml | 27 - .../network/cisco/list-nat-policies.xml | 31 - .../cisco/list-policyrefs-in-policyset.xml | 31 - .../scripts/network/cisco/list-tenants.xml | 26 - .../cisco/list-unassigned-asa1000v.xml | 39 - .../src/main/scripts/network/cisco/login.xml | 20 - .../cisco/CiscoVnmcConnectionTest.java | 148 - .../network/element/CiscoVnmcElementTest.java | 409 - .../resource/CiscoVnmcResourceTest.java | 255 - .../src/main/resources/components-example.xml | 10 - plugins/network-elements/globodns/pom.xml | 41 - .../cloudstack/api/AddGloboDnsHostCmd.java | 118 - .../commands/CreateOrUpdateDomainCommand.java | 44 - ...CreateOrUpdateRecordAndReverseCommand.java | 66 - .../commands/RemoveDomainCommand.java | 44 - .../commands/RemoveRecordCommand.java | 59 - .../cloudstack/commands/SignInCommand.java | 44 - .../cloudstack/element/GloboDnsElement.java | 384 - .../element/GloboDnsElementService.java | 25 - .../cloudstack/resource/GloboDnsResource.java | 454 - .../response/GloboDnsDomainListResponse.java | 38 - .../response/GloboDnsDomainResponse.java | 36 - .../response/GloboDnsExportResponse.java | 36 - .../response/GloboDnsRecordListResponse.java | 38 - .../response/GloboDnsRecordResponse.java | 36 - .../cloudstack/globodns/module.properties | 18 - .../globodns/spring-globodns-context.xml | 22 - .../element/GloboDnsElementTest.java | 266 - .../resource/GloboDnsResourceTest.java | 456 - .../globodns/src/test/resources/db.properties | 73 - .../src/test/resources/log4j.properties | 33 - .../network-elements/juniper-contrail/pom.xml | 146 - .../api/command/CreateServiceInstanceCmd.java | 201 - .../api/response/ServiceInstanceResponse.java | 99 - .../contrail/management/ContrailElement.java | 28 - .../management/ContrailElementImpl.java | 384 - .../contrail/management/ContrailGuru.java | 392 - .../contrail/management/ContrailManager.java | 143 - .../management/ContrailManagerImpl.java | 1018 -- .../management/ContrailVpcElementImpl.java | 204 - .../contrail/management/DBSyncGeneric.java | 333 - .../contrail/management/EventUtils.java | 180 - .../management/ManagementNetworkGuru.java | 128 - .../contrail/management/ModelDatabase.java | 104 - .../contrail/management/ServerDBSync.java | 42 - .../contrail/management/ServerDBSyncImpl.java | 1178 -- .../management/ServerEventHandler.java | 22 - .../management/ServerEventHandlerImpl.java | 241 - .../contrail/management/ServiceManager.java | 41 - .../management/ServiceManagerImpl.java | 253 - .../management/ServiceVirtualMachine.java | 28 - .../contrail/model/FloatingIpModel.java | 211 - .../contrail/model/FloatingIpPoolModel.java | 169 - .../contrail/model/InstanceIpModel.java | 170 - .../contrail/model/ModelController.java | 86 - .../network/contrail/model/ModelObject.java | 150 - .../contrail/model/ModelObjectBase.java | 130 - .../contrail/model/NetworkPolicyModel.java | 303 - .../contrail/model/ServiceInstanceModel.java | 285 - .../contrail/model/VMInterfaceModel.java | 263 - .../contrail/model/VirtualMachineModel.java | 388 - .../contrail/model/VirtualNetworkModel.java | 584 - .../cloudstack/contrail/module.properties | 18 - .../contrail/spring-contrail-context.xml | 54 - ...ng-contrail-system-context-inheritable.xml | 41 - .../management/ApiConnectorMockito.java | 125 - .../IntegrationTestConfiguration.java | 757 - .../management/ManagementServerMock.java | 380 - .../management/MockAccountManager.java | 617 - .../management/NetworkProviderTest.java | 466 - .../management/ProviderTestConfiguration.java | 30 - .../management/PublicNetworkTest.java | 144 - .../PublicNetworkTestConfiguration.java | 31 - .../contrail/management/TestDbSetup.java | 142 - .../contrail/model/InstanceIpModelTest.java | 128 - .../network/contrail/model/MockNetworkVO.java | 50 - .../contrail/model/VMInterfaceModelTest.java | 133 - .../model/VirtualMachineModelTest.java | 110 - .../model/VirtualNetworkModelTest.java | 205 - .../src/test/resources/commonContext.xml | 92 - .../src/test/resources/contrail.properties | 19 - .../src/test/resources/db.properties | 68 - .../src/test/resources/log4j.properties | 34 - .../src/test/resources/mysql_db_start.sh | 51 - .../src/test/resources/mysql_db_stop.sh | 29 - .../src/test/resources/providerContext.xml | 34 - .../test/resources/publicNetworkContext.xml | 26 - plugins/network-elements/nicira-nvp/pom.xml | 60 - ...tForwardingRulesOnLogicalRouterAnswer.java | 35 - ...ForwardingRulesOnLogicalRouterCommand.java | 63 - ...nfigurePublicIpsOnLogicalRouterAnswer.java | 32 - ...figurePublicIpsOnLogicalRouterCommand.java | 66 - .../api/ConfigureSharedNetworkUuidAnswer.java | 32 - .../ConfigureSharedNetworkUuidCommand.java | 85 - .../ConfigureSharedNetworkVlanIdAnswer.java | 31 - .../ConfigureSharedNetworkVlanIdCommand.java | 84 - ...reStaticNatRulesOnLogicalRouterAnswer.java | 44 - ...eStaticNatRulesOnLogicalRouterCommand.java | 65 - .../agent/api/CreateLogicalRouterAnswer.java | 42 - .../agent/api/CreateLogicalRouterCommand.java | 116 - .../agent/api/CreateLogicalSwitchAnswer.java | 38 - .../agent/api/CreateLogicalSwitchCommand.java | 57 - .../api/CreateLogicalSwitchPortAnswer.java | 38 - .../api/CreateLogicalSwitchPortCommand.java | 56 - .../agent/api/DeleteLogicalRouterAnswer.java | 34 - .../agent/api/DeleteLogicalRouterCommand.java | 44 - .../api/DeleteLogicalRouterPortAnswer.java | 31 - .../api/DeleteLogicalRouterPortCommand.java | 53 - .../agent/api/DeleteLogicalSwitchAnswer.java | 32 - .../agent/api/DeleteLogicalSwitchCommand.java | 38 - .../api/DeleteLogicalSwitchPortAnswer.java | 32 - .../api/DeleteLogicalSwitchPortCommand.java | 44 - .../agent/api/FindL2GatewayServiceAnswer.java | 38 - .../api/FindL2GatewayServiceCommand.java | 46 - .../api/FindLogicalRouterPortAnswer.java | 38 - .../api/FindLogicalRouterPortCommand.java | 59 - .../api/FindLogicalSwitchPortAnswer.java | 38 - .../api/FindLogicalSwitchPortCommand.java | 44 - .../agent/api/StartupNiciraNvpCommand.java | 30 - .../api/UpdateLogicalSwitchPortAnswer.java | 38 - .../api/UpdateLogicalSwitchPortCommand.java | 63 - .../api/commands/AddNiciraNvpDeviceCmd.java | 158 - .../commands/DeleteNiciraNvpDeviceCmd.java | 106 - .../ListNiciraNvpDeviceNetworksCmd.java | 109 - .../api/commands/ListNiciraNvpDevicesCmd.java | 108 - .../api/response/NiciraNvpDeviceResponse.java | 96 - .../com/cloud/network/NiciraNvpDeviceVO.java | 99 - .../cloud/network/NiciraNvpNicMappingVO.java | 87 - .../network/NiciraNvpRouterMappingVO.java | 85 - .../com/cloud/network/dao/NiciraNvpDao.java | 35 - .../cloud/network/dao/NiciraNvpDaoImpl.java | 51 - .../network/dao/NiciraNvpNicMappingDao.java | 32 - .../dao/NiciraNvpNicMappingDaoImpl.java | 49 - .../dao/NiciraNvpRouterMappingDao.java | 30 - .../dao/NiciraNvpRouterMappingDaoImpl.java | 58 - .../network/element/NiciraNvpElement.java | 918 - .../element/NiciraNvpElementService.java | 45 - .../guru/NiciraNvpGuestNetworkGuru.java | 368 - .../network/nicira/AccessConfiguration.java | 44 - .../com/cloud/network/nicira/AccessRule.java | 58 - .../java/com/cloud/network/nicira/Acl.java | 23 - .../com/cloud/network/nicira/AclRule.java | 209 - .../com/cloud/network/nicira/Attachment.java | 24 - .../network/nicira/BaseNiciraEntity.java | 85 - .../network/nicira/BaseNiciraNamedEntity.java | 44 - .../network/nicira/ControlClusterStatus.java | 105 - .../network/nicira/DestinationNatRule.java | 113 - .../network/nicira/ExecutionCounter.java | 54 - .../network/nicira/GatewayServiceConfig.java | 47 - .../network/nicira/L2GatewayAttachment.java | 53 - .../nicira/L2GatewayServiceConfig.java | 30 - .../network/nicira/L3GatewayAttachment.java | 55 - .../cloud/network/nicira/LogicalRouter.java | 71 - .../network/nicira/LogicalRouterPort.java | 62 - .../cloud/network/nicira/LogicalSwitch.java | 60 - .../network/nicira/LogicalSwitchPort.java | 82 - .../java/com/cloud/network/nicira/Match.java | 146 - .../com/cloud/network/nicira/NatRule.java | 130 - .../cloud/network/nicira/NatRuleAdapter.java | 49 - .../cloud/network/nicira/NiciraConstants.java | 45 - .../cloud/network/nicira/NiciraNvpApi.java | 663 - .../network/nicira/NiciraNvpApiException.java | 64 - .../cloud/network/nicira/NiciraNvpList.java | 48 - .../cloud/network/nicira/NiciraNvpTag.java | 65 - .../network/nicira/NiciraRestClient.java | 204 - .../cloud/network/nicira/PatchAttachment.java | 41 - .../cloud/network/nicira/RouterNextHop.java | 40 - .../cloud/network/nicira/RoutingConfig.java | 24 - .../network/nicira/RoutingConfigAdapter.java | 52 - .../nicira/RoutingTableRoutingConfig.java | 30 - .../cloud/network/nicira/SecurityProfile.java | 24 - .../cloud/network/nicira/SecurityRule.java | 138 - ...ngleDefaultRouteImplicitRoutingConfig.java | 40 - .../cloud/network/nicira/SourceNatRule.java | 119 - .../network/nicira/TransportZoneBinding.java | 50 - .../cloud/network/nicira/VifAttachment.java | 78 - .../resource/NiciraNvpRequestWrapper.java | 77 - .../network/resource/NiciraNvpResource.java | 357 - .../network/resource/NiciraNvpUtilities.java | 65 - .../NiciraCheckHealthCommandWrapper.java | 61 - ...gurePortForwardingRulesCommandWrapper.java | 120 - ...raNvpConfigurePublicIpsCommandWrapper.java | 61 - ...figureSharedNetworkUuidCommandWrapper.java | 194 - ...gureSharedNetworkVlanIdCommandWrapper.java | 116 - ...ConfigureStaticNatRulesCommandWrapper.java | 112 - ...aNvpCreateLogicalRouterCommandWrapper.java | 150 - ...aNvpCreateLogicalSwitchCommandWrapper.java | 73 - ...CreateLogicalSwitchPortCommandWrapper.java | 68 - ...aNvpDeleteLogicalRouterCommandWrapper.java | 50 - ...DeleteLogicalRouterPortCommandWrapper.java | 57 - ...aNvpDeleteLogicalSwitchCommandWrapper.java | 49 - ...DeleteLogicalSwitchPortCommandWrapper.java | 50 - ...NvpFindL2GatewayServiceCommandWrapper.java | 67 - ...vpFindLogicalRouterPortCommandWrapper.java | 66 - ...vpFindLogicalSwitchPortCommandWrapper.java | 60 - .../NiciraNvpMaintainCommandWrapper.java | 36 - .../wrapper/NiciraNvpReadyCommandWrapper.java | 36 - ...UpdateLogicalSwitchPortCommandWrapper.java | 68 - .../network/utils/CommandRetryUtility.java | 90 - .../META-INF/cloudstack/nvp/module.properties | 21 - .../cloudstack/nvp/spring-nvp-context.xml | 42 - .../network/element/NiciraNvpElementTest.java | 421 - .../guru/NiciraNvpGuestNetworkGuruTest.java | 478 - .../network/nicira/ExecutionCounterTest.java | 102 - .../network/nicira/NatRuleAdapterTest.java | 60 - .../com/cloud/network/nicira/NatRuleTest.java | 55 - .../cloud/network/nicira/NiciraNvpApiIT.java | 337 - .../network/nicira/NiciraNvpApiTest.java | 198 - .../network/nicira/NiciraRestClientTest.java | 212 - .../cloud/network/nicira/NiciraTagTest.java | 58 - .../nicira/RoutingConfigAdapterTest.java | 57 - .../resource/NiciraNvpRequestWrapperTest.java | 250 - .../resource/NiciraNvpResourceTest.java | 825 - .../NiciraCheckHealthCommandWrapperTest.java | 80 - .../src/test/resources/config.properties | 22 - .../network-elements/stratosphere-ssp/pom.xml | 31 - .../cloudstack/api/commands/AddSspCmd.java | 136 - .../cloudstack/api/commands/DeleteSspCmd.java | 72 - .../cloudstack/api/response/SspResponse.java | 77 - .../network/dao/SspCredentialDao.java | 33 - .../network/dao/SspCredentialDaoImpl.java | 40 - .../network/dao/SspCredentialVO.java | 70 - .../cloudstack/network/dao/SspTenantDao.java | 34 - .../network/dao/SspTenantDaoImpl.java | 45 - .../cloudstack/network/dao/SspTenantVO.java | 55 - .../cloudstack/network/dao/SspUuidDao.java | 40 - .../network/dao/SspUuidDaoImpl.java | 112 - .../cloudstack/network/dao/SspUuidVO.java | 80 - .../cloudstack/network/element/SspClient.java | 199 - .../network/element/SspElement.java | 588 - .../network/element/SspManager.java | 70 - .../network/element/SspService.java | 47 - .../network/guru/SspGuestNetworkGuru.java | 152 - .../META-INF/cloudstack/ssp/module.properties | 18 - .../cloudstack/ssp/spring-ssp-context.xml | 41 - .../network/element/SspClientTest.java | 82 - .../network/element/SspElementTest.java | 154 - .../stratosphere-ssp/sspmock/sspmock.py | 99 - plugins/pom.xml | 15 - plugins/storage/volume/cloudbyte/pom.xml | 71 - .../ElastistorPrimaryDataStoreDriver.java | 437 - .../ElastistorPrimaryDataStoreLifeCycle.java | 601 - .../provider/ElastistorHostListener.java | 149 - .../ElastistorPrimaryDataStoreProvider.java | 143 - .../datastore/util/ElastistorUtil.java | 2608 --- .../util/ElastistorVolumeApiService.java | 33 - .../util/ElastistorVolumeApiServiceImpl.java | 206 - .../util/ListElastistorInterfaceCmd.java | 74 - .../util/ListElastistorInterfaceResponse.java | 66 - .../datastore/util/ListElastistorPoolCmd.java | 77 - .../util/ListElastistorPoolResponse.java | 117 - .../util/ListElastistorVolumeCmd.java | 75 - .../util/ListElastistorVolumeResponse.java | 102 - .../module.properties | 21 - ...pring-storage-volume-cloudbyte-context.xml | 40 - plugins/storage/volume/datera/pom.xml | 63 - .../driver/DateraPrimaryDataStoreDriver.java | 1896 -- .../DateraPrimaryDataStoreLifeCycle.java | 420 - .../provider/DateraHostListener.java | 350 - .../DateraPrimaryDataStoreProvider.java | 83 - .../storage/datastore/util/DateraObject.java | 470 - .../storage/datastore/util/DateraUtil.java | 1029 -- .../storage-volume-datera/module.properties | 18 - .../spring-storage-volume-datera-context.xml | 33 - plugins/storage/volume/nexenta/pom.xml | 52 - .../driver/NexentaPrimaryDataStoreDriver.java | 274 - .../NexentaPrimaryDataStoreLifeCycle.java | 202 - .../provider/NexentaHostListener.java | 68 - .../NexentaPrimaryDataStoreProvider.java | 81 - .../datastore/util/NexentaNmsClient.java | 237 - .../storage/datastore/util/NexentaNmsUrl.java | 85 - .../datastore/util/NexentaStorAppliance.java | 418 - .../storage/datastore/util/NexentaUtil.java | 242 - .../module.properties | 18 - .../spring-storage-volume-nexenta-context.xml | 32 - .../util/NexentaStorApplianceTest.java | 335 - .../datastore/util/NexentaUtilTest.java | 135 - plugins/storage/volume/solidfire/pom.xml | 74 - .../SolidFirePrimaryDataStoreDriver.java | 1683 -- ...SolidFireSharedPrimaryDataStoreDriver.java | 20 - .../SolidFirePrimaryDataStoreLifeCycle.java | 395 - ...idFireSharedPrimaryDataStoreLifeCycle.java | 763 - .../provider/SolidFireHostListener.java | 299 - .../SolidFirePrimaryDataStoreProvider.java | 83 - .../provider/SolidFireSharedHostListener.java | 236 - ...lidFireSharedPrimaryDataStoreProvider.java | 83 - .../storage/datastore/util/SolidFireUtil.java | 1414 -- .../module.properties | 18 - ...pring-storage-volume-solidfire-context.xml | 35 - .../storage/test/AopTestAdvice.java | 34 - .../storage/test/ChildTestConfiguration.java | 53 - .../storage/test/TestConfiguration.java | 39 - .../cloudstack/storage/test/VolumeTest.java | 129 - .../src/test/resource/storageContext.xml | 52 - plugins/user-authenticators/md5/pom.xml | 30 - .../cloudstack/auth/MD5UserAuthenticator.java | 86 - .../META-INF/cloudstack/md5/module.properties | 18 - .../cloudstack/md5/spring-md5-context.xml | 34 - .../auth/MD5UserAuthenticatorTest.java | 82 - .../user-authenticators/plain-text/pom.xml | 30 - .../auth/PlainTextUserAuthenticator.java | 63 - .../cloudstack/plaintext/module.properties | 18 - .../plaintext/spring-plaintext-context.xml | 35 - pom.xml | 6 - quickcloud/pom.xml | 30 - ...pring-quickcloud-core-context-override.xml | 32 - .../java/com/cloud/api/ApiResponseHelper.java | 1 - .../com/cloud/api/doc/ApiXmlDocWriter.java | 4 +- .../java/com/cloud/configuration/Config.java | 29 +- .../ConfigurationManagerImpl.java | 12 +- .../com/cloud/network/NetworkModelImpl.java | 8 - .../com/cloud/network/NetworkServiceImpl.java | 12 +- .../cloud/network/guru/DirectNetworkGuru.java | 5 +- .../network/router/NetworkHelperImpl.java | 3 +- .../VirtualNetworkApplianceManager.java | 4 - .../VirtualNetworkApplianceManagerImpl.java | 1 - .../com/cloud/network/vpc/VpcManagerImpl.java | 18 +- .../cloud/resource/ResourceManagerImpl.java | 10 +- .../cloud/server/ConfigurationServerImpl.java | 3 - .../cloud/server/ManagementServerImpl.java | 8 +- .../com/cloud/storage/OCFS2ManagerImpl.java | 1 + .../com/cloud/storage/StorageManagerImpl.java | 2 +- .../storage/listener/StoragePoolMonitor.java | 4 +- .../storage/snapshot/SnapshotManagerImpl.java | 4 - .../java/com/cloud/vm/UserVmManagerImpl.java | 10 +- server/src/test/async-job-component.xml | 3 - .../com/cloud/api/ApiResponseHelperTest.java | 4 +- .../network/guru/DirectNetworkGuruTest.java | 1 - .../com/cloud/vpc/MockNetworkManagerImpl.java | 4 +- .../integration/component/test_asa1000v_fw.py | 136 - .../component/test_bigswitch_bcf.py | 776 - .../integration/component/test_brocade_vcs.py | 331 - .../integration/plugins/datera/TestVolumes.py | 1127 -- .../plugins/solidfire/TestAddRemoveHosts.py | 957 - .../solidfire/TestCapacityManagement.py | 333 - .../TestManagedClusteredFilesystems.py | 431 - .../plugins/solidfire/TestManagedSystemVMs.py | 626 - .../solidfire/TestOnlineStorageMigration.py | 402 - .../plugins/solidfire/TestSnapshots.py | 1769 -- .../plugins/solidfire/TestUploadDownload.py | 516 - .../solidfire/TestVMMigrationWithStorage.py | 707 - .../plugins/solidfire/TestVMSnapshots.py | 784 - .../plugins/solidfire/TestVolumes.py | 2712 --- .../plugins/solidfire/util/sf_util.py | 331 - .../plugins/test_nicira_controller.py | 584 - tools/apidoc/gen_toc.py | 7 - tools/marvin/marvin/deployDataCenter.py | 21 +- tools/marvin/marvin/lib/base.py | 86 - tools/ngui/README.md | 21 - tools/ngui/api.py | 37 - tools/ngui/app.py | 38 - tools/ngui/config.py | 21 - tools/ngui/precache.py | 19 - tools/ngui/requester.py | 153 - .../bootstrap/css/bootstrap-responsive.css | 1109 -- .../css/bootstrap-responsive.min.css | 9 - tools/ngui/static/bootstrap/css/bootstrap.css | 6315 ------- .../static/bootstrap/css/bootstrap.min.css | 874 - .../img/glyphicons-halflings-white.png | Bin 8660 -> 0 bytes .../bootstrap/img/glyphicons-halflings.png | Bin 12020 -> 0 bytes tools/ngui/static/bootstrap/js/bootstrap.js | 2291 --- .../ngui/static/bootstrap/js/bootstrap.min.js | 7 - tools/ngui/static/css/app.css | 45 - tools/ngui/static/images/ajax-inverse.gif | Bin 6488 -> 0 bytes tools/ngui/static/images/ajax-loader.gif | Bin 3208 -> 0 bytes tools/ngui/static/js/app/accounts/accounts.js | 102 - .../static/js/app/accounts/accounts.tpl.html | 36 - tools/ngui/static/js/app/app.js | 77 - .../ngui/static/js/app/dashboard/dashboard.js | 16 - tools/ngui/static/js/app/domains/domains.js | 37 - tools/ngui/static/js/app/events/events.js | 37 - .../js/app/globalsettings/globalsettings.js | 38 - .../globalsettings/globalsettings.tpl.html | 37 - .../js/app/infrastructure/infrastructure.js | 16 - .../app/instances/instance-details.tpl.html | 24 - .../ngui/static/js/app/instances/instances.js | 54 - .../js/app/instances/instances.tpl.html | 54 - tools/ngui/static/js/app/networks/networks.js | 37 - tools/ngui/static/js/app/projects/projects.js | 37 - .../app/serviceofferings/serviceofferings.js | 37 - tools/ngui/static/js/app/storage/storage.js | 153 - .../static/js/app/storage/storage.tpl.html | 51 - .../js/app/storage/upload-volume.tpl.html | 18 - .../ngui/static/js/app/templates/templates.js | 37 - tools/ngui/static/js/common/dictionary.js | 68 - .../static/js/common/directives/confirm.js | 43 - .../js/common/directives/edit-in-place.js | 49 - .../common/directives/edit-in-place.tpl.html | 26 - .../ngui/static/js/common/directives/label.js | 42 - .../static/js/common/directives/modal-form.js | 70 - .../js/common/directives/modal-form.tpl.html | 42 - .../static/js/common/resources/accounts.js | 41 - .../js/common/resources/configurations.js | 44 - .../js/common/resources/diskofferings.js | 33 - .../static/js/common/resources/domains.js | 33 - .../ngui/static/js/common/resources/events.js | 33 - .../static/js/common/resources/networks.js | 33 - .../static/js/common/resources/projects.js | 33 - .../js/common/resources/serviceofferings.js | 33 - .../static/js/common/resources/snapshots.js | 33 - .../static/js/common/resources/templates.js | 33 - .../ngui/static/js/common/resources/users.js | 40 - .../js/common/resources/virtualmachines.js | 75 - .../static/js/common/resources/volumes.js | 33 - .../ngui/static/js/common/resources/zones.js | 33 - .../static/js/common/services/breadcrumbs.js | 32 - .../js/common/services/helperfunctions.js | 39 - .../js/common/services/notifications.js | 34 - .../static/js/common/services/requester.js | 46 - tools/ngui/static/js/lib/angular-ui.min.js | 2 - tools/ngui/static/js/lib/angular.js | 14847 ---------------- tools/ngui/static/js/lib/jquery-1.7.2.js | 9404 ---------- tools/ngui/templates/index.html | 146 - .../nvp/plugin/NiciraNvpApiVersion.java | 50 - .../vmware/mo/HypervisorHostHelper.java | 16 +- 767 files changed, 378 insertions(+), 142599 deletions(-) delete mode 100755 cloud-cli/bindir/cloud-tool delete mode 100644 cloud-cli/cloudapis/__init__.py delete mode 100644 cloud-cli/cloudapis/cloud.py delete mode 100644 cloud-cli/cloudtool/__init__.py delete mode 100644 cloud-cli/cloudtool/utils.py create mode 100644 docs/AUDIT.md delete mode 100644 plugins/api/solidfire-intg-test/pom.xml delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetPathForVolumeCmd.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireAccountIdCmd.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeAccessGroupIdsCmd.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeSizeCmd.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeSnapshotDetailsCmd.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeiScsiNameCmd.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireAccountIdResponse.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeAccessGroupIdsResponse.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeSizeResponse.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeSnapshotDetailsResponse.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeiScsiNameResponse.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestService.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestServiceImpl.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManager.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManagerImpl.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/util/solidfire/SolidFireIntegrationTestUtil.java delete mode 100644 plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/module.properties delete mode 100644 plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/spring-solidfire-intg-test-context.xml delete mode 100644 plugins/hypervisors/ovm/pom.xml delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmDiscoverer.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmFencer.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmGuru.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmHelper.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmResourceBase.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Coder.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Connection.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmBridge.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmDisk.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmHost.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmObject.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmSecurityGroup.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmStoragePool.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVif.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVlan.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVm.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVolume.java delete mode 100644 plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Test.java delete mode 100644 plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/module.properties delete mode 100644 plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/spring-ovm-compute-context.xml delete mode 100644 plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/module.properties delete mode 100644 plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/spring-ovm-discoverer-context.xml delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/ConfigFileOps.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmCommonModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDiskModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDispatcher.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmFaultConstants.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHostModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmLoggerModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmNetworkModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmObjectModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmSecurityGroupModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmStoragePoolModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVifModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVmModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVolumeModule.py delete mode 100755 plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/configureOvm.sh delete mode 100644 plugins/hypervisors/ovm3/.gitignore delete mode 100644 plugins/hypervisors/ovm3/pom.xml delete mode 100644 plugins/hypervisors/ovm3/sonar-project.properties delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/ha/Ovm3Investigator.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/CloudstackPlugin.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Cluster.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Common.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Connection.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Linux.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Network.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ntp.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ovm3ResourceException.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/OvmObject.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Pool.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Remote.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Repository.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/RpcTypeFactory.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/StoragePlugin.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Xen.java delete mode 100755 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3Discoverer.java delete mode 100755 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3FenceBuilder.java delete mode 100755 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorGuru.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResource.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessor.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResource.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3Configuration.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetwork.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupport.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3StoragePool.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupport.java delete mode 100755 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmGuestTypes.java delete mode 100644 plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupport.java delete mode 100644 plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/module.properties delete mode 100644 plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/spring-ovm3-compute-context.xml delete mode 100644 plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/module.properties delete mode 100644 plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/spring-ovm3-discoverer-context.xml delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CloudStackPluginTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CommonTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/ConnectionTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/LinuxTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NetworkTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NtpTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2Test.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RemoteTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RepositoryTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/StoragePluginTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XenTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XmlTestResultTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResourceTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessorTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResourceTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3ConfigurationTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3GuestTypesTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetworkTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupportTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupportTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupportTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/support/Ovm3SupportTest.java delete mode 100644 plugins/hypervisors/ovm3/src/test/resources/log4j.properties delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/clean_primary.sh delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/clean_secondary.sh delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/create_pool_cluster.py delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/info.py delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/password.py delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/repo_pool.py delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/simple_pool.py delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/socat.sh delete mode 100755 plugins/hypervisors/ovm3/src/test/resources/scripts/tail.sh delete mode 100644 plugins/hypervisors/ucs/pom.xml delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDao.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDaoImpl.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeVO.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDao.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDaoImpl.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerVO.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/StringTemplate.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsCommands.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsHttpClient.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManager.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManagerImpl.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/ComputeBlade.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsCookie.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsProfile.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AddUcsManagerCmd.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AssociateUcsProfileToBladeCmd.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/DeleteUcsManagerCmd.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsBladeCmd.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsManagerCmd.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsProfileCmd.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsBladeResponse.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsManagerResponse.java delete mode 100644 plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsProfileResponse.java delete mode 100644 plugins/hypervisors/ucs/src/main/resources/META-INF/cloudstack/core/spring-ucs-core-context.xml delete mode 100644 plugins/network-elements/bigswitch/findbugsExcludeFilter.xml delete mode 100644 plugins/network-elements/bigswitch/pom.xml delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfAnswer.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CacheBcfTopologyCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfAttachmentCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterInterfaceCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfSegmentCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfStaticNatCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfAttachmentCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfSegmentCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfStaticNatCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataAnswer.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsAnswer.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/StartupBigSwitchBcfCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/SyncBcfTopologyCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfAttachmentCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfRouterCommand.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/AddBigSwitchBcfDeviceCmd.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/BcfConstants.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/DeleteBigSwitchBcfDeviceCmd.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/ListBigSwitchBcfDevicesCmd.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/api/response/BigSwitchBcfDeviceResponse.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/BigSwitchBcfDeviceVO.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AclData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AttachmentData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApi.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApiException.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfUtils.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchStatus.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/Capabilities.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterStatus.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControllerData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/FloatingIpData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/NetworkData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterInterfaceData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TopologyData.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TrustingProtocolSocketFactory.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDao.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDaoImpl.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElement.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElementService.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/guru/BigSwitchBcfGuestNetworkGuru.java delete mode 100644 plugins/network-elements/bigswitch/src/main/java/com/cloud/network/resource/BigSwitchBcfResource.java delete mode 100644 plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/module.properties delete mode 100644 plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/spring-bigswitch-context.xml delete mode 100644 plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchApiTest.java delete mode 100644 plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchBcfUtilsTest.java delete mode 100644 plugins/network-elements/bigswitch/src/test/java/com/cloud/network/resource/BigSwitchBcfResourceTest.java delete mode 100644 plugins/network-elements/brocade-vcs/pom.xml delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkAnswer.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkCommand.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkAnswer.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkCommand.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkAnswer.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkCommand.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkAnswer.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkCommand.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/StartupBrocadeVcsCommand.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/AddBrocadeVcsDeviceCmd.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/DeleteBrocadeVcsDeviceCmd.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDeviceNetworksCmd.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDevicesCmd.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/response/BrocadeVcsDeviceResponse.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsDeviceVO.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsNetworkVlanMappingVO.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApiException.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/Constants.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDao.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDaoImpl.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElement.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElementService.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/resource/BrocadeVcsResource.java delete mode 100644 plugins/network-elements/brocade-vcs/src/main/resources/BrocadeInterfaceSchema.xsd delete mode 100644 plugins/network-elements/brocade-vcs/src/main/resources/BrocadePortProfileSchema.xsd delete mode 100644 plugins/network-elements/brocade-vcs/src/main/resources/BrocadeShowVcsSchema.xsd delete mode 100644 plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/module.properties delete mode 100644 plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/spring-vcs-context.xml delete mode 100644 plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/brocade/BrocadeVcsApiTest.java delete mode 100644 plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuruTest.java delete mode 100644 plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/resource/BrocadeVcsResourceTest.java delete mode 100644 plugins/network-elements/cisco-vnmc/pom.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/AssociateAsaWithLogicalEdgeFirewallCommand.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CleanupLogicalEdgeFirewallCommand.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoAsa1000vResourceCmd.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoVnmcResourceCmd.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoAsa1000vResourceCmd.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoVnmcResourceCmd.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoAsa1000vResourcesCmd.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoVnmcResourcesCmd.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoAsa1000vResourceResponse.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoVnmcResourceResponse.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDevice.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDeviceVO.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnection.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcController.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcControllerVO.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMap.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMapVO.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDao.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDaoImpl.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDao.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDaoImpl.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDao.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDaoImpl.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoAsa1000vService.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElement.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElementService.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/resource/CiscoVnmcResource.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/module.properties delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/assoc-asa1000v.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-acl-policy-set.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-policy.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-server.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-nat-policy-set.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-route-policy.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-ref.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-set.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-dnat.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-pf.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dhcp-policy.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dnat-rule.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-profile.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route-policy.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-firewall.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-security-profile.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-egress-acl-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-no-protocol-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-ingress-acl-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ingress-acl-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ip-pool.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-ref.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-set.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-pf-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-port-pool.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-pool.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-rule.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-tenant.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-vdc.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy-set.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-firewall.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-security-profile.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy-set.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-rule.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-tenant.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-vdc.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/disassoc-asa1000v.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-acl-policies.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-children.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-nat-policies.xml delete mode 100755 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-policyrefs-in-policyset.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-tenants.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-unassigned-asa1000v.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/login.xml delete mode 100644 plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/cisco/CiscoVnmcConnectionTest.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/element/CiscoVnmcElementTest.java delete mode 100644 plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/resource/CiscoVnmcResourceTest.java delete mode 100644 plugins/network-elements/globodns/pom.xml delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/api/AddGloboDnsHostCmd.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateDomainCommand.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateRecordAndReverseCommand.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveDomainCommand.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveRecordCommand.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/SignInCommand.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElement.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElementService.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/resource/GloboDnsResource.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainListResponse.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainResponse.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsExportResponse.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordListResponse.java delete mode 100644 plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordResponse.java delete mode 100644 plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/module.properties delete mode 100644 plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/spring-globodns-context.xml delete mode 100644 plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/element/GloboDnsElementTest.java delete mode 100644 plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/resource/GloboDnsResourceTest.java delete mode 100644 plugins/network-elements/globodns/src/test/resources/db.properties delete mode 100644 plugins/network-elements/globodns/src/test/resources/log4j.properties delete mode 100644 plugins/network-elements/juniper-contrail/pom.xml delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElement.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailGuru.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManager.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailVpcElementImpl.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/EventUtils.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ModelDatabase.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSync.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManager.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelController.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObject.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java delete mode 100644 plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/module.properties delete mode 100644 plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml delete mode 100644 plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/system/spring-contrail-system-context-inheritable.xml delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/MockAccountManager.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/TestDbSetup.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/InstanceIpModelTest.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/MockNetworkVO.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModelTest.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/commonContext.xml delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/contrail.properties delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/db.properties delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/log4j.properties delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_start.sh delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_stop.sh delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/providerContext.xml delete mode 100644 plugins/network-elements/juniper-contrail/src/test/resources/publicNetworkContext.xml delete mode 100644 plugins/network-elements/nicira-nvp/pom.xml delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/GatewayServiceConfig.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayAttachment.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayServiceConfig.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkUuidCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkVlanIdCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterPortCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindL2GatewayServiceCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalRouterPortCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java delete mode 100644 plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties delete mode 100644 plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapperTest.java delete mode 100644 plugins/network-elements/nicira-nvp/src/test/resources/config.properties delete mode 100644 plugins/network-elements/stratosphere-ssp/pom.xml delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/AddSspCmd.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/DeleteSspCmd.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/response/SspResponse.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDao.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDaoImpl.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialVO.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDao.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDaoImpl.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantVO.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDao.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDaoImpl.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidVO.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspClient.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspElement.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspManager.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspService.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/guru/SspGuestNetworkGuru.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/module.properties delete mode 100644 plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml delete mode 100644 plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspClientTest.java delete mode 100644 plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspElementTest.java delete mode 100644 plugins/network-elements/stratosphere-ssp/sspmock/sspmock.py delete mode 100644 plugins/storage/volume/cloudbyte/pom.xml delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/driver/ElastistorPrimaryDataStoreDriver.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorHostListener.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorPrimaryDataStoreProvider.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorUtil.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiService.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiServiceImpl.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceCmd.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceResponse.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolCmd.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolResponse.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeCmd.java delete mode 100644 plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeResponse.java delete mode 100755 plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/module.properties delete mode 100755 plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/spring-storage-volume-cloudbyte-context.xml delete mode 100644 plugins/storage/volume/datera/pom.xml delete mode 100644 plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/driver/DateraPrimaryDataStoreDriver.java delete mode 100644 plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/DateraPrimaryDataStoreLifeCycle.java delete mode 100644 plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraHostListener.java delete mode 100644 plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraPrimaryDataStoreProvider.java delete mode 100644 plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraObject.java delete mode 100644 plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraUtil.java delete mode 100644 plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/module.properties delete mode 100644 plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/spring-storage-volume-datera-context.xml delete mode 100644 plugins/storage/volume/nexenta/pom.xml delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java delete mode 100644 plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java delete mode 100644 plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties delete mode 100644 plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml delete mode 100644 plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java delete mode 100644 plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java delete mode 100644 plugins/storage/volume/solidfire/pom.xml delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFireSharedPrimaryDataStoreDriver.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFirePrimaryDataStoreProvider.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedHostListener.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedPrimaryDataStoreProvider.java delete mode 100644 plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java delete mode 100644 plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/module.properties delete mode 100644 plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/spring-storage-volume-solidfire-context.xml delete mode 100644 plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/AopTestAdvice.java delete mode 100644 plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/ChildTestConfiguration.java delete mode 100644 plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/TestConfiguration.java delete mode 100644 plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/VolumeTest.java delete mode 100644 plugins/storage/volume/solidfire/src/test/resource/storageContext.xml delete mode 100644 plugins/user-authenticators/md5/pom.xml delete mode 100644 plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java delete mode 100644 plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/module.properties delete mode 100644 plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml delete mode 100644 plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java delete mode 100644 plugins/user-authenticators/plain-text/pom.xml delete mode 100644 plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java delete mode 100644 plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/module.properties delete mode 100644 plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml delete mode 100644 quickcloud/pom.xml delete mode 100644 quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml delete mode 100644 test/integration/component/test_asa1000v_fw.py delete mode 100644 test/integration/component/test_bigswitch_bcf.py delete mode 100644 test/integration/component/test_brocade_vcs.py delete mode 100644 test/integration/plugins/datera/TestVolumes.py delete mode 100644 test/integration/plugins/solidfire/TestAddRemoveHosts.py delete mode 100644 test/integration/plugins/solidfire/TestCapacityManagement.py delete mode 100644 test/integration/plugins/solidfire/TestManagedClusteredFilesystems.py delete mode 100644 test/integration/plugins/solidfire/TestManagedSystemVMs.py delete mode 100644 test/integration/plugins/solidfire/TestOnlineStorageMigration.py delete mode 100644 test/integration/plugins/solidfire/TestSnapshots.py delete mode 100644 test/integration/plugins/solidfire/TestUploadDownload.py delete mode 100644 test/integration/plugins/solidfire/TestVMMigrationWithStorage.py delete mode 100644 test/integration/plugins/solidfire/TestVMSnapshots.py delete mode 100644 test/integration/plugins/solidfire/TestVolumes.py delete mode 100644 test/integration/plugins/solidfire/util/sf_util.py delete mode 100644 test/integration/plugins/test_nicira_controller.py delete mode 100644 tools/ngui/README.md delete mode 100644 tools/ngui/api.py delete mode 100644 tools/ngui/app.py delete mode 100644 tools/ngui/config.py delete mode 100644 tools/ngui/precache.py delete mode 100644 tools/ngui/requester.py delete mode 100644 tools/ngui/static/bootstrap/css/bootstrap-responsive.css delete mode 100644 tools/ngui/static/bootstrap/css/bootstrap-responsive.min.css delete mode 100644 tools/ngui/static/bootstrap/css/bootstrap.css delete mode 100644 tools/ngui/static/bootstrap/css/bootstrap.min.css delete mode 100644 tools/ngui/static/bootstrap/img/glyphicons-halflings-white.png delete mode 100644 tools/ngui/static/bootstrap/img/glyphicons-halflings.png delete mode 100644 tools/ngui/static/bootstrap/js/bootstrap.js delete mode 100644 tools/ngui/static/bootstrap/js/bootstrap.min.js delete mode 100644 tools/ngui/static/css/app.css delete mode 100644 tools/ngui/static/images/ajax-inverse.gif delete mode 100644 tools/ngui/static/images/ajax-loader.gif delete mode 100644 tools/ngui/static/js/app/accounts/accounts.js delete mode 100644 tools/ngui/static/js/app/accounts/accounts.tpl.html delete mode 100644 tools/ngui/static/js/app/app.js delete mode 100644 tools/ngui/static/js/app/dashboard/dashboard.js delete mode 100644 tools/ngui/static/js/app/domains/domains.js delete mode 100644 tools/ngui/static/js/app/events/events.js delete mode 100644 tools/ngui/static/js/app/globalsettings/globalsettings.js delete mode 100644 tools/ngui/static/js/app/globalsettings/globalsettings.tpl.html delete mode 100644 tools/ngui/static/js/app/infrastructure/infrastructure.js delete mode 100644 tools/ngui/static/js/app/instances/instance-details.tpl.html delete mode 100644 tools/ngui/static/js/app/instances/instances.js delete mode 100644 tools/ngui/static/js/app/instances/instances.tpl.html delete mode 100644 tools/ngui/static/js/app/networks/networks.js delete mode 100644 tools/ngui/static/js/app/projects/projects.js delete mode 100644 tools/ngui/static/js/app/serviceofferings/serviceofferings.js delete mode 100644 tools/ngui/static/js/app/storage/storage.js delete mode 100644 tools/ngui/static/js/app/storage/storage.tpl.html delete mode 100644 tools/ngui/static/js/app/storage/upload-volume.tpl.html delete mode 100644 tools/ngui/static/js/app/templates/templates.js delete mode 100644 tools/ngui/static/js/common/dictionary.js delete mode 100644 tools/ngui/static/js/common/directives/confirm.js delete mode 100644 tools/ngui/static/js/common/directives/edit-in-place.js delete mode 100644 tools/ngui/static/js/common/directives/edit-in-place.tpl.html delete mode 100644 tools/ngui/static/js/common/directives/label.js delete mode 100644 tools/ngui/static/js/common/directives/modal-form.js delete mode 100644 tools/ngui/static/js/common/directives/modal-form.tpl.html delete mode 100644 tools/ngui/static/js/common/resources/accounts.js delete mode 100644 tools/ngui/static/js/common/resources/configurations.js delete mode 100644 tools/ngui/static/js/common/resources/diskofferings.js delete mode 100644 tools/ngui/static/js/common/resources/domains.js delete mode 100644 tools/ngui/static/js/common/resources/events.js delete mode 100644 tools/ngui/static/js/common/resources/networks.js delete mode 100644 tools/ngui/static/js/common/resources/projects.js delete mode 100644 tools/ngui/static/js/common/resources/serviceofferings.js delete mode 100644 tools/ngui/static/js/common/resources/snapshots.js delete mode 100644 tools/ngui/static/js/common/resources/templates.js delete mode 100644 tools/ngui/static/js/common/resources/users.js delete mode 100644 tools/ngui/static/js/common/resources/virtualmachines.js delete mode 100644 tools/ngui/static/js/common/resources/volumes.js delete mode 100644 tools/ngui/static/js/common/resources/zones.js delete mode 100644 tools/ngui/static/js/common/services/breadcrumbs.js delete mode 100644 tools/ngui/static/js/common/services/helperfunctions.js delete mode 100644 tools/ngui/static/js/common/services/notifications.js delete mode 100644 tools/ngui/static/js/common/services/requester.js delete mode 100644 tools/ngui/static/js/lib/angular-ui.min.js delete mode 100644 tools/ngui/static/js/lib/angular.js delete mode 100644 tools/ngui/static/js/lib/jquery-1.7.2.js delete mode 100644 tools/ngui/templates/index.html delete mode 100755 utils/src/main/java/com/cloud/utils/nicira/nvp/plugin/NiciraNvpApiVersion.java diff --git a/api/src/main/java/com/cloud/hypervisor/Hypervisor.java b/api/src/main/java/com/cloud/hypervisor/Hypervisor.java index 1f8741d3b7b2..f0678a631d77 100644 --- a/api/src/main/java/com/cloud/hypervisor/Hypervisor.java +++ b/api/src/main/java/com/cloud/hypervisor/Hypervisor.java @@ -52,7 +52,9 @@ public enum Functionality { public static final HypervisorType Parralels = new HypervisorType("Parralels"); public static final HypervisorType BareMetal = new HypervisorType("BareMetal"); public static final HypervisorType Simulator = new HypervisorType("Simulator", null, EnumSet.of(RootDiskSizeOverride, VmStorageMigration)); + /** @deprecated OVM (Oracle VM 2) hypervisor plugin has been removed. Retained for DB deserialization compatibility. */ public static final HypervisorType Ovm = new HypervisorType("Ovm", ImageFormat.RAW); + /** @deprecated OVM3 (Oracle VM 3) hypervisor plugin has been removed. Retained for DB deserialization compatibility. */ public static final HypervisorType Ovm3 = new HypervisorType("Ovm3", ImageFormat.RAW); public static final HypervisorType LXC = new HypervisorType("LXC"); public static final HypervisorType Custom = new HypervisorType("Custom", null, EnumSet.of(RootDiskSizeOverride)); diff --git a/api/src/main/java/com/cloud/network/Network.java b/api/src/main/java/com/cloud/network/Network.java index e41eb880ffd5..de3bb70adc23 100644 --- a/api/src/main/java/com/cloud/network/Network.java +++ b/api/src/main/java/com/cloud/network/Network.java @@ -176,8 +176,6 @@ public static class Provider { private static List supportedProviders = new ArrayList(); public static final Provider VirtualRouter = new Provider("VirtualRouter", false, false); - public static final Provider JuniperContrailRouter = new Provider("JuniperContrailRouter", false); - public static final Provider JuniperContrailVpcRouter = new Provider("JuniperContrailVpcRouter", false); public static final Provider JuniperSRX = new Provider("JuniperSRX", true); public static final Provider PaloAlto = new Provider("PaloAlto", true); public static final Provider F5BigIp = new Provider("F5BigIp", true); @@ -188,21 +186,10 @@ public static class Provider { public static final Provider SecurityGroupProvider = new Provider("SecurityGroupProvider", false); public static final Provider VPCVirtualRouter = new Provider("VpcVirtualRouter", false); public static final Provider None = new Provider("None", false); - // NiciraNvp is not an "External" provider, otherwise we get in trouble with NetworkServiceImpl.providersConfiguredForExternalNetworking - public static final Provider NiciraNvp = new Provider("NiciraNvp", false); public static final Provider InternalLbVm = new Provider("InternalLbVm", false); - public static final Provider CiscoVnmc = new Provider("CiscoVnmc", true); - // add new Ovs provider public static final Provider Ovs = new Provider("Ovs", false); public static final Provider Opendaylight = new Provider("Opendaylight", false); - public static final Provider BrocadeVcs = new Provider("BrocadeVcs", false); - // add GloboDns provider - public static final Provider GloboDns = new Provider("GloboDns", true); - // add Big Switch Bcf Provider - public static final Provider BigSwitchBcf = new Provider("BigSwitchBcf", false); - //Add ConfigDrive provider public static final Provider ConfigDrive = new Provider("ConfigDrive", false); - //Add Tungsten Fabric provider public static final Provider Tungsten = new Provider("Tungsten", false); public static final Provider Nsx = new Provider("Nsx", false); diff --git a/api/src/main/java/com/cloud/network/NetworkService.java b/api/src/main/java/com/cloud/network/NetworkService.java index 53692f932a4e..13fafcf45212 100644 --- a/api/src/main/java/com/cloud/network/NetworkService.java +++ b/api/src/main/java/com/cloud/network/NetworkService.java @@ -182,11 +182,11 @@ Pair, Integer> listNetworkService long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType); PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, - String simulatorLabel, String vlan, String hypervLabel, String ovm3label); + String simulatorLabel, String vlan, String hypervLabel); PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id); - PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel, String hypervLabel, String ovm3label); + PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel, String hypervLabel); boolean deletePhysicalNetworkTrafficType(Long id); diff --git a/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java b/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java index d3804cd29daf..8e765d78ac12 100644 --- a/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java +++ b/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java @@ -40,7 +40,5 @@ public interface PhysicalNetworkTrafficType extends InternalIdentity, Identity { String getHypervNetworkLabel(); - String getOvm3NetworkLabel(); - String getVlan(); } diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java index 4d4ead277e5d..5598378054aa 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java @@ -819,7 +819,6 @@ public class ApiConstants { public static final String KVM_NETWORK_LABEL = "kvmnetworklabel"; public static final String VMWARE_NETWORK_LABEL = "vmwarenetworklabel"; public static final String HYPERV_NETWORK_LABEL = "hypervnetworklabel"; - public static final String OVM3_NETWORK_LABEL = "ovm3networklabel"; public static final String NETWORK_SERVICE_PROVIDER_ID = "nspid"; public static final String SERVICE_LIST = "servicelist"; public static final String CAN_ENABLE_INDIVIDUAL_SERVICE = "canenableindividualservice"; @@ -1176,9 +1175,6 @@ public class ApiConstants { public static final String METADATA = "metadata"; public static final String PHYSICAL_SIZE = "physicalsize"; public static final String CHAIN_SIZE = "chainsize"; - public static final String OVM3_POOL = "ovm3pool"; - public static final String OVM3_CLUSTER = "ovm3cluster"; - public static final String OVM3_VIP = "ovm3vip"; public static final String CLEAN_UP_DETAILS = "cleanupdetails"; public static final String CLEAN_UP_EXTERNAL_DETAILS = "cleanupexternaldetails"; public static final String CLEAN_UP_EXTRA_CONFIG = "cleanupextraconfig"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java index d8fa2123d228..abc6613f3fb4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java @@ -65,7 +65,7 @@ public class AddClusterCmd extends BaseCmd { @Parameter(name = ApiConstants.HYPERVISOR, type = CommandType.STRING, required = true, - description = "Hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator,Ovm3,External") + description = "Hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator,External") private String hypervisor; @Parameter(name = ApiConstants.ARCH, type = CommandType.STRING, @@ -112,13 +112,6 @@ public class AddClusterCmd extends BaseCmd { description = "Name of virtual switch used for public traffic in the cluster. This would override zone wide traffic label setting.") private String vSwitchNamePublicTraffic; - @Parameter(name = ApiConstants.OVM3_POOL, type = CommandType.STRING, required = false, description = "Ovm3 native pooling enabled for cluster") - private String ovm3pool; - @Parameter(name = ApiConstants.OVM3_CLUSTER, type = CommandType.STRING, required = false, description = "Ovm3 native OCFS2 clustering enabled for cluster") - private String ovm3cluster; - @Parameter(name = ApiConstants.OVM3_VIP, type = CommandType.STRING, required = false, description = "Ovm3 vip to use for pool (and cluster)") - private String ovm3vip; - @Parameter(name = ApiConstants.STORAGE_ACCESS_GROUPS, type = CommandType.LIST, collectionType = CommandType.STRING, description = "comma separated list of storage access groups for the hosts in the cluster", @@ -138,16 +131,6 @@ public class AddClusterCmd extends BaseCmd { since = "4.21.0") protected Map externalDetails; - public String getOvm3Pool() { - return ovm3pool; - } - public String getOvm3Cluster() { - return ovm3cluster; - } - public String getOvm3Vip() { - return ovm3vip; - } - public String getVSwitchTypeGuestTraffic() { return vSwitchTypeGuestTraffic; } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java index 50abd953e63f..8a4752a297d0 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java @@ -72,11 +72,6 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { description = "The network name label of the physical device dedicated to this traffic on a Hyperv host") private String hypervLabel; - @Parameter(name = ApiConstants.OVM3_NETWORK_LABEL, - type = CommandType.STRING, - description = "The network name of the physical device dedicated to this traffic on an OVM3 host") - private String ovm3Label; - @Parameter(name = ApiConstants.VLAN, type = CommandType.STRING, description = "The VLAN id to be used for Management traffic by VMware host") private String vlan; @@ -117,10 +112,6 @@ public String getSimulatorLabel() { return null; } - public String getOvm3Label() { - return ovm3Label; - } - public void setVlan(String vlan) { this.vlan = vlan; } @@ -163,7 +154,7 @@ public void execute() { public void create() throws ResourceAllocationException { PhysicalNetworkTrafficType result = _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getIsolationMethod(), getXenLabel(), getKvmLabel(), getVmwareLabel(), - getSimulatorLabel(), getVlan(), getHypervLabel(), getOvm3Label()); + getSimulatorLabel(), getVlan(), getHypervLabel()); if (result != null) { setEntityId(result.getId()); setEntityUuid(result.getUuid()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java index 29b06a3b5259..9ed691699b8d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java @@ -62,11 +62,6 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { description = "The network name label of the physical device dedicated to this traffic on a Hyperv host") private String hypervLabel; - @Parameter(name = ApiConstants.OVM3_NETWORK_LABEL, - type = CommandType.STRING, - description = "The network name of the physical device dedicated to this traffic on an OVM3 host") - private String ovm3Label; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -91,10 +86,6 @@ public String getHypervLabel() { return hypervLabel; } - public String getOvm3Label() { - return ovm3Label; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -106,7 +97,7 @@ public long getEntityOwnerId() { @Override public void execute() { - PhysicalNetworkTrafficType result = _networkService.updatePhysicalNetworkTrafficType(getId(), getXenLabel(), getKvmLabel(), getVmwareLabel(), getHypervLabel(), getOvm3Label()); + PhysicalNetworkTrafficType result = _networkService.updatePhysicalNetworkTrafficType(getId(), getXenLabel(), getKvmLabel(), getVmwareLabel(), getHypervLabel()); if (result != null) { TrafficTypeResponse response = _responseGenerator.createTrafficTypeResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java index e73cd3876a92..1582d731d08f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ClusterResponse.java @@ -85,10 +85,6 @@ public class ClusterResponse extends BaseResponseWithAnnotations { @Param(description = "The memory overcommit ratio of the cluster") private String memoryovercommitratio; - @SerializedName("ovm3vip") - @Param(description = "Ovm3 VIP to use for pooling and/or clustering") - private String ovm3vip; - @SerializedName(ApiConstants.RESOURCE_DETAILS) @Param(description = "Meta data associated with the zone (key/value pairs)") private Map resourceDetails; @@ -229,14 +225,6 @@ public String getMemoryOvercommitRatio() { return memoryovercommitratio; } - public void setOvm3Vip(String ovm3vip) { - this.ovm3vip = ovm3vip; - } - - public String getOvm3Vip() { - return ovm3vip; - } - public void setResourceDetails(Map details) { if (details == null) { return; @@ -270,14 +258,6 @@ public void setMemoryovercommitratio(String memoryovercommitratio) { this.memoryovercommitratio = memoryovercommitratio; } - public String getOvm3vip() { - return ovm3vip; - } - - public void setOvm3vip(String ovm3vip) { - this.ovm3vip = ovm3vip; - } - public void setCapacities(List capacities) { this.capacities = capacities; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java index 2b8af97f160e..c3230625d2d7 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java @@ -64,10 +64,6 @@ public class TrafficTypeResponse extends BaseResponse { @Param(description = "isolation methods for the physical network traffic") private String isolationMethods; - @SerializedName(ApiConstants.OVM3_NETWORK_LABEL) - @Param(description = "The Network name of the physical device dedicated to this traffic on an OVM3 host") - private String ovm3NetworkLabel; - @Override public String getObjectId() { return this.id; @@ -129,14 +125,6 @@ public String getVmwareLabel() { return vmwareNetworkLabel; } - public String getOvm3Label() { - return ovm3NetworkLabel; - } - - public void setOvm3Label(String ovm3Label) { - this.ovm3NetworkLabel = ovm3Label; - } - public String getIsolationMethods() { return isolationMethods; } diff --git a/api/src/main/java/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java b/api/src/main/java/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java index b34935611025..84bb97470e12 100644 --- a/api/src/main/java/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java +++ b/api/src/main/java/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java @@ -43,11 +43,7 @@ public static class NetworkDevice { public static final NetworkDevice F5BigIpLoadBalancer = new NetworkDevice("F5BigIpLoadBalancer", Network.Provider.F5BigIp.getName()); public static final NetworkDevice JuniperSRXFirewall = new NetworkDevice("JuniperSRXFirewall", Network.Provider.JuniperSRX.getName()); public static final NetworkDevice PaloAltoFirewall = new NetworkDevice("PaloAltoFirewall", Network.Provider.PaloAlto.getName()); - public static final NetworkDevice NiciraNvp = new NetworkDevice("NiciraNvp", Network.Provider.NiciraNvp.getName()); - public static final NetworkDevice CiscoVnmc = new NetworkDevice("CiscoVnmc", Network.Provider.CiscoVnmc.getName()); public static final NetworkDevice OpenDaylightController = new NetworkDevice("OpenDaylightController", Network.Provider.Opendaylight.getName()); - public static final NetworkDevice BrocadeVcs = new NetworkDevice("BrocadeVcs", Network.Provider.BrocadeVcs.getName()); - public static final NetworkDevice GloboDns = new NetworkDevice("GloboDns", Network.Provider.GloboDns.getName()); public NetworkDevice(String deviceName, String ntwkServiceprovider) { _name = deviceName; diff --git a/client/pom.xml b/client/pom.xml index 55123de0f98e..7e67e5a87c37 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -126,21 +126,6 @@ cloud-plugin-storage-volume-ontap ${project.version} - - org.apache.cloudstack - cloud-plugin-storage-volume-solidfire - ${project.version} - - - org.apache.cloudstack - cloud-plugin-storage-volume-cloudbyte - ${project.version} - - - org.apache.cloudstack - cloud-plugin-storage-volume-datera - ${project.version} - org.apache.cloudstack cloud-plugin-storage-volume-scaleio @@ -211,11 +196,6 @@ cloud-plugin-user-authenticator-ldap ${project.version} - - org.apache.cloudstack - cloud-plugin-user-authenticator-md5 - ${project.version} - org.apache.cloudstack cloud-plugin-user-authenticator-oauth2 @@ -226,11 +206,6 @@ cloud-plugin-user-authenticator-pbkdf2 ${project.version} - - org.apache.cloudstack - cloud-plugin-user-authenticator-plaintext - ${project.version} - org.apache.cloudstack cloud-plugin-user-authenticator-saml2 @@ -256,11 +231,6 @@ cloud-plugin-metrics ${project.version} - - org.apache.cloudstack - cloud-plugin-network-nvp - ${project.version} - org.apache.cloudstack cloud-plugin-network-palo-alto @@ -281,16 +251,6 @@ cloud-plugin-network-elb ${project.version} - - org.apache.cloudstack - cloud-plugin-network-bigswitch - ${project.version} - - - org.apache.cloudstack - cloud-plugin-network-ssp - ${project.version} - org.apache.cloudstack cloud-plugin-network-internallb @@ -321,11 +281,6 @@ cloud-plugin-hypervisor-baremetal ${project.version} - - org.apache.cloudstack - cloud-plugin-hypervisor-ucs - ${project.version} - org.apache.cloudstack cloud-plugin-hypervisor-kvm @@ -562,16 +517,6 @@ cloud-plugin-non-strict-host-affinity ${project.version} - - org.apache.cloudstack - cloud-plugin-api-solidfire-intg-test - ${project.version} - - - org.apache.cloudstack - cloud-plugin-network-globodns - ${project.version} - org.apache.cloudstack cloud-plugin-cluster-drs-balanced @@ -868,11 +813,6 @@ match="classpath:componentContext.xml" replace="classpath:nonossComponentContext.xml" byline="true" /> - - - - - @@ -1093,11 +1033,6 @@ cloud-vmware-base ${project.version} - - org.apache.cloudstack - cloud-plugin-network-cisco-vnmc - ${project.version} - org.apache.cloudstack cloud-plugin-network-nsx @@ -1118,11 +1053,6 @@ cloud-plugin-api-vmware-sioc ${project.version} - - org.apache.cloudstack - cloud-plugin-network-contrail - ${project.version} - org.apache.cloudstack cloud-plugin-backup-veeam diff --git a/cloud-cli/bindir/cloud-tool b/cloud-cli/bindir/cloud-tool deleted file mode 100755 index 0f0815307a13..000000000000 --- a/cloud-cli/bindir/cloud-tool +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python3 - -# 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. - -import sys -import os - -sys.path.append(os.path.dirname(os.path.dirname(__file__))) - -import cloudtool - -ret = cloudtool.main() -if ret: - sys.exit(ret) diff --git a/cloud-cli/cloudapis/__init__.py b/cloud-cli/cloudapis/__init__.py deleted file mode 100644 index dd84d7b5c9bb..000000000000 --- a/cloud-cli/cloudapis/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# 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. - - - -''' -Created on Aug 2, 2010 - -''' - -import os,pkgutil - -def get_all_apis(): - apis = [] - for x in pkgutil.walk_packages([os.path.dirname(__file__)]): - loader = x[0].find_module(x[1]) - try: module = loader.load_module("cloudapis." + x[1]) - except ImportError: continue - apis.append(module) - return apis - -def lookup_api(api_name): - api = None - matchingapi = [ x for x in get_all_apis() if api_name.replace("-","_") == x.__name__.split(".")[-1] ] - if not matchingapi: api = None - else: api = matchingapi[0] - if api: api = getattr(api,"implementor") - return api diff --git a/cloud-cli/cloudapis/cloud.py b/cloud-cli/cloudapis/cloud.py deleted file mode 100644 index 60175b9401d6..000000000000 --- a/cloud-cli/cloudapis/cloud.py +++ /dev/null @@ -1,196 +0,0 @@ -# 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. - - - -'''Implements the CloudStack API''' - - -from cloudtool.utils import describe -import urllib.request, urllib.parse, urllib.error -import urllib.request, urllib.error, urllib.parse -import os -import xml.dom.minidom -import re -import base64 -import hmac -import hashlib -import http.client - -class CloudAPI: - - @describe("server", "Management Server host name or address") - @describe("apikey", "Management Server apiKey") - @describe("securitykey", "Management Server securityKey") - @describe("responseformat", "Response format: xml or json") - @describe("stripxml", "True if xml tags have to be stripped in the output, false otherwise") - def __init__(self, - server="127.0.0.1:8096", - responseformat="xml", - stripxml="true", - apiKey=None, - securityKey=None - ): - self.__dict__.update(locals()) - - def _make_request_with_keys(self,command,requests={}): - requests["command"] = command - requests["apiKey"] = self.apiKey - requests["response"] = "xml" - requests = list(zip(list(requests.keys()), list(requests.values()))) - requests.sort(key=lambda x: str.lower(x[0])) - - requestUrl = "&".join(["=".join([request[0], urllib.parse.quote_plus(str(request[1]))]) for request in requests]) - hashStr = "&".join(["=".join([str.lower(request[0]), urllib.parse.quote_plus(str.lower(str(request[1])))]) for request in requests]) - - sig = urllib.parse.quote_plus(base64.encodestring(hmac.new(self.securityKey, hashStr, hashlib.sha1).digest()).strip()) - - requestUrl += "&signature=%s"%sig - return requestUrl - - - def _make_request_with_auth(self, command, requests): - self.connection = http.client.HTTPConnection("%s"%(self.server)) - requests["command"] = command - requests["apiKey"] = self.apiKey - requests["response"] = self.responseformat - requests = list(zip(list(requests.keys()), list(requests.values()))) - requests.sort(key=lambda x: str.lower(x[0])) - - requestUrl = "&".join(["=".join([request[0], urllib.parse.quote(str(request[1],""))]) for request in requests]) - hashStr = "&".join(["=".join([str.lower(request[0]), urllib.parse.quote(str.lower(str(request[1])),"")]) for request in requests]) - - sig = urllib.parse.quote_plus(base64.encodestring(hmac.new(self.securityKey, str.lower(hashStr), hashlib.sha1).digest()).strip()) - - requestUrl += "&signature=%s"%sig - - self.connection.request("GET", "/client/api?%s"%requestUrl) - return self.connection.getresponse().read() - - def _make_request(self,command,parameters=None): - - '''Command is a string, parameters is a dictionary''' - if ":" in self.server: - host,port = self.server.split(":") - port = int(port) - else: - host = self.server - port = 8096 - - url = "http://" + self.server + "/client/api?" - - if not parameters: parameters = {} - if self.apiKey is not None and self.securityKey is not None: - return self._make_request_with_auth(command, parameters) - else: - parameters["command"] = command - parameters["response"] = self.responseformat - querystring = urllib.parse.urlencode(parameters) - - url += querystring - - f = urllib.request.urlopen(url) - data = f.read() - if self.stripxml == "true": - data=re.sub("<\?.*\?>", "\n", data); - data=re.sub("", "\n", data); - data=data.replace(">", "="); - data=data.replace("=<", "\n"); - data=data.replace("\n<", "\n"); - data=re.sub("\n.*cloud-stack-version=.*", "", data); - data=data.replace("\n\n\n", "\n"); - - return data - - -def load_dynamic_methods(): - '''creates smart function objects for every method in the commands.xml file''' - - def getText(nodelist): - rc = [] - for node in nodelist: - if node.nodeType == node.TEXT_NODE: rc.append(node.data) - return ''.join(rc) - - # FIXME figure out installation and packaging - xmlfile = os.path.join("/etc/cloud/cli/","commands.xml") - dom = xml.dom.minidom.parse(xmlfile) - - for cmd in dom.getElementsByTagName("command"): - name = getText(cmd.getElementsByTagName('name')[0].childNodes).strip() - assert name - - description = getText(cmd.getElementsByTagName('description')[0].childNodes).strip() - if description: - description = '"""%s"""' % description - else: description = '' - arguments = [] - options = [] - descriptions = [] - - for param in cmd.getElementsByTagName("request")[0].getElementsByTagName("arg"): - argname = getText(param.getElementsByTagName('name')[0].childNodes).strip() - assert argname - - required = getText(param.getElementsByTagName('required')[0].childNodes).strip() - if required == 'true': required = True - elif required == 'false': required = False - else: raise AssertionError("Not reached") - if required: arguments.append(argname) - options.append(argname) - - #import ipdb; ipdb.set_trace() - requestDescription = param.getElementsByTagName('description') - if requestDescription: - descriptionParam = getText(requestDescription[0].childNodes) - else: - descriptionParam = '' - if descriptionParam: descriptions.append( (argname,descriptionParam) ) - - funcparams = ["self"] + [ "%s=None"%o for o in options ] - funcparams = ", ".join(funcparams) - - code = """ - def %s(%s): - %s - parms = dict(locals()) - del parms["self"] - for arg in %r: - if locals()[arg] is None: - raise TypeError, "%%s is a required option"%%arg - for k,v in parms.items(): - if v is None: del parms[k] - output = self._make_request("%s",parms) - return output - """%(name,funcparams,description,arguments,name) - - namespace = {} - exec(code.strip(), namespace) - - func = namespace[name] - for argname,description in descriptions: - func = describe(argname,description)(func) - - yield (name,func) - - -for name,meth in load_dynamic_methods(): - setattr(CloudAPI, name, meth) - -implementor = CloudAPI - -del name,meth,describe,load_dynamic_methods diff --git a/cloud-cli/cloudtool/__init__.py b/cloud-cli/cloudtool/__init__.py deleted file mode 100644 index c5785dcbd827..000000000000 --- a/cloud-cli/cloudtool/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# 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. - - - -''' -Created on Aug 2, 2010 - -''' - -import sys -import cloudapis as apis -import cloudtool.utils as utils - - -def main(argv=None): - - #import ipdb; ipdb.set_trace() - if argv == None: - argv = sys.argv - - prelim_args = [ x for x in argv[0:] if not x.startswith('-') ] - parser = utils.get_parser() - - api = __import__("cloudapis") - apis = getattr(api, "implementor") - if len(prelim_args) == 1: - commandlist = utils.get_command_list(apis) - parser.error("you need to specify a command name as the first argument\n\nCommands supported by the %s API:\n"%prelim_args[0] + "\n".join(commandlist)) - - command = utils.lookup_command_in_api(apis,prelim_args[1]) - if not command: parser.error("command %r not supported by the %s API"%(prelim_args[1],prelim_args[0])) - - argv = argv[1:] - if len(argv) == 1: - argv.append("--help") - - parser = utils.get_parser(apis.__init__,command) - opts,args,api_optionsdict,cmd_optionsdict = parser.parse_args(argv) - - - try: - api = apis(**api_optionsdict) - except utils.OptParseError as e: - parser.error(str(e)) - - command = utils.lookup_command_in_api(api,args[0]) - - # we now discard the first two arguments as those necessarily are the api and command names - args = args[2:] - - try: return command(*args,**cmd_optionsdict) - except TypeError as e: parser.error(str(e)) - - -if __name__ == '__main__': - main(argv) diff --git a/cloud-cli/cloudtool/utils.py b/cloud-cli/cloudtool/utils.py deleted file mode 100644 index 0fc21e19924e..000000000000 --- a/cloud-cli/cloudtool/utils.py +++ /dev/null @@ -1,169 +0,0 @@ -# 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. - - - -''' -Created on Aug 2, 2010 - -''' - - -import sys -import os -import inspect -from optparse import OptionParser, OptParseError, BadOptionError, OptionError, OptionConflictError, OptionValueError -import cloudapis as apis - - -def describe(name,desc): - def inner(decoratee): - if not hasattr(decoratee,"descriptions"): decoratee.descriptions = {} - decoratee.descriptions[name] = desc - return decoratee - return inner - - -def error(msg): - sys.stderr.write(msg) - sys.stderr.write("\n") - - -class MyOptionParser(OptionParser): - def error(self, msg): - error("%s: %s\n" % (self.get_prog_name(),msg)) - self.print_usage(sys.stderr) - self.exit(os.EX_USAGE) - - def parse_args(self,*args,**kwargs): - options,arguments = OptionParser.parse_args(self,*args,**kwargs) - - def prune_options(options,alist): - """Given 'options' -- a list of arguments to OptionParser.add_option, - and a set of optparse Values, return a dictionary of only those values - that apply exclusively to 'options'""" - return dict( [ (k,getattr(options,k)) for k in dir(options) if k in alist ] ) - - api_options = prune_options(options,self.api_dests) - cmd_options = prune_options(options,self.cmd_dests) - - return options,arguments,api_options,cmd_options - - -def get_parser(api_callable=None,cmd_callable=None): # this should probably be the __init__ method of myoptionparser - - def getdefaulttag(default): - if default is not None: return " [Default: %default]" - return '' - - def get_arguments_and_options(callable): - """Infers and returns arguments and options based on a callable's signature. - Cooperates with decorator @describe""" - try: - funcargs = inspect.getargspec(callable).args - defaults = inspect.getargspec(callable).defaults - except: - funcargs = inspect.getargspec(callable)[0] - defaults = inspect.getargspec(callable)[3] - if not defaults: defaults = [] - args = funcargs[1:len(funcargs)-len(defaults)] # this assumes self, so assumes methods - opts = funcargs[len(funcargs)-len(defaults):] - try: descriptions = callable.descriptions - except AttributeError: descriptions = {} - arguments = [ (argname, descriptions.get(argname,'') ) for argname in args ] - options = [ [ - ("--%s"%argname.replace("_","-"),), - { - "dest":argname, - "help":descriptions.get(argname,'') + getdefaulttag(default), - "default":default, - } - ] for argname,default in zip(opts,defaults) ] - return arguments,options - - basic_usage = "usage: %prog [options...] " - - api_name = "" - cmd_name = "" - description = "%prog is a command-line tool to access several cloud APIs." - arguments = '' - argexp = "" - - if api_callable: - api_name = api_callable.__module__.split(".")[-1].replace("_","-") - api_arguments,api_options = get_arguments_and_options(api_callable) - assert len(api_arguments) is 0 # no mandatory arguments for class initializers - - if cmd_callable: - cmd_name = cmd_callable.__name__.replace("_","-") - cmd_arguments,cmd_options = get_arguments_and_options(cmd_callable) - if cmd_arguments: - arguments = " " + " ".join( [ s[0].upper() for s in cmd_arguments ] ) - argexp = "\n\nArguments:\n" + "\n".join ( " %s\n %s"%(s.upper(),u) for s,u in cmd_arguments ) - description = cmd_callable.__doc__ - - api_command = "%s %s"%(api_name,cmd_name) - - if description: description = "\n\n" + description - else: description = '' - - usage = basic_usage + api_command + arguments + description + argexp - - parser = MyOptionParser(usage=usage, add_help_option=False) - - parser.add_option('--help', action="help") - - group = parser.add_option_group("General options") - group.add_option('-v', '--verbose', dest="verbose", help="Print extra output") - - parser.api_dests = [] - if api_callable and api_options: - group = parser.add_option_group("Options for the %s API"%api_name) - for a in api_options: - group.add_option(a[0][0],**a[1]) - parser.api_dests.append(a[1]["dest"]) - - parser.cmd_dests = [] - if cmd_callable and cmd_options: - group = parser.add_option_group("Options for the %s command"%cmd_name) - for a in cmd_options: - group.add_option(a[0][0],**a[1]) - parser.cmd_dests.append(a[1]["dest"]) - - return parser - -def lookup_command_in_api(api,command_name): - command = getattr(api,command_name.replace("-","_"),None) - return command - -def get_api_list(api): - apilist = [] - for cmd_name in dir(api): - cmd = getattr(api,cmd_name) - if callable(cmd) and not cmd_name.startswith("_"): - apilist.append(cmd_name) - return apilist - -def get_command_list(api): - cmds = [] - for cmd_name in dir(api): - cmd = getattr(api,cmd_name) - if callable(cmd) and not cmd_name.startswith("_"): - if cmd.__doc__:docstring = cmd.__doc__ - else:docstring = '' - cmds.append( " %s" % (cmd_name.replace('_','-')) ) - return cmds diff --git a/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml b/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml index 01c568d78916..0d36d1c9fa97 100644 --- a/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml +++ b/core/src/main/resources/META-INF/cloudstack/core/spring-core-registry-core-context.xml @@ -75,7 +75,7 @@ class="org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry"> + value="SimpleInvestigator,XenServerInvestigator,KVMInvestigator,HypervInvestigator,VMwareInvestigator,PingInvestigator,ManagementIPSysVMInvestigator" /> diff --git a/docs/AUDIT.md b/docs/AUDIT.md new file mode 100644 index 000000000000..ccf39c3ffcc5 --- /dev/null +++ b/docs/AUDIT.md @@ -0,0 +1,315 @@ +# Apache CloudStack Fork — Codebase Audit Report + +**Date:** 2026-05-15 +**Source:** Apache CloudStack 4.23.0.0-SNAPSHOT (main branch) +**Purpose:** Full codebase assessment to guide modernization of the forked project + +--- + +## Executive Summary + +CloudStack is a **2.15M-line**, **161-module** Java/Python/Vue.js codebase with 15+ years of history. It has strong test coverage (0.92:1 Java test ratio, 336K lines of Python integration tests) and a well-modularized plugin architecture (98 plugin modules). However, it carries significant technical debt: + +- **~14 dead plugins** (~70K+ lines) integrating with discontinued products +- **Critical EOL dependencies** (Spring 5.3, Jetty 9.4, Bouncy Castle 1.70, OpenSAML 2.6) +- **Java 11 target** when Java 17+ is needed for the Spring 6 migration +- **God-class service implementations** (multiple 5K-10K line files in `server/`) +- **Insecure authentication options** still present (MD5, plaintext passwords) +- **Vendored dead code** (AngularJS, jQuery 1.7 in abandoned `tools/ngui/`) + +The fork should prioritize: dead plugin removal, dependency modernization (especially the Spring 5→6 / javax→jakarta migration), and incremental refactoring of the `server/` module. + +--- + +## 1. Codebase Size & Structure + +### Lines by Language + +| Language | Files | Lines | % of Total | +|----------|-------|-------|------------| +| Java | 7,799 | 474,672 | 22.1% | +| Python | 640 | 365,452 | 17.0% | +| Vue | 387 | 150,335 | 7.0% | +| XML | 588 | 96,042 | 4.5% | +| JavaScript | 211 | 70,829 | 3.3% | +| SQL | 221 | 36,237 | 1.7% | +| Shell | 258 | 27,557 | 1.3% | +| Other (CSS, MD, YAML, Groovy, Properties, HTML) | — | ~34,500 | 1.6% | +| **Total** | — | **~2,151,000** | | + +### Module Structure + +- **161 Maven modules** (pom.xml files) +- **98 plugin modules** across 22 categories +- **Production Java:** 273K lines | **Test Java:** 253K lines (0.92:1 ratio) +- **Python integration tests:** 336K lines (Marvin framework) + +### Top-Level Directory Map + +| Directory | Size | Role | +|-----------|------|------| +| `plugins/` | 27 MB | Plugin architecture (hypervisors, networking, storage, auth, etc.) | +| `server/` | 16 MB | Management server core — largest single module (310K Java lines) | +| `test/` | 14 MB | Python/Marvin integration tests | +| `engine/` | 14 MB | Orchestration, schema/DB, storage engine, userdata | +| `ui/` | 12 MB | Vue 3 + Ant Design web UI | +| `api/` | 11 MB | Public API command/response definitions | +| `tools/` | 4.6 MB | Marvin, CLI tools, appliance builder, **dead ngui prototype** | +| `framework/` | 3.2 MB | DB, Spring, clustering, jobs, events, security, quota | +| `systemvm/` | 3.1 MB | System VM (CPVM/SSVM) agent code | +| `core/` | 3.1 MB | Agent↔server message types | +| `services/` | 2.4 MB | Console proxy (VNC/RDP), secondary storage agent | +| `utils/` | 1.9 MB | Shared utilities | +| `scripts/` | 1.8 MB | Host-level shell scripts | +| `vmware-base/` | 924 KB | VMware vSphere SDK wrappers | +| `setup/` | 556 KB | DB schema creation & upgrade scripts | +| `usage/` | 388 KB | Usage metering server | +| `agent/` | 344 KB | Hypervisor host agent launcher | +| `extensions/` | 48 KB | Stubs only (Hyper-V, MaaS, Proxmox) | +| `cloud-cli/` | 28 KB | Legacy CLI (dead) | +| `quickcloud/` | 8 KB | Dead quick-start scripts | + +### Largest Source Files (Refactoring Targets) + +| Lines | File | Notes | +|-------|------|-------| +| 14,847 | `tools/ngui/static/js/lib/angular.js` | Vendored AngularJS — delete entirely | +| 10,068 | `server/.../UserVmManagerImpl.java` | God class — VM lifecycle | +| 9,515 | `server/.../ConfigurationManagerImpl.java` | God class — system config | +| 9,404 | `tools/ngui/static/js/lib/jquery-1.7.2.js` | Vendored jQuery — delete entirely | +| 7,823 | `plugins/hypervisors/vmware/.../VmwareResource.java` | VMware hypervisor handler | +| 6,699 | `engine/orchestration/.../VirtualMachineManagerImpl.java` | VM state machine | +| 6,689 | `plugins/hypervisors/kvm/.../LibvirtComputingResource.java` | KVM hypervisor handler | +| 6,484 | `server/.../NetworkServiceImpl.java` | Network service | +| 5,994 | `server/.../ManagementServerImpl.java` | Core management server | +| 5,878 | `server/.../ApiResponseHelper.java` | API serialization | + +--- + +## 2. Dependency Health + +### Critical — EOL / Known CVEs + +| Dependency | Current Version | Issue | Action | +|------------|----------------|-------|--------| +| **Spring Framework** | 5.3.26 | EOL (Dec 2024). No security patches. | Migrate to Spring 6.x (requires Java 17+, javax→jakarta) | +| **Jetty** | 9.4.58 | EOL. No security fixes. | Migrate to Jetty 11/12 (align with Jakarta) | +| **Bouncy Castle** | 1.70 (jdk15on) | jdk15on deprecated; CVEs between 1.70 and 1.78+ | Upgrade to 1.78+ (jdk18on) | +| **OpenSAML** | 2.6.6 | Ancient/EOL. Known vulnerabilities. | Upgrade to 4.x (major rewrite of SAML2 plugin) | +| **OWASP ESAPI** | 2.1.0.1 | Multiple CVEs | Upgrade to 2.5.x | +| **JSch** | 0.1.55 | Abandoned upstream | Replace with `com.github.mwiede:jsch` 0.2.x or Apache MINA SSHD | +| **Apache CXF** | 3.2.14 | EOL | Upgrade to 4.x | +| **commons-httpclient** | 3.1 | Deprecated since 2011 | Replace with HttpClient 5.x | +| **commons-fileupload** | 1.4 | CVE-2023-24998 (DoS) | Replace with commons-fileupload2-jakarta | +| **Kafka clients** | 2.7.0 | EOL, multiple CVEs | Upgrade to 3.7+ | + +### High — Significantly Behind + +| Dependency | Current | Latest | Notes | +|------------|---------|--------|-------| +| Jackson | 2.13.3 | 2.17+ | Security fixes missed | +| Groovy | 2.4.17 | 4.x | EOL | +| Axis2 | 1.6.4 | — | Unmaintained; used for VMware SOAP | +| Ehcache | 2.6.11 | 3.x | EOL | +| AWS SDK | v1 1.12.795 | v2 | v1 in maintenance mode | +| Guava | 31.1 | 33+ | Security/bug fixes | +| Google Tink | 1.7.0 | 1.14+ | Behind 7 major versions | +| Log4j 2 | 2.19.0 | 2.24+ | Should update | + +### Build Tooling + +| Tool | Current | Latest | Priority | +|------|---------|--------|----------| +| maven-surefire-plugin | 2.22.2 | 3.x | High (JDK compat) | +| maven-failsafe-plugin | 2.22.2 | 3.x | High | +| maven-compiler-plugin | 3.8.1 | 3.13+ | Medium | +| Checkstyle lib | 8.18 | 10.x | Medium | +| OWASP Dependency-Check | 7.4.4 | 10.x | High (DB schema) | + +### Code Quality Configuration + +- **Checkstyle:** Active on `validate` phase with custom `cloud-style.xml` +- **SpotBugs:** Disabled by default; `failOnError=false` +- **PMD:** Active with custom rules; `failOnViolation=false` +- **JaCoCo:** Only in `quality` profile; **0% threshold** (not enforced) +- **SonarCloud:** Configured for Apache org + +--- + +## 3. Subsystem Inventory + +### Hypervisor Plugins + +| Plugin | Location | Java Lines | Tests | Status | +|--------|----------|-----------|-------|--------| +| **KVM/libvirt** | `plugins/hypervisors/kvm` | 58,851 | 54 files | Active | +| **VMware vSphere** | `plugins/hypervisors/vmware` + `vmware-base/` | 44,085 | 7 files | Active | +| **XenServer/XCP-ng** | `plugins/hypervisors/xenserver` | 25,189 | 23 files | Active | +| **Simulator** | `plugins/hypervisors/simulator` | 9,840 | 0 | Active (CI) | +| **External** | `plugins/hypervisors/external` | 3,878 | 4 files | Active | +| **OVM3 (Oracle VM 3)** | `plugins/hypervisors/ovm3` | 14,945 | 23 files | Abandoned (product EOL) | +| **Baremetal** | `plugins/hypervisors/baremetal` | 8,290 | 0 | Neglected | +| **Hyper-V** | `plugins/hypervisors/hyperv` | 4,392 | 1 file | Abandoned | +| **OVM (Oracle VM 2)** | `plugins/hypervisors/ovm` | 2,733 | 0 | Dead | +| **UCS (Cisco)** | `plugins/hypervisors/ucs` | 2,171 | 0 | Dead | + +### Network Plugins + +| Plugin | Location | Java Lines | Status | +|--------|----------|-----------|--------| +| **Tungsten Fabric** | `plugins/network-elements/tungsten` | 35,620 | Active | +| **NSX** | `plugins/network-elements/nsx` | 7,953 | Active | +| **Netris** | `plugins/network-elements/netris` | 9,432 | Active | +| **OVS** | `plugins/network-elements/ovs` | 3,850 | Active | +| **Internal LB** | `plugins/network-elements/internal-loadbalancer` | 3,182 | Active | +| **VXLAN** | `plugins/network-elements/vxlan` | 447 | Active | +| **DNS Notifier** | `plugins/network-elements/dns-notifier` | 120 | Active | +| **NetScaler** | `plugins/network-elements/netscaler` | 9,237 | Neglected | +| **Palo Alto** | `plugins/network-elements/palo-alto` | 4,430 | Neglected | +| **Elastic LB** | `plugins/network-elements/elastic-loadbalancer` | 1,996 | Neglected | +| **Nicira NVP** | `plugins/network-elements/nicira-nvp` | 12,505 | Dead (replaced by NSX) | +| **Juniper Contrail** | `plugins/network-elements/juniper-contrail` | 11,076 | Dead (replaced by Tungsten) | +| **BigSwitch** | `plugins/network-elements/bigswitch` | 6,771 | Dead | +| **Cisco VNMC** | `plugins/network-elements/cisco-vnmc` | 5,838 | Dead | +| **OpenDaylight** | `plugins/network-elements/opendaylight` | 4,733 | Dead | +| **Brocade VCS** | `plugins/network-elements/brocade-vcs` | 3,924 | Dead | +| **GloboDNS** | `plugins/network-elements/globodns` | 2,144 | Dead | +| **Stratosphere SSP** | `plugins/network-elements/stratosphere-ssp` | 2,086 | Dead | + +### Storage Plugins — Volume (Primary) + +| Plugin | Java Lines | Status | +|--------|-----------|--------| +| **StorPool** | 8,558 | Active | +| **ScaleIO/PowerFlex** | 6,966 | Active | +| **NetApp ONTAP** | 6,740 | Active | +| **LINSTOR** | 5,317 | Active | +| **Primera/3PAR** | 3,862 | Neglected | +| **Adaptive** | 2,663 | Active | +| **Flash Array** | 2,270 | Active | +| **Default (NFS/Local)** | 1,430 | Active | +| **SolidFire** | 5,231 | Dead | +| **CloudByte** | 4,688 | Dead | +| **Datera** | 4,248 | Dead | +| **Nexenta** | 2,077 | Dead | + +### Storage Plugins — Image / Object / SharedFS + +All image storage (Default, S3, Swift, Sample), object storage (Cloudian, MinIO, Ceph, Simulator), and shared filesystem (StorageVM) plugins are **Active**, except Swift (Neglected). + +### Other Active Plugin Areas + +- **Authentication:** LDAP, SAML 2.0, OAuth 2.0, SHA256, PBKDF2 (all active). MD5 and plain-text are insecure and should be removed. +- **2FA:** TOTP and Static PIN (active) +- **Backup:** Networker, Veeam, NAS (all active) +- **Event Bus:** Webhook, RabbitMQ, In-Memory, Kafka (all active) +- **Integrations:** Kubernetes Service (17K lines, major feature), Cloudian, Prometheus +- **DRS:** Balanced and Condensed cluster scheduling (active, newer) +- **Quota/Billing:** Active +- **Metrics/Maintenance:** Active + +### UI Layer + +| Property | Value | +|----------|-------| +| Framework | Vue 3.2 + Ant Design Vue 3.2 | +| Location | `/ui` (387 Vue files, 102 JS files) | +| Build | Vue CLI | +| Status | Active — current and only UI | + +--- + +## 4. Dead Code — Removal Candidates + +### Immediate Removal (products/companies no longer exist) + +| Component | Path | Lines | Reason | +|-----------|------|-------|--------| +| BigSwitch BCF | `plugins/network-elements/bigswitch` | ~6,771 | Arista discontinued BCF (2020) | +| Brocade VCS | `plugins/network-elements/brocade-vcs` | ~3,924 | Broadcom killed VCS (2017) | +| Cisco VNMC | `plugins/network-elements/cisco-vnmc` | ~5,838 | ASA 1000V EOL (2017) | +| Stratosphere SSP | `plugins/network-elements/stratosphere-ssp` | ~2,086 | Company gone | +| OpenDaylight | `plugins/network-elements/opendaylight` | ~4,733 | Project stagnant | +| Juniper Contrail | `plugins/network-elements/juniper-contrail` | ~11,076 | Superseded by Tungsten plugin | +| Nicira NVP | `plugins/network-elements/nicira-nvp` | ~12,505 | Superseded by NSX plugin | +| GloboDNS | `plugins/network-elements/globodns` | ~2,144 | Single-company internal project | +| Oracle VM 2 | `plugins/hypervisors/ovm` | ~2,733 | EOL for years | +| Cisco UCS | `plugins/hypervisors/ucs` | ~2,171 | Not a real hypervisor plugin | +| CloudByte | `plugins/storage/volume/cloudbyte` | ~4,688 | Company gone | +| Datera | `plugins/storage/volume/datera` | ~4,248 | Company bankrupt (2020) | +| SolidFire | `plugins/storage/volume/solidfire` | ~5,231 | Product discontinued | +| Nexenta | `plugins/storage/volume/nexenta` | ~2,077 | Product sunset | +| SolidFire test | `plugins/api/solidfire-intg-test` | ~500 | Test for dead product | +| MD5 auth | `plugins/user-authenticators/md5` | ~168 | Cryptographically broken | +| Plain-text auth | `plugins/user-authenticators/plain-text` | ~63 | Security risk | +| ngui (dead UI) | `tools/ngui/` | ~25K+ | Abandoned Angular/jQuery UI prototype | +| cloud-cli | `/cloud-cli` | ~500 | Dead legacy CLI | +| quickcloud | `/quickcloud` | ~200 | Dead quick-start | +| **Total** | | **~96,000+** | | + +### Consider for Removal (product declining or plugin neglected) + +| Component | Path | Lines | Notes | +|-----------|------|-------|-------| +| Oracle VM 3 | `plugins/hypervisors/ovm3` | ~14,945 | Product EOL | +| Hyper-V | `plugins/hypervisors/hyperv` | ~4,392 | Product deprecated by Microsoft | +| Baremetal | `plugins/hypervisors/baremetal` | ~8,290 | No tests, unclear demand | +| Swift image store | `plugins/storage/image/swift` | ~363 | Niche | +| Extensions stubs | `/extensions/` | ~200 | Non-functional stubs | + +--- + +## 5. Recommended Modernization Roadmap + +### Phase 1: Low-Risk Cleanup (Weeks 1-4) + +1. **Remove dead plugins** — delete the 17 components listed above (~96K lines) +2. **Remove dead tooling** — `tools/ngui/`, `cloud-cli/`, `quickcloud/` +3. **Update Maven build plugins** — surefire/failsafe to 3.x, compiler to 3.13+ +4. **Update safe dependencies** — Guava, commons-io, commons-lang3, Jackson, Log4j2 +5. **Enable JaCoCo with real thresholds** — enforce minimum coverage +6. **Fix SpotBugs/PMD** — set `failOnError=true` / `failOnViolation=true` + +### Phase 2: Security & Dependency Modernization (Weeks 4-10) + +7. **Replace JSch** with maintained fork +8. **Remove commons-httpclient 3.1** — migrate callers to HttpClient 5 +9. **Upgrade Bouncy Castle** to jdk18on 1.78+ +10. **Upgrade OWASP ESAPI** to 2.5.x +11. **Replace commons-fileupload** with fileupload2-jakarta +12. **Upgrade Kafka client** to 3.7+ +13. **Upgrade OWASP Dependency-Check** to 10.x and run full scan + +### Phase 3: The Big Migration — Java 17 + Spring 6 + Jakarta (Weeks 10-20) + +14. **Upgrade Java target** from 11 to 17 +15. **Migrate javax → jakarta** namespace (affects entire codebase) +16. **Upgrade Spring** 5.3 → 6.x +17. **Upgrade Jetty** 9.4 → 11 or 12 +18. **Upgrade Apache CXF** 3.2 → 4.x +19. **Upgrade OpenSAML** 2.6 → 4.x (or evaluate dropping SAML) +20. **Upgrade Groovy** 2.4 → 4.x + +### Phase 4: Refactoring (Ongoing) + +21. **Break up god classes** — `UserVmManagerImpl` (10K), `ConfigurationManagerImpl` (9.5K), etc. +22. **Standardize API layer** — inconsistent patterns across commands +23. **Improve plugin SPI** — make plugin development easier +24. **Modernize UI** — update Vue 3 / Ant Design versions, improve DX +25. **Add observability** — structured logging, metrics, distributed tracing + +### Phase 5: New Capabilities + +26. **Container workloads** — expand CKS (Kubernetes Service) +27. **Modern networking** — OVN integration, eBPF +28. **Improved multi-tenancy** and RBAC +29. **API v2** — REST-native with OpenAPI spec +30. **Better developer experience** — faster builds, better docs, docker-compose dev env + +--- + +## Appendix: Dependency Inventory + +Total unique external dependencies: ~202 artifacts from 146 group IDs. +Dependencies managed centrally in root POM: ~90. +Full dependency tree available via `mvn dependency:tree`. diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java index 4262ee701aab..b3ab4693c107 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -4005,8 +4005,7 @@ public List listVmNics(final long vmId, final Long nicId, final L } for (final NicVO nic : result) { - if (_networkModel.isProviderForNetwork(Provider.NiciraNvp, nic.getNetworkId())) { - //For NSX Based networks, add nsxlogicalswitch, nsxlogicalswitchport to each result + if (_networkModel.isProviderForNetwork(Provider.Nsx, nic.getNetworkId())) { logger.info("Listing NSX logical switch and logical switch por for each nic"); final NetworkVO network = _networksDao.findById(nic.getNetworkId()); final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index bf3985d3ce77..942c6c49cd39 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1156,8 +1156,6 @@ private ImageFormat getSupportedImageFormatForCluster(HypervisorType hyperType) return ImageFormat.QCOW2; } else if (hyperType == HypervisorType.VMware) { return ImageFormat.OVA; - } else if (hyperType == HypervisorType.Ovm) { - return ImageFormat.RAW; } else if (hyperType == HypervisorType.Hyperv) { return ImageFormat.VHDX; } else { diff --git a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java index fdd827ffeeef..15b612abad62 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java @@ -39,9 +39,7 @@ public class PhysicalNetworkTrafficTypeDaoImpl extends GenericDaoBase xenAllFieldsSearch; final GenericSearchBuilder vmWareAllFieldsSearch; final GenericSearchBuilder simulatorAllFieldsSearch; - final GenericSearchBuilder ovmAllFieldsSearch; final GenericSearchBuilder hypervAllFieldsSearch; - final GenericSearchBuilder ovm3AllFieldsSearch; protected PhysicalNetworkTrafficTypeDaoImpl() { super(); @@ -80,17 +78,6 @@ protected PhysicalNetworkTrafficTypeDaoImpl() { simulatorAllFieldsSearch.selectFields(simulatorAllFieldsSearch.entity().getSimulatorNetworkLabel()); simulatorAllFieldsSearch.done(); - ovmAllFieldsSearch = createSearchBuilder(String.class); - ovmAllFieldsSearch.and("physicalNetworkId", ovmAllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); - ovmAllFieldsSearch.and("trafficType", ovmAllFieldsSearch.entity().getTrafficType(), Op.EQ); - ovmAllFieldsSearch.selectFields(ovmAllFieldsSearch.entity().getSimulatorNetworkLabel()); - ovmAllFieldsSearch.done(); - - ovm3AllFieldsSearch = createSearchBuilder(String.class); - ovm3AllFieldsSearch.and("physicalNetworkId", ovm3AllFieldsSearch.entity().getPhysicalNetworkId(), Op.EQ); - ovm3AllFieldsSearch.and("trafficType", ovm3AllFieldsSearch.entity().getTrafficType(), Op.EQ); - ovm3AllFieldsSearch.selectFields(ovm3AllFieldsSearch.entity().getOvm3NetworkLabel()); - ovm3AllFieldsSearch.done(); } @Override @@ -123,14 +110,10 @@ public String getNetworkTag(long physicalNetworkId, TrafficType trafficType, Hyp sc = vmWareAllFieldsSearch.create(); } else if (hType == HypervisorType.Simulator) { sc = simulatorAllFieldsSearch.create(); - } else if (hType == HypervisorType.Ovm) { - sc = ovmAllFieldsSearch.create(); } else if (hType == HypervisorType.BareMetal || hType == HypervisorType.External) { return null; } else if (hType == HypervisorType.Hyperv) { sc = hypervAllFieldsSearch.create(); - } else if (hType == HypervisorType.Ovm3) { - sc = ovm3AllFieldsSearch.create(); } else { assert (false) : "We don't handle this hypervisor type"; return null; diff --git a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java index a5eff2aeab90..4f299f115db6 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java @@ -63,6 +63,7 @@ public class PhysicalNetworkTrafficTypeVO implements PhysicalNetworkTrafficType @Column(name = "hyperv_network_label") private String hypervNetworkLabel; + /** @deprecated OVM3 hypervisor plugin has been removed. Column retained for DB compatibility. */ @Column(name = "ovm_network_label") private String ovm3NetworkLabel; @@ -164,12 +165,4 @@ public String getHypervNetworkLabel() { return hypervNetworkLabel; } - public void setOvm3NetworkLabel(String ovm3NetworkLabel) { - this.ovm3NetworkLabel = ovm3NetworkLabel; - } - - @Override - public String getOvm3NetworkLabel() { - return ovm3NetworkLabel; - } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java b/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java index 2acb4138d234..9b6393d0fa2e 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/SystemVmTemplateRegistration.java @@ -310,8 +310,7 @@ public void setUpdated(Date updated) { new Pair<>(Hypervisor.HypervisorType.VMware, CPU.CPUArch.amd64), new Pair<>(Hypervisor.HypervisorType.XenServer, CPU.CPUArch.amd64), new Pair<>(Hypervisor.HypervisorType.Hyperv, CPU.CPUArch.amd64), - new Pair<>(Hypervisor.HypervisorType.LXC, CPU.CPUArch.amd64), - new Pair<>(Hypervisor.HypervisorType.Ovm3, CPU.CPUArch.amd64) + new Pair<>(Hypervisor.HypervisorType.LXC, CPU.CPUArch.amd64) ); protected static final List METADATA_TEMPLATE_LIST = new ArrayList<>(); @@ -323,7 +322,6 @@ public void setUpdated(Date updated) { put(Hypervisor.HypervisorType.XenServer, "router.template.xenserver"); put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv"); put(Hypervisor.HypervisorType.LXC, "router.template.lxc"); - put(Hypervisor.HypervisorType.Ovm3, "router.template.ovm3"); } }; @@ -334,7 +332,6 @@ public void setUpdated(Date updated) { put(Hypervisor.HypervisorType.VMware, ImageFormat.OVA); put(Hypervisor.HypervisorType.Hyperv, ImageFormat.VHD); put(Hypervisor.HypervisorType.LXC, ImageFormat.QCOW2); - put(Hypervisor.HypervisorType.Ovm3, ImageFormat.RAW); } }; @@ -345,7 +342,6 @@ public void setUpdated(Date updated) { put(Hypervisor.HypervisorType.VMware, OTHER_LINUX_ID); put(Hypervisor.HypervisorType.Hyperv, LINUX_12_ID); put(Hypervisor.HypervisorType.LXC, LINUX_12_ID); - put(Hypervisor.HypervisorType.Ovm3, LINUX_12_ID); } }; @@ -709,7 +705,6 @@ protected void updateHypervisorGuestOsMap() { hypervisorGuestOsMap.put(Hypervisor.HypervisorType.KVM, LINUX_12_ID); hypervisorGuestOsMap.put(Hypervisor.HypervisorType.Hyperv, LINUX_12_ID); hypervisorGuestOsMap.put(Hypervisor.HypervisorType.LXC, LINUX_12_ID); - hypervisorGuestOsMap.put(Hypervisor.HypervisorType.Ovm3, LINUX_12_ID); } catch (Exception e) { LOGGER.warn("Couldn't update System VM template guest OS ID, due to {}", e.getMessage()); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java index c7295414326d..2000199a6c20 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41500to41510.java @@ -34,7 +34,6 @@ import static com.cloud.hypervisor.Hypervisor.HypervisorType.Hyperv; import static com.cloud.hypervisor.Hypervisor.HypervisorType.KVM; import static com.cloud.hypervisor.Hypervisor.HypervisorType.LXC; -import static com.cloud.hypervisor.Hypervisor.HypervisorType.Ovm3; import static com.cloud.hypervisor.Hypervisor.HypervisorType.VMware; import static com.cloud.hypervisor.Hypervisor.HypervisorType.XenServer; @@ -89,8 +88,6 @@ public void updateSystemVmTemplates(final Connection conn) { hypervisorsListInUse.add(Hyperv); } else if (type.equals(LXC)) { hypervisorsListInUse.add(LXC); - } else if (type.equals(Ovm3)) { - hypervisorsListInUse.add(Ovm3); } } } catch (final SQLException e) { @@ -105,7 +102,6 @@ public void updateSystemVmTemplates(final Connection conn) { put(XenServer, "systemvm-xenserver-4.15.1"); put(Hyperv, "systemvm-hyperv-4.15.1"); put(LXC, "systemvm-lxc-4.15.1"); - put(Ovm3, "systemvm-ovm3-4.15.1"); } }; @@ -116,7 +112,6 @@ public void updateSystemVmTemplates(final Connection conn) { put(XenServer, "router.template.xenserver"); put(Hyperv, "router.template.hyperv"); put(LXC, "router.template.lxc"); - put(Ovm3, "router.template.ovm3"); } }; @@ -127,7 +122,6 @@ public void updateSystemVmTemplates(final Connection conn) { put(XenServer, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-xen.vhd.bz2"); put(Hyperv, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-hyperv.vhd.zip"); put(LXC, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-kvm.qcow2.bz2"); - put(Ovm3, "https://download.cloudstack.org/systemvm/4.15/systemvmtemplate-4.15.1-ovm.raw.bz2"); } }; @@ -138,7 +132,6 @@ public void updateSystemVmTemplates(final Connection conn) { put(VMware, "4006982765846d373eb3719b2fe4d720"); put(Hyperv, "0b9514e4b6cba1f636fea2125f0f7a5f"); put(LXC, "0e9f9a7d0957c3e0a2088e41b2da2cec"); - put(Ovm3, "ae3977e696b3e6c81bdcbb792d514d29"); } }; diff --git a/engine/schema/src/main/resources/META-INF/db/create-default-role-api-mappings.sql b/engine/schema/src/main/resources/META-INF/db/create-default-role-api-mappings.sql index d814b0fc298e..0c42ab75bd7b 100644 --- a/engine/schema/src/main/resources/META-INF/db/create-default-role-api-mappings.sql +++ b/engine/schema/src/main/resources/META-INF/db/create-default-role-api-mappings.sql @@ -157,10 +157,6 @@ INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'extractVolume', 'ALLOW', 134) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getApiLimit', 'ALLOW', 135) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getCloudIdentifier', 'ALLOW', 136) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getSolidFireAccountId', 'ALLOW', 137) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getSolidFireVolumeAccessGroupId', 'ALLOW', 138) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getSolidFireVolumeIscsiName', 'ALLOW', 139) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getSolidFireVolumeSize', 'ALLOW', 140) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getUploadParamsForTemplate', 'ALLOW', 141) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getUploadParamsForVolume', 'ALLOW', 142) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 2, 'getVMPassword', 'ALLOW', 143) ON DUPLICATE KEY UPDATE rule=rule; @@ -470,10 +466,6 @@ INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'extractVolume', 'ALLOW', 130) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getApiLimit', 'ALLOW', 131) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getCloudIdentifier', 'ALLOW', 132) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getSolidFireAccountId', 'ALLOW', 133) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getSolidFireVolumeAccessGroupId', 'ALLOW', 134) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getSolidFireVolumeIscsiName', 'ALLOW', 135) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getSolidFireVolumeSize', 'ALLOW', 136) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getUploadParamsForTemplate', 'ALLOW', 137) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getUploadParamsForVolume', 'ALLOW', 138) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 3, 'getVMPassword', 'ALLOW', 139) ON DUPLICATE KEY UPDATE rule=rule; @@ -749,10 +741,6 @@ INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'extractVolume', 'ALLOW', 108) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getApiLimit', 'ALLOW', 109) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getCloudIdentifier', 'ALLOW', 110) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getSolidFireAccountId', 'ALLOW', 111) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getSolidFireVolumeAccessGroupId', 'ALLOW', 112) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getSolidFireVolumeIscsiName', 'ALLOW', 113) ON DUPLICATE KEY UPDATE rule=rule; -INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getSolidFireVolumeSize', 'ALLOW', 114) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getUploadParamsForTemplate', 'ALLOW', 115) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getUploadParamsForVolume', 'ALLOW', 116) ON DUPLICATE KEY UPDATE rule=rule; INSERT INTO `cloud`.`role_permissions` (`uuid`, `role_id`, `rule`, `permission`, `sort_order`) values (UUID(), 4, 'getVMPassword', 'ALLOW', 117) ON DUPLICATE KEY UPDATE rule=rule; diff --git a/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java b/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java index ef50064050f8..0c283f527fcd 100644 --- a/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java +++ b/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java @@ -87,7 +87,6 @@ public class ConfigKey { public static final Pair SUBGROUP_KVM = new Pair<>("KVM", 2L); public static final Pair SUBGROUP_VMWARE = new Pair<>("VMware", 3L); public static final Pair SUBGROUP_XENSERVER = new Pair<>("XenServer", 4L); - public static final Pair SUBGROUP_OVM = new Pair<>("OVM", 5L); public static final Pair SUBGROUP_BAREMETAL = new Pair<>("Baremetal", 6L); public static final Pair SUBGROUP_CONSOLE_PROXY_VM = new Pair<>("ConsoleProxyVM", 1L); public static final Pair SUBGROUP_SEC_STORAGE_VM = new Pair<>("SecStorageVM", 2L); diff --git a/framework/jobs/src/test/resources/log4j.properties b/framework/jobs/src/test/resources/log4j.properties index 7ffdca8aea52..4253a201c255 100644 --- a/framework/jobs/src/test/resources/log4j.properties +++ b/framework/jobs/src/test/resources/log4j.properties @@ -30,5 +30,4 @@ log4j.appender.rolling.DatePattern='.'yyy-MM-dd log4j.appender.rolling.file.append=false log4j.category.org.apache=DEBUG, rolling, stdout #log4j.category.com.cloud.utils.db.Transaction=ALL -log4j.category.org.apache.cloudstack.network.contrail=ALL log4j.category.com.cloud.network=ALL diff --git a/plugins/api/solidfire-intg-test/pom.xml b/plugins/api/solidfire-intg-test/pom.xml deleted file mode 100644 index 0cc9d1aba5a2..000000000000 --- a/plugins/api/solidfire-intg-test/pom.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - 4.0.0 - cloud-plugin-api-solidfire-intg-test - Apache CloudStack Plugin - API SolidFire Integration Testing - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - org.apache.cloudstack - cloud-plugin-storage-volume-solidfire - ${project.version} - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - @{argLine} -Xmx1024m - - org/apache/cloudstack/solidfire/integration/* - - - - - - diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetPathForVolumeCmd.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetPathForVolumeCmd.java deleted file mode 100644 index 5ff7f82a7b0e..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetPathForVolumeCmd.java +++ /dev/null @@ -1,59 +0,0 @@ -// 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 org.apache.cloudstack.api.command.admin.solidfire; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.solidfire.ApiPathForVolumeResponse; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; - -@APICommand(name = "getPathForVolume", responseObject = ApiPathForVolumeResponse.class, description = "Get the path associated with the provided volume UUID", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class GetPathForVolumeCmd extends BaseCmd { - - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.STRING, description = "CloudStack Volume UUID", required = true) - private String _volumeUuid; - - @Inject private SolidFireIntegrationTestUtil _util; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public long getEntityOwnerId() { - return _util.getAccountIdForVolumeUuid(_volumeUuid); - } - - @Override - public void execute() { - logger.info("'GetPathForVolumeIdCmd.execute' method invoked"); - - String pathForVolume = _util.getPathForVolumeUuid(_volumeUuid); - - ApiPathForVolumeResponse response = new ApiPathForVolumeResponse(pathForVolume); - - response.setResponseName(getCommandName()); - response.setObjectName("apipathforvolume"); - - setResponseObject(response); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireAccountIdCmd.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireAccountIdCmd.java deleted file mode 100644 index baedb0389d55..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireAccountIdCmd.java +++ /dev/null @@ -1,64 +0,0 @@ -// 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 org.apache.cloudstack.api.command.admin.solidfire; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.solidfire.ApiSolidFireAccountIdResponse; -import org.apache.cloudstack.solidfire.SolidFireIntegrationTestManager; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; - -@APICommand(name = "getSolidFireAccountId", responseObject = ApiSolidFireAccountIdResponse.class, description = "Get SolidFire Account ID", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class GetSolidFireAccountIdCmd extends BaseCmd { - - @Parameter(name = ApiConstants.ACCOUNT_ID, type = CommandType.STRING, description = "CloudStack Account UUID", required = true) - private String csAccountUuid; - @Parameter(name = ApiConstants.STORAGE_ID, type = CommandType.STRING, description = "Storage Pool UUID", required = true) - private String storagePoolUuid; - - @Inject private SolidFireIntegrationTestManager manager; - @Inject private SolidFireIntegrationTestUtil util; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public long getEntityOwnerId() { - return util.getAccountIdForAccountUuid(csAccountUuid); - } - - @Override - public void execute() { - logger.info("'GetSolidFireAccountIdCmd.execute' method invoked"); - - long sfAccountId = manager.getSolidFireAccountId(csAccountUuid, storagePoolUuid); - - ApiSolidFireAccountIdResponse response = new ApiSolidFireAccountIdResponse(sfAccountId); - - response.setResponseName(getCommandName()); - response.setObjectName("apisolidfireaccountid"); - - this.setResponseObject(response); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeAccessGroupIdsCmd.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeAccessGroupIdsCmd.java deleted file mode 100644 index c250c870f8d7..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeAccessGroupIdsCmd.java +++ /dev/null @@ -1,73 +0,0 @@ -// 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 org.apache.cloudstack.api.command.admin.solidfire; - -import com.cloud.user.Account; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.solidfire.ApiSolidFireVolumeAccessGroupIdsResponse; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.solidfire.SolidFireIntegrationTestManager; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; - -@APICommand(name = "getSolidFireVolumeAccessGroupIds", responseObject = ApiSolidFireVolumeAccessGroupIdsResponse.class, description = "Get the SF Volume Access Group IDs", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class GetSolidFireVolumeAccessGroupIdsCmd extends BaseCmd { - - @Parameter(name = ApiConstants.CLUSTER_ID, type = CommandType.STRING, description = "Cluster UUID", required = true) - private String clusterUuid; - @Parameter(name = ApiConstants.STORAGE_ID, type = CommandType.STRING, description = "Storage Pool UUID", required = true) - private String storagePoolUuid; - - @Inject private SolidFireIntegrationTestManager manager; - @Inject private SolidFireIntegrationTestUtil util; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public long getEntityOwnerId() { - Account account = CallContext.current().getCallingAccount(); - - if (account != null) { - return account.getId(); - } - - return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked - } - - @Override - public void execute() { - logger.info("'GetSolidFireVolumeAccessGroupIdsCmd.execute' method invoked"); - - long[] sfVagIds = manager.getSolidFireVolumeAccessGroupIds(clusterUuid, storagePoolUuid); - - ApiSolidFireVolumeAccessGroupIdsResponse response = new ApiSolidFireVolumeAccessGroupIdsResponse(sfVagIds); - - response.setResponseName(getCommandName()); - response.setObjectName("apisolidfirevolumeaccessgroupids"); - - this.setResponseObject(response); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeSizeCmd.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeSizeCmd.java deleted file mode 100644 index 10af3be25b06..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetSolidFireVolumeSizeCmd.java +++ /dev/null @@ -1,62 +0,0 @@ -// 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 org.apache.cloudstack.api.command.admin.solidfire; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.solidfire.ApiSolidFireVolumeSizeResponse; -import org.apache.cloudstack.solidfire.SolidFireIntegrationTestManager; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; - -@APICommand(name = "getSolidFireVolumeSize", responseObject = ApiSolidFireVolumeSizeResponse.class, description = "Get the SF volume size including Hypervisor Snapshot Reserve", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class GetSolidFireVolumeSizeCmd extends BaseCmd { - - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.STRING, description = "Volume UUID", required = true) - private String volumeUuid; - - @Inject private SolidFireIntegrationTestManager manager; - @Inject private SolidFireIntegrationTestUtil util; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public long getEntityOwnerId() { - return util.getAccountIdForVolumeUuid(volumeUuid); - } - - @Override - public void execute() { - logger.info("'GetSolidFireVolumeSizeCmd.execute' method invoked"); - - long sfVolumeSize = manager.getSolidFireVolumeSize(volumeUuid); - - ApiSolidFireVolumeSizeResponse response = new ApiSolidFireVolumeSizeResponse(sfVolumeSize); - - response.setResponseName(getCommandName()); - response.setObjectName("apisolidfirevolumesize"); - - this.setResponseObject(response); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeSnapshotDetailsCmd.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeSnapshotDetailsCmd.java deleted file mode 100644 index bbb86bec31ed..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeSnapshotDetailsCmd.java +++ /dev/null @@ -1,65 +0,0 @@ -// 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 org.apache.cloudstack.api.command.admin.solidfire; - -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.solidfire.ApiVolumeSnapshotDetailsResponse; -import org.apache.cloudstack.api.response.solidfire.ApiVolumeiScsiNameResponse; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; - -@APICommand(name = "getVolumeSnapshotDetails", responseObject = ApiVolumeiScsiNameResponse.class, description = "Get Volume Snapshot Details", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) - -public class GetVolumeSnapshotDetailsCmd extends BaseCmd { - - @Parameter(name = ApiConstants.SNAPSHOT_ID, type = CommandType.STRING, description = "CloudStack Snapshot UUID", required = true) - private String snapshotUuid; - - @Inject private SolidFireIntegrationTestUtil util; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public long getEntityOwnerId() { - return util.getAccountIdForSnapshotUuid(snapshotUuid); - } - - @Override - public void execute() { - logger.info("'" + GetVolumeSnapshotDetailsCmd.class.getSimpleName() + ".execute' method invoked"); - - List responses = util.getSnapshotDetails(snapshotUuid); - - ListResponse listReponse = new ListResponse<>(); - - listReponse.setResponses(responses); - listReponse.setResponseName(getCommandName()); - listReponse.setObjectName("apivolumesnapshotdetails"); - - this.setResponseObject(listReponse); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeiScsiNameCmd.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeiScsiNameCmd.java deleted file mode 100644 index e2063ce9d69a..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/command/admin/solidfire/GetVolumeiScsiNameCmd.java +++ /dev/null @@ -1,60 +0,0 @@ -// 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 org.apache.cloudstack.api.command.admin.solidfire; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.solidfire.ApiVolumeiScsiNameResponse; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; - -@APICommand(name = "getVolumeiScsiName", responseObject = ApiVolumeiScsiNameResponse.class, description = "Get Volume's iSCSI Name", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) - -public class GetVolumeiScsiNameCmd extends BaseCmd { - - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.STRING, description = "CloudStack Volume UUID", required = true) - private String volumeUuid; - - @Inject private SolidFireIntegrationTestUtil _util; - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public long getEntityOwnerId() { - return _util.getAccountIdForVolumeUuid(volumeUuid); - } - - @Override - public void execute() { - logger.info("'GetVolumeiScsiNameCmd.execute' method invoked"); - - String volume_iScsiName = _util.getVolume_iScsiName(volumeUuid); - - ApiVolumeiScsiNameResponse response = new ApiVolumeiScsiNameResponse(volume_iScsiName); - - response.setResponseName(getCommandName()); - response.setObjectName("apivolumeiscsiname"); - - this.setResponseObject(response); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java deleted file mode 100644 index 3e0f820aeab7..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiPathForVolumeResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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 org.apache.cloudstack.api.response.solidfire; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; - -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; - -public class ApiPathForVolumeResponse extends BaseResponse { - @SerializedName(ApiConstants.PATH) - @Param(description = "The path field for the volume") - private String path; - - public ApiPathForVolumeResponse(String path) { - this.path = path; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireAccountIdResponse.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireAccountIdResponse.java deleted file mode 100644 index a1c2a4c32d18..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireAccountIdResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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 org.apache.cloudstack.api.response.solidfire; - -import com.cloud.serializer.Param; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.BaseResponse; - -public class ApiSolidFireAccountIdResponse extends BaseResponse { - @SerializedName("solidFireAccountId") - @Param(description = "SolidFire Account ID") - private long solidFireAccountId; - - public ApiSolidFireAccountIdResponse(long sfAccountId) { - solidFireAccountId = sfAccountId; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeAccessGroupIdsResponse.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeAccessGroupIdsResponse.java deleted file mode 100644 index 299b3bdd4c87..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeAccessGroupIdsResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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 org.apache.cloudstack.api.response.solidfire; - -import com.cloud.serializer.Param; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.BaseResponse; - -public class ApiSolidFireVolumeAccessGroupIdsResponse extends BaseResponse { - @SerializedName("solidFireVolumeAccessGroupIds") - @Param(description = "SolidFire Volume Access Group Ids") - private long[] solidFireVolumeAccessGroupIds; - - public ApiSolidFireVolumeAccessGroupIdsResponse(long[] sfVolumeAccessGroupIds) { - solidFireVolumeAccessGroupIds = sfVolumeAccessGroupIds; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeSizeResponse.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeSizeResponse.java deleted file mode 100644 index 9ae89d52310e..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiSolidFireVolumeSizeResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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 org.apache.cloudstack.api.response.solidfire; - -import com.cloud.serializer.Param; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.BaseResponse; - -public class ApiSolidFireVolumeSizeResponse extends BaseResponse { - @SerializedName("solidFireVolumeSize") - @Param(description = "SolidFire Volume Size Including Hypervisor Snapshot Reserve") - private long solidFireVolumeSize; - - public ApiSolidFireVolumeSizeResponse(long sfVolumeSize) { - solidFireVolumeSize = sfVolumeSize; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeSnapshotDetailsResponse.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeSnapshotDetailsResponse.java deleted file mode 100644 index 914fa1f1b0e9..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeSnapshotDetailsResponse.java +++ /dev/null @@ -1,43 +0,0 @@ -// 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 org.apache.cloudstack.api.response.solidfire; - -import com.cloud.serializer.Param; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.BaseResponse; - -public class ApiVolumeSnapshotDetailsResponse extends BaseResponse { - @SerializedName("volumeSnapshotId") - @Param(description = "CloudStack Volume Snapshot ID") - private long volumeSnapshotId; - - @SerializedName("snapshotDetailsName") - @Param(description = "Snapshot Details Name") - private String volumeSnapshotDetailsName; - - @SerializedName("snapshotDetailsValue") - @Param(description = "Snapshot Details Value") - private String volumeSnapshotDetailsValue; - - public ApiVolumeSnapshotDetailsResponse(long volumeSnapshotId, String volumeSnapshotDetailsName, String volumeSnapshotDetailsValue) { - this.volumeSnapshotId = volumeSnapshotId; - this.volumeSnapshotDetailsName = volumeSnapshotDetailsName; - this.volumeSnapshotDetailsValue = volumeSnapshotDetailsValue; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeiScsiNameResponse.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeiScsiNameResponse.java deleted file mode 100644 index f43e53352aaa..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/response/solidfire/ApiVolumeiScsiNameResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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 org.apache.cloudstack.api.response.solidfire; - -import com.cloud.serializer.Param; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.BaseResponse; - -public class ApiVolumeiScsiNameResponse extends BaseResponse { - @SerializedName("volumeiScsiName") - @Param(description = "Volume iSCSI Name") - private String volumeiScsiName; - - public ApiVolumeiScsiNameResponse(String volumeiScsiName) { - this.volumeiScsiName = volumeiScsiName; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestService.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestService.java deleted file mode 100644 index ff206d3a3b6a..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestService.java +++ /dev/null @@ -1,22 +0,0 @@ -// 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 org.apache.cloudstack.api.solidfire; - -import com.cloud.utils.component.PluggableService; - -public interface ApiSolidFireIntegrationTestService extends PluggableService { -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestServiceImpl.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestServiceImpl.java deleted file mode 100644 index 91868f4ef8f0..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/api/solidfire/ApiSolidFireIntegrationTestServiceImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -// 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 org.apache.cloudstack.api.solidfire; - -import java.util.List; -import java.util.ArrayList; - -import org.apache.cloudstack.api.command.admin.solidfire.GetPathForVolumeCmd; -import org.apache.cloudstack.api.command.admin.solidfire.GetSolidFireAccountIdCmd; -import org.apache.cloudstack.api.command.admin.solidfire.GetSolidFireVolumeAccessGroupIdsCmd; -import org.apache.cloudstack.api.command.admin.solidfire.GetVolumeSnapshotDetailsCmd; -import org.apache.cloudstack.api.command.admin.solidfire.GetVolumeiScsiNameCmd; -import org.apache.cloudstack.api.command.admin.solidfire.GetSolidFireVolumeSizeCmd; -import org.springframework.stereotype.Component; - -import com.cloud.utils.component.AdapterBase; - -@Component -public class ApiSolidFireIntegrationTestServiceImpl extends AdapterBase implements ApiSolidFireIntegrationTestService { - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - - cmdList.add(GetPathForVolumeCmd.class); - cmdList.add(GetSolidFireAccountIdCmd.class); - cmdList.add(GetSolidFireVolumeAccessGroupIdsCmd.class); - cmdList.add(GetVolumeiScsiNameCmd.class); - cmdList.add(GetSolidFireVolumeSizeCmd.class); - cmdList.add(GetVolumeSnapshotDetailsCmd.class); - - return cmdList; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManager.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManager.java deleted file mode 100644 index 302a034911f1..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManager.java +++ /dev/null @@ -1,23 +0,0 @@ -// 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 org.apache.cloudstack.solidfire; - -public interface SolidFireIntegrationTestManager { - long getSolidFireAccountId(String csAccountUuid, String storagePoolUuid); - long[] getSolidFireVolumeAccessGroupIds(String csClusterUuid, String storagePoolUuid); - long getSolidFireVolumeSize(String volumeUuid); -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManagerImpl.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManagerImpl.java deleted file mode 100644 index 0339379d116a..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/solidfire/SolidFireIntegrationTestManagerImpl.java +++ /dev/null @@ -1,107 +0,0 @@ -// 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 org.apache.cloudstack.solidfire; - -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.storage.VolumeDetailVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeDetailsDao; -import com.cloud.user.AccountDetailVO; -import com.cloud.user.AccountDetailsDao; -import com.cloud.utils.exception.CloudRuntimeException; - -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; -import org.apache.cloudstack.util.solidfire.SolidFireIntegrationTestUtil; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.List; -import javax.inject.Inject; - -@Component -public class SolidFireIntegrationTestManagerImpl implements SolidFireIntegrationTestManager { - @Inject private AccountDetailsDao accountDetailsDao; - @Inject private HostDao hostDao; - @Inject private SolidFireIntegrationTestUtil util; - @Inject private StoragePoolDetailsDao storagePoolDetailsDao; - @Inject private VolumeDao volumeDao; - @Inject private VolumeDetailsDao volumeDetailsDao; - - @Override - public long getSolidFireAccountId(String csAccountUuid, String storagePoolUuid) { - long csAccountId = util.getAccountIdForAccountUuid(csAccountUuid); - long storagePoolId = util.getStoragePoolIdForStoragePoolUuid(storagePoolUuid); - - AccountDetailVO accountDetail = accountDetailsDao.findDetail(csAccountId, SolidFireUtil.getAccountKey(storagePoolId)); - - if (accountDetail == null) { - throw new CloudRuntimeException("Unable to find SF account for storage " + storagePoolUuid + " for CS account " + csAccountUuid); - } - - String sfAccountId = accountDetail.getValue(); - - return Long.parseLong(sfAccountId); - } - - @Override - public long[] getSolidFireVolumeAccessGroupIds(String csClusterUuid, String storagePoolUuid) { - long storagePoolId = util.getStoragePoolIdForStoragePoolUuid(storagePoolUuid); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - List sfVags = SolidFireUtil.getAllVags(sfConnection); - - long csClusterId = util.getClusterIdForClusterUuid(csClusterUuid); - List hosts = hostDao.findByClusterId(csClusterId); - - if (hosts == null) { - return new long[0]; - } - - List vagIds = new ArrayList<>(hosts.size()); - - for (HostVO host : hosts) { - String iqn = host.getStorageUrl(); - - SolidFireUtil.SolidFireVag sfVag = SolidFireUtil.getVolumeAccessGroup(iqn, sfVags); - - if (sfVag != null) { - if (!vagIds.contains(sfVag.getId())) { - vagIds.add(sfVag.getId()); - } - } - } - - return vagIds.stream().mapToLong(l -> l).toArray(); - } - - @Override - public long getSolidFireVolumeSize(String volumeUuid) { - VolumeVO volume = volumeDao.findByUuid(volumeUuid); - - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volume.getId(), SolidFireUtil.VOLUME_SIZE); - - if (volumeDetail != null && volumeDetail.getValue() != null) { - return Long.parseLong(volumeDetail.getValue()); - } - - throw new CloudRuntimeException("Unable to determine the size of the SolidFire volume"); - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/util/solidfire/SolidFireIntegrationTestUtil.java b/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/util/solidfire/SolidFireIntegrationTestUtil.java deleted file mode 100644 index 4cbf74aba675..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/java/org/apache/cloudstack/util/solidfire/SolidFireIntegrationTestUtil.java +++ /dev/null @@ -1,145 +0,0 @@ -// 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 org.apache.cloudstack.util.solidfire; - -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.user.Account; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.exception.CloudRuntimeException; - -import org.apache.cloudstack.api.response.solidfire.ApiVolumeSnapshotDetailsResponse; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -public class SolidFireIntegrationTestUtil { - @Inject private AccountDao accountDao; - @Inject private ClusterDao clusterDao; - @Inject private PrimaryDataStoreDao storagePoolDao; - @Inject private SnapshotDao snapshotDao; - @Inject private SnapshotDetailsDao snapshotDetailsDao; - @Inject private VolumeDao volumeDao; - - private SolidFireIntegrationTestUtil() {} - - public long getAccountIdForAccountUuid(String accountUuid) { - Account account = accountDao.findByUuid(accountUuid); - - if (account == null) { - throw new CloudRuntimeException("Unable to find Account for ID: " + accountUuid); - } - - return account.getAccountId(); - } - - public long getAccountIdForVolumeUuid(String volumeUuid) { - VolumeVO volume = volumeDao.findByUuid(volumeUuid); - - if (volume == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + volumeUuid); - } - - return volume.getAccountId(); - } - - public long getAccountIdForSnapshotUuid(String snapshotUuid) { - SnapshotVO snapshot = snapshotDao.findByUuid(snapshotUuid); - - if (snapshot == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + snapshotUuid); - } - - return snapshot.getAccountId(); - } - - public long getClusterIdForClusterUuid(String clusterUuid) { - ClusterVO cluster = clusterDao.findByUuid(clusterUuid); - - if (cluster == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + clusterUuid); - } - - return cluster.getId(); - } - - public long getStoragePoolIdForStoragePoolUuid(String storagePoolUuid) { - StoragePoolVO storagePool = storagePoolDao.findByUuid(storagePoolUuid); - - if (storagePool == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + storagePoolUuid); - } - - return storagePool.getId(); - } - - public String getPathForVolumeUuid(String volumeUuid) { - VolumeVO volume = volumeDao.findByUuid(volumeUuid); - - if (volume == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + volumeUuid); - } - - return volume.getPath(); - } - - public String getVolume_iScsiName(String volumeUuid) { - VolumeVO volume = volumeDao.findByUuid(volumeUuid); - - if (volume == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + volumeUuid); - } - - return volume.get_iScsiName(); - } - - public List getSnapshotDetails(String snapshotUuid) { - SnapshotVO snapshot = snapshotDao.findByUuid(snapshotUuid); - - if (snapshot == null) { - throw new CloudRuntimeException("Unable to find Volume for ID: " + snapshotUuid); - } - - List snapshotDetails = snapshotDetailsDao.listDetails(snapshot.getId()); - - List responses = new ArrayList<>(); - - if (snapshotDetails != null) { - for (SnapshotDetailsVO snapshotDetail : snapshotDetails) { - ApiVolumeSnapshotDetailsResponse response = new ApiVolumeSnapshotDetailsResponse( - snapshotDetail.getResourceId(), - snapshotDetail.getName(), - snapshotDetail.getValue() - ); - - responses.add(response); - } - } - - return responses; - } -} diff --git a/plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/module.properties b/plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/module.properties deleted file mode 100644 index 3b3f2a816770..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=solidfire-intg-test -parent=api diff --git a/plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/spring-solidfire-intg-test-context.xml b/plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/spring-solidfire-intg-test-context.xml deleted file mode 100644 index 28d1e1a9024c..000000000000 --- a/plugins/api/solidfire-intg-test/src/main/resources/META-INF/cloudstack/solidfire-intg-test/spring-solidfire-intg-test-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/hypervisors/ovm/pom.xml b/plugins/hypervisors/ovm/pom.xml deleted file mode 100644 index d29f9afa73a0..000000000000 --- a/plugins/hypervisors/ovm/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - cloud-plugin-hypervisor-ovm - Apache CloudStack Plugin - Hypervisor OracleVM - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - com.citrix.hypervisor - xen-api - ${cs.xapi.version} - - - diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmDiscoverer.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmDiscoverer.java deleted file mode 100644 index 7dfd98301d72..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmDiscoverer.java +++ /dev/null @@ -1,259 +0,0 @@ -// 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.ovm.hypervisor; - -import java.net.InetAddress; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.xmlrpc.XmlRpcException; - -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.configuration.Config; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.exception.DiscoveryException; -import com.cloud.host.HostInfo; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.ovm.object.Connection; -import com.cloud.ovm.object.OvmHost; -import com.cloud.resource.Discoverer; -import com.cloud.resource.DiscovererBase; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.utils.UuidUtils; -import com.cloud.utils.db.QueryBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.ssh.SSHCmdHelper; - -public class OvmDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter { - protected String _publicNetworkDevice; - protected String _privateNetworkDevice; - protected String _guestNetworkDevice; - - @Inject - ClusterDao _clusterDao; - @Inject - ResourceManager _resourceMgr; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _publicNetworkDevice = _params.get(Config.OvmPublicNetwork.key()); - _privateNetworkDevice = _params.get(Config.OvmPrivateNetwork.key()); - _guestNetworkDevice = _params.get(Config.OvmGuestNetwork.key()); - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); - return true; - } - - protected OvmDiscoverer() { - } - - @Override - public boolean stop() { - _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); - return super.stop(); - } - - private boolean checkIfExisted(String guid) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); - sc.and(sc.entity().getGuid(), SearchCriteria.Op.EQ, guid); - sc.and(sc.entity().getHypervisorType(), SearchCriteria.Op.EQ, HypervisorType.Ovm); - List hosts = sc.list(); - return !hosts.isEmpty(); - } - - @Override - public Map> - find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) throws DiscoveryException { - Connection conn = null; - - if (!url.getScheme().equals("http")) { - String msg = "urlString is not http so we're not taking care of the discovery for this: " + url; - logger.debug(msg); - return null; - } - if (clusterId == null) { - String msg = "must specify cluster Id when add host"; - logger.debug(msg); - throw new CloudRuntimeException(msg); - } - - if (podId == null) { - String msg = "must specify pod Id when add host"; - logger.debug(msg); - throw new CloudRuntimeException(msg); - } - - ClusterVO cluster = _clusterDao.findById(clusterId); - if (cluster == null || (cluster.getHypervisorType() != HypervisorType.Ovm)) { - if (logger.isInfoEnabled()) - logger.info("invalid cluster id or cluster is not for Ovm hypervisors"); - return null; - } - - String agentUsername = _params.get("agentusername"); - if (agentUsername == null) { - throw new CloudRuntimeException("Agent user name must be specified"); - } - - String agentPassword = _params.get("agentpassword"); - if (agentPassword == null) { - throw new CloudRuntimeException("Agent password must be specified"); - } - - try { - String hostname = url.getHost(); - InetAddress ia = InetAddress.getByName(hostname); - String hostIp = ia.getHostAddress(); - String guid = UuidUtils.nameUUIDFromBytes(hostIp.getBytes()).toString(); - - if (checkIfExisted(guid)) { - throw new CloudRuntimeException("The host " + hostIp + " has been added before"); - } - - logger.debug("Ovm discover is going to disover host having guid " + guid); - - ClusterVO clu = _clusterDao.findById(clusterId); - if (clu.getGuid() == null) { - clu.setGuid(UUID.randomUUID().toString()); - _clusterDao.update(clusterId, clu); - } - - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hostIp, 22); - sshConnection.connect(null, 60000, 60000); - sshConnection = SSHCmdHelper.acquireAuthorizedConnection(hostIp, username, password); - if (sshConnection == null) { - throw new DiscoveryException(String.format("Cannot connect to ovm host(IP=%1$s, username=%2$s, password=%3$s, discover failed", hostIp, username, - password)); - } - - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "[ -f '/etc/ovs-agent/agent.ini' ]")) { - throw new DiscoveryException("Can not find /etc/ovs-agent/agent.ini " + hostIp); - } - - Map details = new HashMap(); - OvmResourceBase ovmResource = new OvmResourceBase(); - details.put("ip", hostIp); - details.put("username", username); - details.put("password", password); - details.put("zone", Long.toString(dcId)); - details.put("guid", guid); - details.put("pod", Long.toString(podId)); - details.put("cluster", Long.toString(clusterId)); - details.put("agentusername", agentUsername); - details.put("agentpassword", agentPassword); - if (_publicNetworkDevice != null) { - details.put("public.network.device", _publicNetworkDevice); - } - if (_privateNetworkDevice != null) { - details.put("private.network.device", _privateNetworkDevice); - } - if (_guestNetworkDevice != null) { - details.put("guest.network.device", _guestNetworkDevice); - } - - Map params = new HashMap(); - params.putAll(details); - ovmResource.configure("Ovm Server", params); - ovmResource.start(); - - conn = new Connection(hostIp, "oracle", agentPassword); - /* After resource start, we are able to execute our agent api */ - OvmHost.Details d = OvmHost.getDetails(conn); - details.put("agentVersion", d.agentVersion); - details.put(HostInfo.HOST_OS_KERNEL_VERSION, d.dom0KernelVersion); - details.put(HostInfo.HYPERVISOR_VERSION, d.hypervisorVersion); - - Map> resources = new HashMap>(); - resources.put(ovmResource, details); - return resources; - } catch (XmlRpcException e) { - logger.debug("XmlRpc exception, Unable to discover OVM: " + url, e); - return null; - } catch (UnknownHostException e) { - logger.debug("Host name resolve failed exception, Unable to discover OVM: " + url, e); - return null; - } catch (ConfigurationException e) { - logger.debug("Configure resource failed, Unable to discover OVM: " + url, e); - return null; - } catch (Exception e) { - logger.debug("Unable to discover OVM: " + url, e); - return null; - } - } - - @Override - public void postDiscovery(List hosts, long msId) throws DiscoveryException { - // TODO Auto-generated method stub - - } - - @Override - public boolean matchHypervisor(String hypervisor) { - return HypervisorType.Ovm.toString().equalsIgnoreCase(hypervisor); - } - - @Override - public HypervisorType getHypervisorType() { - return HypervisorType.Ovm; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - StartupCommand firstCmd = startup[0]; - if (!(firstCmd instanceof StartupRoutingCommand)) { - return null; - } - - StartupRoutingCommand ssCmd = ((StartupRoutingCommand)firstCmd); - if (ssCmd.getHypervisorType() != HypervisorType.Ovm) { - return null; - } - - return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.Ovm, details, hostTags); - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (host.getType() != com.cloud.host.Host.Type.Routing || host.getHypervisorType() != HypervisorType.Ovm) { - return null; - } - - _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage); - return new DeleteHostAnswer(true); - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmFencer.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmFencer.java deleted file mode 100644 index 60792f0ddb7d..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmFencer.java +++ /dev/null @@ -1,117 +0,0 @@ -// 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.ovm.hypervisor; - -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.FenceAnswer; -import com.cloud.agent.api.FenceCommand; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.ha.FenceBuilder; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceManager; -import com.cloud.utils.component.AdapterBase; -import com.cloud.vm.VirtualMachine; - -public class OvmFencer extends AdapterBase implements FenceBuilder { - @Inject - AgentManager _agentMgr; - @Inject - ResourceManager _resourceMgr; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - return true; - } - - @Override - public boolean start() { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean stop() { - // TODO Auto-generated method stub - return true; - } - - public OvmFencer() { - super(); - } - - @Override - public Boolean fenceOff(VirtualMachine vm, Host host) { - if (host.getHypervisorType() != HypervisorType.Ovm) { - logger.debug("Don't know how to fence non Ovm hosts " + host.getHypervisorType()); - return null; - } - - List hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); - FenceCommand fence = new FenceCommand(vm, host); - - for (HostVO h : hosts) { - if (h.getHypervisorType() != HypervisorType.Ovm) { - continue; - } - - if (h.getStatus() != Status.Up) { - continue; - } - - if (h.getId() == host.getId()) { - continue; - } - - FenceAnswer answer; - try { - answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); - } catch (AgentUnavailableException e) { - if (logger.isDebugEnabled()) { - logger.debug("Moving on to the next host because " + h.toString() + " is unavailable", e); - } - continue; - } catch (OperationTimedoutException e) { - if (logger.isDebugEnabled()) { - logger.debug("Moving on to the next host because " + h.toString() + " is unavailable", e); - } - continue; - } - - if (answer != null && answer.getResult()) { - return true; - } - } - - if (logger.isDebugEnabled()) { - logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); - } - - return false; - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmGuru.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmGuru.java deleted file mode 100644 index 1978ef17823f..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmGuru.java +++ /dev/null @@ -1,67 +0,0 @@ -// 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.ovm.hypervisor; - -import java.util.Map; - -import javax.inject.Inject; - -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.HypervisorGuru; -import com.cloud.hypervisor.HypervisorGuruBase; -import com.cloud.storage.GuestOSVO; -import com.cloud.storage.dao.GuestOSDao; -import com.cloud.vm.VirtualMachineProfile; - -public class OvmGuru extends HypervisorGuruBase implements HypervisorGuru { - @Inject - GuestOSDao _guestOsDao; - - protected OvmGuru() { - super(); - } - - @Override - public HypervisorType getHypervisorType() { - return HypervisorType.Ovm; - } - - @Override - public VirtualMachineTO implement(VirtualMachineProfile vm) { - VirtualMachineTO to = toVirtualMachineTO(vm); - to.setBootloader(vm.getBootLoaderType()); - - // Determine the VM's OS description - GuestOSVO guestOS = _guestOsDao.findById(vm.getVirtualMachine().getGuestOSId()); - to.setOs(guestOS.getDisplayName()); - - return to; - } - - @Override - public boolean trackVmHostChange() { - return true; - } - - @Override - public Map getClusterSettings(long vmId) { - return null; - } - - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmHelper.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmHelper.java deleted file mode 100644 index 2eb07360fec0..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmHelper.java +++ /dev/null @@ -1,65 +0,0 @@ -// 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.ovm.hypervisor; - -import java.util.HashMap; - -public class OvmHelper { - private static final HashMap s_ovmMap = new HashMap(); - - public static final String ORACLE_LINUX = "Oracle Linux"; - public static final String ORACLE_SOLARIS = "Oracle Solaris"; - public static final String WINDOWS = "Windows"; - - static { - s_ovmMap.put("Oracle Enterprise Linux 6.0 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 6.0 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.0 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.0 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.1 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.1 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.2 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.2 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.3 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.3 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.4 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.4 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.5 (32-bit)", ORACLE_LINUX); - s_ovmMap.put("Oracle Enterprise Linux 5.5 (64-bit)", ORACLE_LINUX); - s_ovmMap.put("Windows 7 (32-bit)", WINDOWS); - s_ovmMap.put("Windows 7 (64-bit)", WINDOWS); - s_ovmMap.put("Windows Server 2003 (32-bit)", WINDOWS); - s_ovmMap.put("Windows Server 2003 (64-bit)", WINDOWS); - s_ovmMap.put("Windows Server 2008 (32-bit)", WINDOWS); - s_ovmMap.put("Windows Server 2008 (64-bit)", WINDOWS); - s_ovmMap.put("Windows Server 2008 R2 (64-bit)", WINDOWS); - s_ovmMap.put("Windows 2000 SP4 (32-bit)", WINDOWS); - s_ovmMap.put("Windows Vista (32-bit)", WINDOWS); - s_ovmMap.put("Windows XP SP2 (32-bit)", WINDOWS); - s_ovmMap.put("Windows XP SP3 (32-bit)", WINDOWS); - s_ovmMap.put("Sun Solaris 10(32-bit)", ORACLE_SOLARIS); - s_ovmMap.put("Sun Solaris 10(64-bit)", ORACLE_SOLARIS); - s_ovmMap.put("Sun Solaris 9(Experimental)", ORACLE_SOLARIS); - s_ovmMap.put("Sun Solaris 8(Experimental)", ORACLE_SOLARIS); - s_ovmMap.put("Sun Solaris 11 (32-bit)", ORACLE_SOLARIS); - s_ovmMap.put("Sun Solaris 11 (64-bit)", ORACLE_SOLARIS); - } - - public static String getOvmGuestType(String stdType) { - return s_ovmMap.get(stdType); - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmResourceBase.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmResourceBase.java deleted file mode 100644 index 514554290392..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/hypervisor/OvmResourceBase.java +++ /dev/null @@ -1,1268 +0,0 @@ -// 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.ovm.hypervisor; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.naming.ConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.apache.xmlrpc.XmlRpcException; - -import com.trilead.ssh2.SCPClient; - -import org.apache.cloudstack.storage.to.TemplateObjectTO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AttachIsoCommand; -import com.cloud.agent.api.CheckNetworkAnswer; -import com.cloud.agent.api.CheckNetworkCommand; -import com.cloud.agent.api.CheckVirtualMachineAnswer; -import com.cloud.agent.api.CheckVirtualMachineCommand; -import com.cloud.agent.api.CleanupNetworkRulesCmd; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; -import com.cloud.agent.api.CreateStoragePoolCommand; -import com.cloud.agent.api.DeleteStoragePoolCommand; -import com.cloud.agent.api.FenceAnswer; -import com.cloud.agent.api.FenceCommand; -import com.cloud.agent.api.GetHostStatsAnswer; -import com.cloud.agent.api.GetHostStatsCommand; -import com.cloud.agent.api.GetStorageStatsAnswer; -import com.cloud.agent.api.GetStorageStatsCommand; -import com.cloud.agent.api.GetVmStatsAnswer; -import com.cloud.agent.api.GetVmStatsCommand; -import com.cloud.agent.api.GetVncPortAnswer; -import com.cloud.agent.api.GetVncPortCommand; -import com.cloud.agent.api.HostStatsEntry; -import com.cloud.agent.api.HostVmStateReportEntry; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.MigrateAnswer; -import com.cloud.agent.api.MigrateCommand; -import com.cloud.agent.api.ModifyStoragePoolAnswer; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.PingRoutingCommand; -import com.cloud.agent.api.PingTestCommand; -import com.cloud.agent.api.PrepareForMigrationAnswer; -import com.cloud.agent.api.PrepareForMigrationCommand; -import com.cloud.agent.api.PrepareOCFS2NodesCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.RebootAnswer; -import com.cloud.agent.api.RebootCommand; -import com.cloud.agent.api.SecurityGroupRuleAnswer; -import com.cloud.agent.api.SecurityGroupRulesCmd; -import com.cloud.agent.api.StartAnswer; -import com.cloud.agent.api.StartCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.agent.api.StopAnswer; -import com.cloud.agent.api.StopCommand; -import com.cloud.agent.api.VmStatsEntry; -import com.cloud.agent.api.storage.CopyVolumeAnswer; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.storage.CreateAnswer; -import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; -import com.cloud.agent.api.storage.DestroyCommand; -import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; -import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.NfsTO; -import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.StorageFilerTO; -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.agent.api.to.VolumeTO; -import com.cloud.host.Host.Type; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetworkSetupInfo; -import com.cloud.ovm.object.Connection; -import com.cloud.ovm.object.OvmBridge; -import com.cloud.ovm.object.OvmDisk; -import com.cloud.ovm.object.OvmHost; -import com.cloud.ovm.object.OvmSecurityGroup; -import com.cloud.ovm.object.OvmStoragePool; -import com.cloud.ovm.object.OvmVif; -import com.cloud.ovm.object.OvmVlan; -import com.cloud.ovm.object.OvmVm; -import com.cloud.ovm.object.OvmVolume; -import com.cloud.resource.ServerResource; -import com.cloud.resource.hypervisor.HypervisorResource; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.Volume; -import com.cloud.storage.template.TemplateProp; -import com.cloud.template.VirtualMachineTemplate.BootloaderType; -import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; -import com.cloud.utils.UuidUtils; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.script.Script; -import com.cloud.utils.ssh.SSHCmdHelper; -import com.cloud.vm.DiskProfile; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.PowerState; - -public class OvmResourceBase implements ServerResource, HypervisorResource { - protected Logger logger = LogManager.getLogger(getClass()); - String _name; - Long _zoneId; - Long _podId; - Long _clusterId; - String _ip; - String _username; - String _password; - String _guid; - String _agentUserName = "oracle"; - String _agentPassword; - Connection _conn; - String _privateNetworkName; - String _publicNetworkName; - String _guestNetworkName; - boolean _canBridgeFirewall; - static boolean s_isHeartBeat = false; - List _bridges = null; - private final Map> _vmNetworkStats = new ConcurrentHashMap>(); - private static String s_ovsAgentPath = "/opt/ovs-agent-latest"; - - - static HashMap s_powerStateMaps; - static { - s_powerStateMaps = new HashMap(); - s_powerStateMaps.put("RUNNING", PowerState.PowerOn); - s_powerStateMaps.put("DOWN", PowerState.PowerOff); - s_powerStateMaps.put("ERROR", PowerState.PowerUnknown); - s_powerStateMaps.put("SUSPEND", PowerState.PowerOff); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - try { - _zoneId = Long.parseLong((String)params.get("zone")); - _podId = Long.parseLong((String)params.get("pod")); - _clusterId = Long.parseLong((String)params.get("cluster")); - _ip = (String)params.get("ip"); - _username = (String)params.get("username"); - _password = (String)params.get("password"); - _guid = (String)params.get("guid"); - _privateNetworkName = (String)params.get("private.network.device"); - _publicNetworkName = (String)params.get("public.network.device"); - _guestNetworkName = (String)params.get("guest.network.device"); - _agentUserName = (String)params.get("agentusername"); - _agentPassword = (String)params.get("agentpassword"); - } catch (Exception e) { - logger.debug("Configure " + _name + " failed", e); - throw new ConfigurationException("Configure " + _name + " failed, " + e.toString()); - } - - if (_podId == null) { - throw new ConfigurationException("Unable to get the pod"); - } - - if (_ip == null) { - throw new ConfigurationException("Unable to get the host address"); - } - - if (_username == null) { - throw new ConfigurationException("Unable to get the username"); - } - - if (_password == null) { - throw new ConfigurationException("Unable to get the password"); - } - - if (_guid == null) { - throw new ConfigurationException("Unable to get the guid"); - } - - if (_agentUserName == null) { - throw new ConfigurationException("Unable to get agent user name"); - } - - if (_agentPassword == null) { - throw new ConfigurationException("Unable to get agent password"); - } - - try { - setupServer(); - } catch (Exception e) { - logger.debug("Setup server failed, ip " + _ip, e); - throw new ConfigurationException("Unable to setup server"); - } - - _conn = new Connection(_ip, _agentUserName, _agentPassword); - try { - OvmHost.registerAsPrimary(_conn); - OvmHost.registerAsVmServer(_conn); - _bridges = OvmBridge.getAllBridges(_conn); - } catch (XmlRpcException e) { - logger.debug("Get bridges failed", e); - throw new ConfigurationException("Cannot get bridges on host " + _ip + "," + e.getMessage()); - } - - if (_privateNetworkName != null && !_bridges.contains(_privateNetworkName)) { - throw new ConfigurationException("Cannot find bridge " + _privateNetworkName + " on host " + _ip + ", all bridges are:" + _bridges); - } - - if (_publicNetworkName != null && !_bridges.contains(_publicNetworkName)) { - throw new ConfigurationException("Cannot find bridge " + _publicNetworkName + " on host " + _ip + ", all bridges are:" + _bridges); - } - - if (_guestNetworkName != null && !_bridges.contains(_guestNetworkName)) { - throw new ConfigurationException("Cannot find bridge " + _guestNetworkName + " on host " + _ip + ", all bridges are:" + _bridges); - } - - /* set to false so each time ModifyStoragePoolCommand will re-setup heartbeat*/ - s_isHeartBeat = false; - - /* - try { - _canBridgeFirewall = canBridgeFirewall(); - } catch (XmlRpcException e) { - logger.error("Failed to detect whether the host supports security groups.", e); - _canBridgeFirewall = false; - } - */ - - _canBridgeFirewall = false; - - logger.debug("OVM host doesn't support security groups."); - - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public Type getType() { - return Type.Routing; - } - - protected void fillHostInfo(StartupRoutingCommand cmd) { - try { - OvmHost.Details hostDetails = OvmHost.getDetails(_conn); - - cmd.setName(hostDetails.name); - cmd.setSpeed(hostDetails.cpuSpeed); - cmd.setCpus(hostDetails.cpuNum); - cmd.setMemory(hostDetails.freeMemory); - cmd.setDom0MinMemory(hostDetails.dom0Memory); - cmd.setGuid(_guid); - cmd.setDataCenter(_zoneId.toString()); - cmd.setPod(_podId.toString()); - cmd.setCluster(_clusterId.toString()); - cmd.setVersion(OvmResourceBase.class.getPackage().getImplementationVersion()); - cmd.setHypervisorType(HypervisorType.Ovm); - //TODO: introudce PIF - cmd.setPrivateIpAddress(_ip); - cmd.setStorageIpAddress(_ip); - - String defaultBridge = OvmBridge.getBridgeByIp(_conn, _ip); - if (_publicNetworkName == null) { - _publicNetworkName = defaultBridge; - } - if (_privateNetworkName == null) { - _privateNetworkName = _publicNetworkName; - } - if (_guestNetworkName == null) { - _guestNetworkName = _privateNetworkName; - } - Map d = cmd.getHostDetails(); - d.put("public.network.device", _publicNetworkName); - d.put("private.network.device", _privateNetworkName); - d.put("guest.network.device", _guestNetworkName); - cmd.setHostDetails(d); - - logger.debug(String.format("Add a OVM host(%s)", hostDetails.toJson())); - } catch (XmlRpcException e) { - logger.debug("XML RPC Exception" + e.getMessage(), e); - throw new CloudRuntimeException("XML RPC Exception" + e.getMessage(), e); - } - } - - protected void setupServer() throws IOException { - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_ip, 22); - sshConnection.connect(null, 60000, 60000); - if (!sshConnection.authenticateWithPassword(_username, _password)) { - throw new CloudRuntimeException("Unable to authenticate"); - } - SCPClient scp = new SCPClient(sshConnection); - - String configScriptName = "scripts/vm/hypervisor/ovm/configureOvm.sh"; - String configScriptPath = Script.findScript("", configScriptName); - if (configScriptPath == null) { - throw new CloudRuntimeException("Unable to find " + configScriptName); - } - scp.put(configScriptPath, "/usr/bin/", "0755"); - - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "sh /usr/bin/configureOvm.sh preSetup")) { - throw new CloudRuntimeException("Execute configureOvm.sh preSetup failed on " + _ip); - } - - File tmp = new File(configScriptPath); - File scriptDir = new File(tmp.getParent()); - File[] scripts = scriptDir.listFiles(); - for (int i = 0; i < scripts.length; i++) { - File script = scripts[i]; - if (script.getName().equals("configureOvm.sh")) { - continue; - } - - if (logger.isDebugEnabled()) { - logger.debug("Copying " + script.getPath() + " to " + s_ovsAgentPath + " on " + _ip + " with permission 0644"); - } - scp.put(script.getPath(), s_ovsAgentPath, "0644"); - } - - sshConnection = SSHCmdHelper.acquireAuthorizedConnection(_ip, _username, _password); - if (sshConnection == null) { - throw new CloudRuntimeException(String.format("Cannot connect to ovm host(IP=%1$s, username=%2$s)", _ip, _username)); - } - - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "sh /usr/bin/configureOvm.sh postSetup")) { - throw new CloudRuntimeException("Execute configureOvm.sh postSetup failed on " + _ip); - } - - } - - @Override - public StartupCommand[] initialize() { - try { - StartupRoutingCommand cmd = new StartupRoutingCommand(); - fillHostInfo(cmd); - cmd.setCaps("hvm"); - return new StartupCommand[] {cmd}; - } catch (Exception e) { - logger.debug("Ovm resource initializes failed", e); - return null; - } - } - - @Override - public PingCommand getCurrentStatus(long id) { - try { - OvmHost.ping(_conn); - return new PingRoutingCommand(getType(), id, getHostVmStateReport()); - } catch (XmlRpcException e) { - logger.debug("Check agent status failed", e); - return null; - } - } - - protected ReadyAnswer execute(ReadyCommand cmd) { - try { - OvmHost.Details d = OvmHost.getDetails(_conn); - //TODO: cleanup halted vm - if (d.primaryIp.equalsIgnoreCase(_ip)) { - return new ReadyAnswer(cmd); - } else { - logger.debug("Primary IP changes to " + d.primaryIp + ", it should be " + _ip); - return new ReadyAnswer(cmd, "I am not the primary server"); - } - } catch (XmlRpcException e) { - logger.debug("XML RPC Exception" + e.getMessage(), e); - throw new CloudRuntimeException("XML RPC Exception" + e.getMessage(), e); - } - - } - - protected void createNfsSr(StorageFilerTO pool) throws XmlRpcException { - String mountPoint = String.format("%1$s:%2$s", pool.getHost(), pool.getPath()); - OvmStoragePool.Details d = new OvmStoragePool.Details(); - d.path = mountPoint; - d.type = OvmStoragePool.NFS; - d.uuid = pool.getUuid(); - OvmStoragePool.create(_conn, d); - logger.debug(String.format("Created SR (mount point:%1$s)", mountPoint)); - } - - protected void createOCFS2Sr(StorageFilerTO pool) throws XmlRpcException { - OvmStoragePool.Details d = new OvmStoragePool.Details(); - d.path = pool.getPath(); - d.type = OvmStoragePool.OCFS2; - d.uuid = pool.getUuid(); - OvmStoragePool.create(_conn, d); - logger.debug(String.format("Created SR (mount point:%1$s)", d.path)); - } - - private void setupHeartBeat(String poolUuid) { - try { - if (!s_isHeartBeat) { - OvmHost.setupHeartBeat(_conn, poolUuid, _ip); - s_isHeartBeat = true; - } - } catch (Exception e) { - logger.debug("setup heart beat for " + _ip + " failed", e); - s_isHeartBeat = false; - } - } - - protected Answer execute(ModifyStoragePoolCommand cmd) { - StorageFilerTO pool = cmd.getPool(); - try { - if (pool.getType() == StoragePoolType.NetworkFilesystem) { - createNfsSr(pool); - } else if (pool.getType() == StoragePoolType.OCFS2) { - createOCFS2Sr(pool); - } else { - return new Answer(cmd, false, "The pool type: " + pool.getType().name() + " is not supported."); - } - - setupHeartBeat(pool.getUuid()); - OvmStoragePool.Details d = OvmStoragePool.getDetailsByUuid(_conn, pool.getUuid()); - Map tInfo = new HashMap(); - ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, d.totalSpace, d.freeSpace, tInfo); - return answer; - } catch (Exception e) { - logger.debug("ModifyStoragePoolCommand failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - protected Answer execute(CreateStoragePoolCommand cmd) { - return new Answer(cmd, true, "success"); - } - - protected PrimaryStorageDownloadAnswer execute(final PrimaryStorageDownloadCommand cmd) { - try { - URI uri = new URI(cmd.getUrl()); - String secondaryStoragePath = uri.getHost() + ":" + uri.getPath(); - Pair res = OvmStoragePool.downloadTemplate(_conn, cmd.getPoolUuid(), secondaryStoragePath); - return new PrimaryStorageDownloadAnswer(res.first(), res.second()); - } catch (Exception e) { - logger.debug("PrimaryStorageDownloadCommand failed", e); - return new PrimaryStorageDownloadAnswer(e.getMessage()); - } - } - - protected CreateAnswer execute(CreateCommand cmd) { - StorageFilerTO primaryStorage = cmd.getPool(); - DiskProfile disk = cmd.getDiskCharacteristics(); - - try { - OvmVolume.Details vol = null; - if (cmd.getTemplateUrl() != null) { - vol = OvmVolume.createFromTemplate(_conn, primaryStorage.getUuid(), cmd.getTemplateUrl()); - } else { - vol = OvmVolume.createDataDsik(_conn, primaryStorage.getUuid(), Long.toString(disk.getSize()), disk.getType() == Volume.Type.ROOT); - } - - VolumeTO volume = - new VolumeTO(cmd.getVolumeId(), disk.getType(), primaryStorage.getType(), primaryStorage.getUuid(), primaryStorage.getPath(), vol.name, vol.path, - vol.size, null); - return new CreateAnswer(cmd, volume); - } catch (Exception e) { - logger.debug("CreateCommand failed", e); - return new CreateAnswer(cmd, e.getMessage()); - } - } - - protected void applySpecToVm(OvmVm.Details vm, VirtualMachineTO spec) { - vm.name = spec.getName(); - vm.memory = spec.getMinRam(); - vm.cpuNum = spec.getCpus(); - vm.uuid = UuidUtils.nameUUIDFromBytes(spec.getName().getBytes()).toString(); - if (spec.getBootloader() == BootloaderType.CD) { - vm.bootDev = OvmVm.CD; - vm.type = OvmVm.HVM; - } else { - vm.bootDev = OvmVm.HDD; - String osType = OvmHelper.getOvmGuestType(spec.getOs()); - if (OvmHelper.ORACLE_LINUX.equals(osType)) { - vm.type = OvmVm.PV; - } else if (OvmHelper.WINDOWS.equals(osType) || OvmHelper.ORACLE_SOLARIS.equals(osType)) { - vm.type = OvmVm.HVM; - } else { - throw new CloudRuntimeException(spec.getOs() + " is not supported" + ",Oracle VM only supports Oracle Linux and Windows"); - } - } - } - - protected void createVbds(OvmVm.Details vm, VirtualMachineTO spec) throws URISyntaxException { - for (DiskTO volume : spec.getDisks()) { - if (volume.getType() == Volume.Type.ROOT) { - VolumeObjectTO vol = (VolumeObjectTO)volume.getData(); - OvmDisk.Details root = new OvmDisk.Details(); - root.path = vol.getPath(); - root.type = OvmDisk.WRITE; - root.isIso = false; - vm.rootDisk = root; - } else if (volume.getType() == Volume.Type.ISO) { - DataTO isoTO = volume.getData(); - if (isoTO.getPath() != null) { - TemplateObjectTO template = (TemplateObjectTO)isoTO; - DataStoreTO store = template.getDataStore(); - if (!(store instanceof NfsTO)) { - throw new CloudRuntimeException("unsupported protocol"); - } - NfsTO nfsStore = (NfsTO)store; - String isoPath = nfsStore.getUrl() + File.separator + template.getPath(); - OvmDisk.Details iso = new OvmDisk.Details(); - URI path = new URI(isoPath); - iso.path = path.getHost() + ":" + path.getPath(); - iso.type = OvmDisk.READ; - iso.isIso = true; - vm.disks.add(iso); - } - } else if (volume.getType() == Volume.Type.DATADISK) { - - OvmDisk.Details data = new OvmDisk.Details(); - data.path = volume.getData().getPath(); - data.type = OvmDisk.SHAREDWRITE; - data.isIso = false; - vm.disks.add(data); - } else { - throw new CloudRuntimeException("Unknown volume type: " + volume.getType()); - } - } - } - - private String createVlanBridge(String networkName, String vlanId) throws XmlRpcException { - OvmBridge.Details brdetails = OvmBridge.getDetails(_conn, networkName); - if (brdetails.attach.equalsIgnoreCase("null")) { - throw new CloudRuntimeException("Bridge " + networkName + " has no PIF"); - } - - OvmVlan.Details vdetails = new OvmVlan.Details(); - vdetails.pif = brdetails.attach; - vdetails.vid = Integer.parseInt(vlanId); - brdetails.name = "vlan" + vlanId; - brdetails.attach = "null"; - OvmBridge.createVlanBridge(_conn, brdetails, vdetails); - return brdetails.name; - } - - //TODO: complete all network support - protected String getNetwork(NicTO nic) throws XmlRpcException { - String vlanId = null; - String bridgeName = null; - if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { - vlanId = BroadcastDomainType.getValue(nic.getBroadcastUri()); - } - - if (nic.getType() == TrafficType.Guest) { - if (nic.getBroadcastType() == BroadcastDomainType.Vlan && !vlanId.equalsIgnoreCase("untagged")) { - bridgeName = createVlanBridge(_guestNetworkName, vlanId); - } else { - bridgeName = _guestNetworkName; - } - } else if (nic.getType() == TrafficType.Control) { - throw new CloudRuntimeException("local link network is not supported"); - } else if (nic.getType() == TrafficType.Public) { - throw new CloudRuntimeException("public network for system vm is not supported"); - } else if (nic.getType() == TrafficType.Management) { - bridgeName = _privateNetworkName; - } else { - throw new CloudRuntimeException("Unkonw network traffic type:" + nic.getType()); - } - - return bridgeName; - } - - protected OvmVif.Details createVif(NicTO nic) throws XmlRpcException { - OvmVif.Details vif = new OvmVif.Details(); - vif.mac = nic.getMac(); - vif.bridge = getNetwork(nic); - return vif; - } - - protected void createVifs(OvmVm.Details vm, VirtualMachineTO spec) throws CloudRuntimeException, XmlRpcException { - NicTO[] nics = spec.getNics(); - List vifs = new ArrayList(nics.length); - for (NicTO nic : nics) { - OvmVif.Details vif = createVif(nic); - vifs.add(nic.getDeviceId(), vif); - } - vm.vifs.addAll(vifs); - } - - protected void startVm(OvmVm.Details vm) throws XmlRpcException { - OvmVm.create(_conn, vm); - } - - private void cleanupNetwork(List vifs) throws XmlRpcException { - for (OvmVif.Details vif : vifs) { - if (vif.bridge.startsWith("vlan")) { - OvmBridge.deleteVlanBridge(_conn, vif.bridge); - } - } - } - - protected void cleanup(OvmVm.Details vm) { - try { - cleanupNetwork(vm.vifs); - } catch (XmlRpcException e) { - logger.debug("Clean up network for " + vm.name + " failed", e); - } - _vmNetworkStats.remove(vm.name); - } - - @Override - public synchronized StartAnswer execute(StartCommand cmd) { - VirtualMachineTO vmSpec = cmd.getVirtualMachine(); - String vmName = vmSpec.getName(); - OvmVm.Details vmDetails = null; - try { - vmDetails = new OvmVm.Details(); - applySpecToVm(vmDetails, vmSpec); - createVbds(vmDetails, vmSpec); - createVifs(vmDetails, vmSpec); - startVm(vmDetails); - - // Add security group rules - NicTO[] nics = vmSpec.getNics(); - for (NicTO nic : nics) { - if (nic.isSecurityGroupEnabled()) { - if (vmSpec.getType().equals(VirtualMachine.Type.User)) { - defaultNetworkRulesForUserVm(vmName, vmSpec.getId(), nic); - } - } - } - - return new StartAnswer(cmd); - } catch (Exception e) { - logger.debug("Start vm " + vmName + " failed", e); - cleanup(vmDetails); - return new StartAnswer(cmd, e.getMessage()); - } - } - - protected Answer execute(GetHostStatsCommand cmd) { - try { - Map res = OvmHost.getPerformanceStats(_conn, _publicNetworkName); - Double cpuUtil = Double.parseDouble(res.get("cpuUtil")); - Double rxBytes = Double.parseDouble(res.get("rxBytes")); - Double txBytes = Double.parseDouble(res.get("txBytes")); - Double totalMemory = Double.parseDouble(res.get("totalMemory")); - Double freeMemory = Double.parseDouble(res.get("freeMemory")); - HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil, rxBytes, txBytes, "host", totalMemory, freeMemory, 0, 0); - return new GetHostStatsAnswer(cmd, hostStats); - } catch (Exception e) { - logger.debug("Get host stats of " + cmd.getHostName() + " failed", e); - return new Answer(cmd, false, e.getMessage()); - } - - } - - @Override - public StopAnswer execute(StopCommand cmd) { - String vmName = cmd.getVmName(); - try { - OvmVm.Details vm = null; - try { - vm = OvmVm.getDetails(_conn, vmName); - } catch (XmlRpcException e) { - logger.debug("Unable to get details of vm: " + vmName + ", treating it as stopped", e); - return new StopAnswer(cmd, "success", true); - } - - deleteAllNetworkRulesForVm(vmName); - OvmVm.stop(_conn, vmName); - cleanup(vm); - return new StopAnswer(cmd, "success", true); - } catch (Exception e) { - logger.debug("Stop " + vmName + "failed", e); - return new StopAnswer(cmd, e.getMessage(), false); - } - } - - @Override - public RebootAnswer execute(RebootCommand cmd) { - String vmName = cmd.getVmName(); - - try { - Map res = OvmVm.reboot(_conn, vmName); - Integer vncPort = Integer.parseInt(res.get("vncPort")); - return new RebootAnswer(cmd, null, vncPort); - } catch (Exception e) { - logger.debug("Reboot " + vmName + " failed", e); - return new RebootAnswer(cmd, e.getMessage(), false); - } - } - - private PowerState toPowerState(String vmName, String s) { - PowerState state = s_powerStateMaps.get(s); - if (state == null) { - logger.debug("Unkown state " + s + " for " + vmName); - state = PowerState.PowerUnknown; - } - return state; - } - - protected HashMap getHostVmStateReport() throws XmlRpcException { - final HashMap vmStates = new HashMap(); - Map vms = OvmHost.getAllVms(_conn); - for (final Map.Entry entry : vms.entrySet()) { - PowerState state = toPowerState(entry.getKey(), entry.getValue()); - vmStates.put(entry.getKey(), new HostVmStateReportEntry(state, _conn.getIp())); - } - return vmStates; - } - - protected HashMap getAllVms() throws XmlRpcException { - final HashMap vmStates = new HashMap(); - Map vms = OvmHost.getAllVms(_conn); - for (final Map.Entry entry : vms.entrySet()) { - PowerState powerState = toPowerState(entry.getKey(), entry.getValue()); - vmStates.put(entry.getKey(), powerState); - } - return vmStates; - } - - - protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { - try { - OvmStoragePool.Details d = OvmStoragePool.getDetailsByUuid(_conn, cmd.getStorageId()); - return new GetStorageStatsAnswer(cmd, d.totalSpace, d.usedSpace); - } catch (Exception e) { - logger.debug("GetStorageStatsCommand on pool " + cmd.getStorageId() + " failed", e); - return new GetStorageStatsAnswer(cmd, e.getMessage()); - } - } - - private VmStatsEntry getVmStat(String vmName) throws XmlRpcException { - Map vmStat = OvmVm.getVmStats(_conn, vmName); - int nvcpus = Integer.parseInt(vmStat.get("cpuNum")); - float cpuUtil = Float.parseFloat(vmStat.get("cpuUtil")); - long rxBytes = Long.parseLong(vmStat.get("rxBytes")); - long txBytes = Long.parseLong(vmStat.get("txBytes")); - Pair oldNetworkStat = _vmNetworkStats.get(vmName); - - long rx = rxBytes; - long tx = txBytes; - if (oldNetworkStat != null) { - rx -= oldNetworkStat.first(); - tx -= oldNetworkStat.second(); - oldNetworkStat.set(rxBytes, txBytes); - } else { - oldNetworkStat = new Pair(rx, tx); - } - _vmNetworkStats.put(vmName, oldNetworkStat); - - VmStatsEntry e = new VmStatsEntry(); - e.setCPUUtilization(cpuUtil); - e.setNumCPUs(nvcpus); - e.setNetworkReadKBs(rx); - e.setNetworkWriteKBs(tx); - e.setEntityType("vm"); - return e; - } - - protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) { - List vmNames = cmd.getVmNames(); - HashMap vmStatsNameMap = new HashMap(); - for (String vmName : vmNames) { - try { - VmStatsEntry e = getVmStat(vmName); - vmStatsNameMap.put(vmName, e); - } catch (XmlRpcException e) { - logger.debug("Get vm stat for " + vmName + " failed", e); - continue; - } - } - return new GetVmStatsAnswer(cmd, vmStatsNameMap); - } - - public Answer execute(DestroyCommand cmd) { - try { - OvmVolume.destroy(_conn, cmd.getVolume().getPoolUuid(), cmd.getVolume().getPath()); - return new Answer(cmd, true, "Success"); - } catch (Exception e) { - logger.debug("Destroy volume " + cmd.getVolume().getName() + " failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - protected PrepareForMigrationAnswer execute(PrepareForMigrationCommand cmd) { - VirtualMachineTO vm = cmd.getVirtualMachine(); - if (logger.isDebugEnabled()) { - logger.debug("Preparing host for migrating " + vm); - } - - NicTO[] nics = vm.getNics(); - try { - for (NicTO nic : nics) { - getNetwork(nic); - } - - return new PrepareForMigrationAnswer(cmd); - } catch (Exception e) { - logger.warn("Catch Exception " + e.getClass().getName() + " prepare for migration failed due to " + e.toString(), e); - return new PrepareForMigrationAnswer(cmd, e); - } - } - - protected MigrateAnswer execute(final MigrateCommand cmd) { - final String vmName = cmd.getVmName(); - try { - OvmVm.Details vm = OvmVm.getDetails(_conn, vmName); - String destIp = cmd.getDestinationIp(); - OvmVm.migrate(_conn, vmName, destIp); - cleanup(vm); - return new MigrateAnswer(cmd, true, "migration succeeded", null); - } catch (Exception e) { - String msg = "Catch Exception " + e.getClass().getName() + ": Migration failed due to " + e.toString(); - logger.debug(msg, e); - return new MigrateAnswer(cmd, false, msg, null); - } - } - - protected CheckVirtualMachineAnswer execute(final CheckVirtualMachineCommand cmd) { - final String vmName = cmd.getVmName(); - try { - Map res = OvmVm.register(_conn, vmName); - Integer vncPort = Integer.parseInt(res.get("vncPort")); - HashMap states = getAllVms(); - PowerState vmPowerState = states.get(vmName); - if (vmPowerState == null) { - logger.warn("Check state of " + vmName + " return null in CheckVirtualMachineCommand"); - vmPowerState = PowerState.PowerOff; - } - - return new CheckVirtualMachineAnswer(cmd, vmPowerState, vncPort); - } catch (Exception e) { - logger.debug("Check migration for " + vmName + " failed", e); - return new CheckVirtualMachineAnswer(cmd, PowerState.PowerOff, null); - } - } - - protected MaintainAnswer execute(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - protected GetVncPortAnswer execute(GetVncPortCommand cmd) { - try { - Integer vncPort = OvmVm.getVncPort(_conn, cmd.getName()); - return new GetVncPortAnswer(cmd, _ip, vncPort); - } catch (Exception e) { - logger.debug("get vnc port for " + cmd.getName() + " failed", e); - return new GetVncPortAnswer(cmd, e.getMessage()); - } - } - - protected Answer execute(PingTestCommand cmd) { - try { - if (cmd.getComputingHostIp() != null) { - OvmHost.pingAnotherHost(_conn, cmd.getComputingHostIp()); - } else { - return new Answer(cmd, false, "why asks me to ping router???"); - } - - return new Answer(cmd, true, "success"); - } catch (Exception e) { - logger.debug("Ping " + cmd.getComputingHostIp() + " failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - protected FenceAnswer execute(FenceCommand cmd) { - try { - Boolean res = OvmHost.fence(_conn, cmd.getHostIp()); - return new FenceAnswer(cmd, res, res.toString()); - } catch (Exception e) { - logger.debug("fence " + cmd.getHostIp() + " failed", e); - return new FenceAnswer(cmd, false, e.getMessage()); - } - } - - protected Answer execute(AttachIsoCommand cmd) { - try { - URI iso = new URI(cmd.getIsoPath()); - String isoPath = iso.getHost() + ":" + iso.getPath(); - OvmVm.detachOrAttachIso(_conn, cmd.getVmName(), isoPath, cmd.isAttach()); - return new Answer(cmd); - } catch (Exception e) { - logger.debug("Attach or detach ISO " + cmd.getIsoPath() + " for " + cmd.getVmName() + " attach:" + cmd.isAttach() + " failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - private Answer execute(SecurityGroupRulesCmd cmd) { - boolean result = false; - try { - OvmVif.Details vif = getVifFromVm(cmd.getVmName(), null); - String vifDeviceName = vif.name; - String bridgeName = vif.bridge; - result = - addNetworkRules(cmd.getVmName(), Long.toString(cmd.getVmId()), cmd.getGuestIp(), cmd.getSignature(), String.valueOf(cmd.getSeqNum()), cmd.getGuestMac(), - cmd.stringifyRules(), vifDeviceName, bridgeName); - } catch (XmlRpcException e) { - logger.error(e); - result = false; - } - - if (!result) { - logger.warn("Failed to program network rules for vm " + cmd.getVmName()); - return new SecurityGroupRuleAnswer(cmd, false, "programming network rules failed"); - } else { - logger.info("Programmed network rules for vm " + cmd.getVmName() + " guestIp=" + cmd.getGuestIp() + ":ingress num rules=" + cmd.getIngressRuleSet().size() + - ":egress num rules=" + cmd.getEgressRuleSet().size()); - return new SecurityGroupRuleAnswer(cmd); - } - } - - private Answer execute(CleanupNetworkRulesCmd cmd) { - boolean result = false; - try { - result = cleanupNetworkRules(); - } catch (XmlRpcException e) { - logger.error(e); - result = false; - } - - if (result) { - return new Answer(cmd); - } else { - return new Answer(cmd, result, "Failed to cleanup network rules."); - } - } - - protected boolean defaultNetworkRulesForUserVm(String vmName, Long vmId, NicTO nic) throws XmlRpcException { - if (!_canBridgeFirewall) { - return false; - } - - OvmVif.Details vif = getVifFromVm(vmName, nic.getDeviceId()); - String ipAddress = nic.getIp(); - String macAddress = vif.mac; - String vifName = vif.name; - String bridgeName = vif.bridge; - - return OvmSecurityGroup.defaultNetworkRulesForUserVm(_conn, vmName, String.valueOf(vmId), ipAddress, macAddress, vifName, bridgeName); - } - - protected boolean deleteAllNetworkRulesForVm(String vmName) throws XmlRpcException { - if (!_canBridgeFirewall) { - return false; - } - - String vif = getVifFromVm(vmName, null).name; - return OvmSecurityGroup.deleteAllNetworkRulesForVm(_conn, vmName, vif); - } - - protected boolean addNetworkRules(String vmName, String vmId, String guestIp, String signature, String seqno, String vifMacAddress, String rules, - String vifDeviceName, String bridgeName) throws XmlRpcException { - if (!_canBridgeFirewall) { - return false; - } - - String newRules = rules.replace(" ", ";"); - return OvmSecurityGroup.addNetworkRules(_conn, vmName, vmId, guestIp, signature, seqno, vifMacAddress, newRules, vifDeviceName, bridgeName); - } - - protected boolean cleanupNetworkRules() throws XmlRpcException { - if (!_canBridgeFirewall) { - return false; - } - - return OvmSecurityGroup.cleanupNetworkRules(_conn); - } - - protected boolean canBridgeFirewall() throws XmlRpcException { - return OvmSecurityGroup.canBridgeFirewall(_conn); - } - - protected OvmVif.Details getVifFromVm(String vmName, Integer deviceId) throws XmlRpcException { - List vifs = null; - - try { - vifs = getInterfaces(vmName); - } catch (XmlRpcException e) { - logger.error("Failed to get VIFs for VM " + vmName, e); - throw e; - } - - if (deviceId != null && vifs.size() > deviceId) { - return vifs.get(deviceId); - } else if (deviceId == null && vifs.size() > 0) { - return vifs.get(0); - } else { - return null; - } - } - - protected List getInterfaces(String vmName) throws XmlRpcException { - OvmVm.Details vmDetails = OvmVm.getDetails(_conn, vmName); - return vmDetails.vifs; - } - - protected Answer execute(PrepareOCFS2NodesCommand cmd) { - List> nodes = cmd.getNodes(); - StringBuffer params = new StringBuffer(); - for (Ternary node : nodes) { - String param = String.format("%1$s:%2$s:%3$s", node.first(), node.second(), node.third()); - params.append(param); - params.append(";"); - } - - try { - OvmStoragePool.prepareOCFS2Nodes(_conn, cmd.getClusterName(), params.toString()); - return new Answer(cmd, true, "Success"); - } catch (XmlRpcException e) { - logger.debug("OCFS2 prepare nodes failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromVolumeCommand cmd) { - String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String volumePath = cmd.getVolumePath(); - Long accountId = cmd.getAccountId(); - Long templateId = cmd.getTemplateId(); - int wait = cmd.getWait(); - if (wait == 0) { - /* Defaut timeout 2 hours */ - wait = 7200; - } - - try { - URI uri; - uri = new URI(secondaryStorageUrl); - String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); - String installPath = "template/tmpl/" + accountId + "/" + templateId; - Map res = OvmStoragePool.createTemplateFromVolume(_conn, secondaryStorageMountPath, installPath, volumePath, wait); - return new CreatePrivateTemplateAnswer(cmd, true, null, res.get("installPath"), Long.parseLong(res.get("virtualSize")), Long.parseLong(res.get("physicalSize")), - res.get("templateFileName"), ImageFormat.RAW); - } catch (Exception e) { - logger.debug("Create template failed", e); - return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); - } - } - - protected CopyVolumeAnswer execute(CopyVolumeCommand cmd) { - String volumePath = cmd.getVolumePath(); - String secondaryStorageURL = cmd.getSecondaryStorageURL(); - int wait = cmd.getWait(); - if (wait == 0) { - wait = 7200; - } - - try { - URI uri = new URI(secondaryStorageURL); - String secStorageMountPath = uri.getHost() + ":" + uri.getPath(); - String volumeFolderOnSecStorage = "volumes/" + String.valueOf(cmd.getVolumeId()); - String storagePoolUuid = cmd.getPool().getUuid(); - Boolean toSec = cmd.toSecondaryStorage(); - String res = OvmStoragePool.copyVolume(_conn, secStorageMountPath, volumeFolderOnSecStorage, volumePath, storagePoolUuid, toSec, wait); - return new CopyVolumeAnswer(cmd, true, null, null, res); - } catch (Exception e) { - logger.debug("Copy volume failed", e); - return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null); - } - } - - protected Answer execute(DeleteStoragePoolCommand cmd) { - try { - OvmStoragePool.delete(_conn, cmd.getPool().getUuid()); - } catch (Exception e) { - logger.debug("Delete storage pool on host " + _ip + " failed, however, we leave to user for cleanup and tell management server it succeeded", e); - } - - return new Answer(cmd); - } - - protected CheckNetworkAnswer execute(CheckNetworkCommand cmd) { - if (logger.isDebugEnabled()) { - logger.debug("Checking if network name setup is done on the resource"); - } - - List infoList = cmd.getPhysicalNetworkInfoList(); - - boolean errorout = false; - String msg = ""; - for (PhysicalNetworkSetupInfo info : infoList) { - if (!isNetworkSetupByName(info.getGuestNetworkName())) { - msg = "For Physical Network id:" + info.getPhysicalNetworkId() + ", Guest Network is not configured on the backend by name " + info.getGuestNetworkName(); - errorout = true; - break; - } - if (!isNetworkSetupByName(info.getPrivateNetworkName())) { - msg = - "For Physical Network id:" + info.getPhysicalNetworkId() + ", Private Network is not configured on the backend by name " + - info.getPrivateNetworkName(); - errorout = true; - break; - } - if (!isNetworkSetupByName(info.getPublicNetworkName())) { - msg = - "For Physical Network id:" + info.getPhysicalNetworkId() + ", Public Network is not configured on the backend by name " + info.getPublicNetworkName(); - errorout = true; - break; - } - } - - if (errorout) { - logger.error(msg); - return new CheckNetworkAnswer(cmd, false, msg); - } else { - return new CheckNetworkAnswer(cmd, true, "Network Setup check by names is done"); - } - } - - private boolean isNetworkSetupByName(String nameTag) { - if (nameTag != null) { - if (logger.isDebugEnabled()) { - logger.debug("Looking for network setup by name " + nameTag); - } - return _bridges.contains(nameTag); - } - return true; - } - - @Override - public Answer executeRequest(Command cmd) { - Class clazz = cmd.getClass(); - if (clazz == ReadyCommand.class) { - return execute((ReadyCommand)cmd); - } else if (clazz == CreateStoragePoolCommand.class) { - return execute((CreateStoragePoolCommand)cmd); - } else if (clazz == ModifyStoragePoolCommand.class) { - return execute((ModifyStoragePoolCommand)cmd); - } else if (clazz == PrimaryStorageDownloadCommand.class) { - return execute((PrimaryStorageDownloadCommand)cmd); - } else if (clazz == CreateCommand.class) { - return execute((CreateCommand)cmd); - } else if (clazz == GetHostStatsCommand.class) { - return execute((GetHostStatsCommand)cmd); - } else if (clazz == StopCommand.class) { - return execute((StopCommand)cmd); - } else if (clazz == RebootCommand.class) { - return execute((RebootCommand)cmd); - } else if (clazz == GetStorageStatsCommand.class) { - return execute((GetStorageStatsCommand)cmd); - } else if (clazz == GetVmStatsCommand.class) { - return execute((GetVmStatsCommand)cmd); - } else if (clazz == DestroyCommand.class) { - return execute((DestroyCommand)cmd); - } else if (clazz == PrepareForMigrationCommand.class) { - return execute((PrepareForMigrationCommand)cmd); - } else if (clazz == MigrateCommand.class) { - return execute((MigrateCommand)cmd); - } else if (clazz == CheckVirtualMachineCommand.class) { - return execute((CheckVirtualMachineCommand)cmd); - } else if (clazz == MaintainCommand.class) { - return execute((MaintainCommand)cmd); - } else if (clazz == StartCommand.class) { - return execute((StartCommand)cmd); - } else if (clazz == GetVncPortCommand.class) { - return execute((GetVncPortCommand)cmd); - } else if (clazz == PingTestCommand.class) { - return execute((PingTestCommand)cmd); - } else if (clazz == FenceCommand.class) { - return execute((FenceCommand)cmd); - } else if (clazz == AttachIsoCommand.class) { - return execute((AttachIsoCommand)cmd); - } else if (clazz == SecurityGroupRulesCmd.class) { - return execute((SecurityGroupRulesCmd)cmd); - } else if (clazz == CleanupNetworkRulesCmd.class) { - return execute((CleanupNetworkRulesCmd)cmd); - } else if (clazz == PrepareOCFS2NodesCommand.class) { - return execute((PrepareOCFS2NodesCommand)cmd); - } else if (clazz == CreatePrivateTemplateFromVolumeCommand.class) { - return execute((CreatePrivateTemplateFromVolumeCommand)cmd); - } else if (clazz == CopyVolumeCommand.class) { - return execute((CopyVolumeCommand)cmd); - } else if (clazz == DeleteStoragePoolCommand.class) { - return execute((DeleteStoragePoolCommand)cmd); - } else if (clazz == CheckNetworkCommand.class) { - return execute((CheckNetworkCommand)cmd); - } else { - return Answer.createUnsupportedCommandAnswer(cmd); - } - } - - @Override - public void disconnected() { - // TODO Auto-generated method stub - - } - - @Override - public IAgentControl getAgentControl() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - // TODO Auto-generated method stub - - } - - @Override - public void setName(String name) { - // TODO Auto-generated method stub - - } - - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - - } - - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Coder.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Coder.java deleted file mode 100644 index 9bb42ac388e7..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Coder.java +++ /dev/null @@ -1,84 +0,0 @@ -// 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.ovm.object; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.reflect.TypeToken; - -public class Coder { - private static Gson s_gson; - private static Gson s_mapGson; - - public static Object[] s_emptyParams = new Object[0]; - - private static class MapDecoder implements JsonDeserializer> { - @Override - public Map deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { - if (!arg0.isJsonObject()) { - throw new JsonParseException(arg0.toString() + " is not Json Object, cannot convert to map"); - } - JsonObject objs = arg0.getAsJsonObject(); - Map map = new HashMap(); - for (Entry e : objs.entrySet()) { - if (!e.getValue().isJsonPrimitive()) { - throw new JsonParseException(e.getValue().toString() + " is not a Json primitive," + arg0 + " can not convert to map"); - } - map.put(e.getKey(), e.getValue().getAsString()); - } - return map; - } - - } - - static { - GsonBuilder _builder = new GsonBuilder(); - _builder.registerTypeAdapter(Map.class, new MapDecoder()); - s_mapGson = _builder.create(); - s_gson = new Gson(); - } - - public static String toJson(Object obj) { - return s_gson.toJson(obj); - } - - public static T fromJson(String str, Class clz) { - return s_gson.fromJson(str, clz); - } - - @SuppressWarnings("unchecked") - public static Map mapFromJson(String str) { - return s_mapGson.fromJson(str, Map.class); - } - - public static List listFromJson(String str) { - Type listType = new TypeToken>() { - }.getType(); - return s_gson.fromJson(str, listType); - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Connection.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Connection.java deleted file mode 100644 index 0c6a5ebd943c..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Connection.java +++ /dev/null @@ -1,140 +0,0 @@ -// 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.ovm.object; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.TimeZone; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.apache.xmlrpc.XmlRpcException; -import org.apache.xmlrpc.client.TimingOutCallback; -import org.apache.xmlrpc.client.XmlRpcClient; -import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; - -import com.cloud.utils.exception.CloudRuntimeException; - -public class Connection { - protected Logger logger = LogManager.getLogger(getClass()); - private XmlRpcClientConfigImpl _config = new XmlRpcClientConfigImpl(); - XmlRpcClient _client; - String _username; - String _password; - String _ip; - Integer _port = 8899; - Boolean _isSsl = false; - - private XmlRpcClient getXmlClient() { - XmlRpcClient client = new XmlRpcClient(); - - URL url; - try { - url = new URL("http://" + _ip + ":" + _port.toString()); - _config.setTimeZone(TimeZone.getTimeZone("UTC")); - _config.setServerURL(url); - _config.setReplyTimeout(0); // disable, we use asyncexecute to control timeout - _config.setConnectionTimeout(6000); - _config.setBasicUserName(_username); - _config.setBasicPassword(_password); - client.setConfig(_config); - } catch (MalformedURLException e) { - throw new CloudRuntimeException(e.getMessage()); - } - - return client; - } - - public Connection(String ip, Integer port, String username, String password) { - _ip = ip; - _port = port; - _username = username; - _password = password; - _client = getXmlClient(); - } - - public Connection(String ip, String username, String password) { - _ip = ip; - _username = username; - _password = password; - _client = getXmlClient(); - } - - public Object call(String method, Object[] params) throws XmlRpcException { - /* default timeout is 10 mins */ - return callTimeoutInSec(method, params, 600); - } - - public Object call(String method, Object[] params, boolean debug) throws XmlRpcException { - /* default timeout is 10 mins */ - return callTimeoutInSec(method, params, 600, debug); - } - - public Object callTimeoutInSec(String method, Object[] params, int timeout, boolean debug) throws XmlRpcException { - TimingOutCallback callback = new TimingOutCallback(timeout * 1000); - Object[] mParams = new Object[params.length + 1]; - mParams[0] = method; - for (int i = 0; i < params.length; i++) { - mParams[i + 1] = params[i]; - } - - if (debug) { - /* - * some parameters including user password should not be printed in log - */ - logger.debug("Call Ovm agent: " + Coder.toJson(mParams)); - } - - long startTime = System.currentTimeMillis(); - _client.executeAsync("OvmDispatch", mParams, callback); - try { - return callback.waitForResponse(); - } catch (TimingOutCallback.TimeoutException to) { - throw to; - } catch (Throwable e) { - throw new XmlRpcException(-2, e.getMessage()); - } finally { - long endTime = System.currentTimeMillis(); - long during = (endTime - startTime) / 1000; // in secs - logger.debug("Ovm call " + method + " finished in " + String.valueOf(during) + " secs"); - } - } - - public Object callTimeoutInSec(String method, Object[] params, int timeout) throws XmlRpcException { - return callTimeoutInSec(method, params, timeout, true); - } - - public String getIp() { - return _ip; - } - - public Integer getPort() { - return _port; - } - - public String getUserName() { - return _username; - } - - public String getPassword() { - return _password; - } - - public Boolean getIsSsl() { - return _isSsl; - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmBridge.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmBridge.java deleted file mode 100644 index 6d2867ea46e9..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmBridge.java +++ /dev/null @@ -1,70 +0,0 @@ -// 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.ovm.object; - -import java.util.List; - -import org.apache.xmlrpc.XmlRpcException; - -public class OvmBridge extends OvmObject { - public static class Details { - public String name; - public String attach; - public List interfaces; - - public String toJson() { - return Coder.toJson(this); - } - } - - public static void create(Connection c, Details d) throws XmlRpcException { - Object[] params = {d.toJson()}; - c.call("OvmNetwork.createBridge", params); - } - - public static void delete(Connection c, String name) throws XmlRpcException { - Object[] params = {name}; - c.call("OvmNetwork.deleteBridge", params); - } - - public static List getAllBridges(Connection c) throws XmlRpcException { - String res = (String)c.call("OvmNetwork.getAllBridges", Coder.s_emptyParams); - return Coder.listFromJson(res); - } - - public static String getBridgeByIp(Connection c, String ip) throws XmlRpcException { - Object[] params = {ip}; - String res = (String)c.call("OvmNetwork.getBridgeByIp", params); - return Coder.mapFromJson(res).get("bridge"); - } - - public static void createVlanBridge(Connection c, OvmBridge.Details bDetails, OvmVlan.Details vDetails) throws XmlRpcException { - Object[] params = {bDetails.toJson(), vDetails.toJson()}; - c.call("OvmNetwork.createVlanBridge", params); - } - - public static void deleteVlanBridge(Connection c, String name) throws XmlRpcException { - Object[] params = {name}; - c.call("OvmNetwork.deleteVlanBridge", params); - } - - public static Details getDetails(Connection c, String name) throws XmlRpcException { - Object[] params = {name}; - String res = (String)c.call("OvmNetwork.getBridgeDetails", params); - return Coder.fromJson(res, Details.class); - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmDisk.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmDisk.java deleted file mode 100644 index 67eabc2403a6..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmDisk.java +++ /dev/null @@ -1,30 +0,0 @@ -// 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.ovm.object; - -public class OvmDisk extends OvmObject { - public static final String WRITE = "w"; - public static final String READ = "r"; - public static final String SHAREDWRITE = "w!"; - public static final String SHAREDREAD = "r!"; - - public static class Details { - public String type; - public String path; - public Boolean isIso; - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmHost.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmHost.java deleted file mode 100644 index 664fea3de791..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmHost.java +++ /dev/null @@ -1,92 +0,0 @@ -// 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.ovm.object; - -import java.util.Map; - -import org.apache.xmlrpc.XmlRpcException; - -public class OvmHost extends OvmObject { - public static final String SITE = "site"; - public static final String UTILITY = "utility"; - public static final String XEN = "xen"; - - public static class Details { - public String primaryIp; - public Integer cpuNum; - public Integer cpuSpeed; - public Long totalMemory; - public Long freeMemory; - public Long dom0Memory; - public String agentVersion; - public String name; - public String dom0KernelVersion; - public String hypervisorVersion; - - public String toJson() { - return Coder.toJson(this); - } - } - - public static void registerAsPrimary(Connection c) throws XmlRpcException { - Object[] params = {c.getIp(), c.getUserName(), c.getPassword(), c.getPort(), c.getIsSsl()}; - c.call("OvmHost.registerAsPrimary", params, false); - } - - public static void registerAsVmServer(Connection c) throws XmlRpcException { - Object[] params = {c.getIp(), c.getUserName(), c.getPassword(), c.getPort(), c.getIsSsl()}; - c.call("OvmHost.registerAsVmServer", params); - } - - public static Details getDetails(Connection c) throws XmlRpcException { - String res = (String)c.call("OvmHost.getDetails", Coder.s_emptyParams); - return Coder.fromJson(res, OvmHost.Details.class); - } - - public static void ping(Connection c) throws XmlRpcException { - Object[] params = {c.getIp()}; - c.call("OvmHost.ping", params); - } - - public static Map getPerformanceStats(Connection c, String bridge) throws XmlRpcException { - Object[] params = {bridge}; - String res = (String)c.call("OvmHost.getPerformanceStats", params); - return Coder.mapFromJson(res); - } - - public static Map getAllVms(Connection c) throws XmlRpcException { - String res = (String)c.call("OvmHost.getAllVms", Coder.s_emptyParams); - return Coder.mapFromJson(res); - } - - public static void setupHeartBeat(Connection c, String poolUuid, String ip) throws XmlRpcException { - Object[] params = {poolUuid, ip}; - c.call("OvmHost.setupHeartBeat", params); - } - - public static Boolean fence(Connection c, String ip) throws XmlRpcException { - Object[] params = {ip}; - String res = (String)c.call("OvmHost.fence", params); - Map result = Coder.mapFromJson(res); - return Boolean.parseBoolean(result.get("isLive")); - } - - public static void pingAnotherHost(Connection c, String ip) throws XmlRpcException { - Object[] params = {ip}; - c.call("OvmHost.pingAnotherHost", params); - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmObject.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmObject.java deleted file mode 100644 index eeea491c9f61..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmObject.java +++ /dev/null @@ -1,20 +0,0 @@ -// 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.ovm.object; - -public class OvmObject { -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmSecurityGroup.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmSecurityGroup.java deleted file mode 100644 index 8a9f19a7ce70..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmSecurityGroup.java +++ /dev/null @@ -1,56 +0,0 @@ -// 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.ovm.object; - -import org.apache.xmlrpc.XmlRpcException; - -public class OvmSecurityGroup extends OvmObject { - - // canBridgeFirewall - // cleanupRules - // defaultNetworkRulesUserVm - // addNetworkRules - // deleteAllNetworkRulesForVm - - public static boolean canBridgeFirewall(Connection c) throws XmlRpcException { - Object[] params = {}; - return (Boolean)c.call("OvmSecurityGroup.can_bridge_firewall", params); - } - - public static boolean cleanupNetworkRules(Connection c) throws XmlRpcException { - Object[] params = {}; - return (Boolean)c.call("OvmSecurityGroup.cleanup_rules", params); - } - - public static boolean defaultNetworkRulesForUserVm(Connection c, String vmName, String vmId, String ipAddress, String macAddress, String vifName, String bridgeName) - throws XmlRpcException { - Object[] params = {vmName, vmId, ipAddress, macAddress, vifName, bridgeName}; - return (Boolean)c.call("OvmSecurityGroup.default_network_rules_user_vm", params); - } - - public static boolean addNetworkRules(Connection c, String vmName, String vmId, String guestIp, String signature, String seqno, String vifMacAddress, - String newRules, String vifDeviceName, String bridgeName) throws XmlRpcException { - Object[] params = {vmName, vmId, guestIp, signature, seqno, vifMacAddress, newRules, vifDeviceName, bridgeName}; - return (Boolean)c.call("OvmSecurityGroup.add_network_rules", params); - } - - public static boolean deleteAllNetworkRulesForVm(Connection c, String vmName, String vif) throws XmlRpcException { - Object[] params = {vmName, vif}; - return (Boolean)c.call("OvmSecurityGroup.delete_all_network_rules_for_vm", params); - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmStoragePool.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmStoragePool.java deleted file mode 100644 index db9fb2554630..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmStoragePool.java +++ /dev/null @@ -1,107 +0,0 @@ -// 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.ovm.object; - -import java.util.Map; - -import org.apache.xmlrpc.XmlRpcException; - -import com.cloud.utils.Pair; - -public class OvmStoragePool extends OvmObject { - public static final String NFS = "OVSSPNFS"; - public static final String OCFS2 = "OVSSPOCFS2"; - public static final String PARTITION = "OVSSPPartition"; - - public static class Details { - public String uuid; - public String type; - public String path; - public String mountPoint; - public Long totalSpace; - public Long freeSpace; - public Long usedSpace; - - public String toJson() { - return Coder.toJson(this); - } - } - - /** - * @param c: connection - * @param d: includes three fields {uuid, type, path} - * @throws XmlRpcException - */ - public static void create(Connection c, Details d) throws XmlRpcException { - Object[] params = {d.toJson()}; - c.callTimeoutInSec("OvmStoragePool.create", params, 3600); - } - - /** - * - * @param c: connection - * @param uuid: uuid of primary storage - * @return: Details with full fields - * @throws XmlRpcException - */ - public static Details getDetailsByUuid(Connection c, String uuid) throws XmlRpcException { - Object[] params = {uuid}; - String res = (String)c.call("OvmStoragePool.getDetailsByUuid", params); - return Coder.fromJson(res, Details.class); - } - - /** - * - * @param c: Connection - * @param uuid: Pool uuid - * @param from: secondary storage download path - * @return: - * @throws XmlRpcException - */ - public static Pair downloadTemplate(Connection c, String uuid, String from) throws XmlRpcException { - Object[] params = {uuid, from}; - String res = (String)c.callTimeoutInSec("OvmStoragePool.downloadTemplate", params, 3600); - Map pair = Coder.mapFromJson(res); - return new Pair((String)pair.get("installPath"), Long.parseLong((String)pair.get("templateSize"))); - } - - public static void prepareOCFS2Nodes(Connection c, String clusterName, String nodes) throws XmlRpcException { - Object[] params = {clusterName, nodes}; - c.call("OvmStoragePool.prepareOCFS2Nodes", params); - } - - public static Map createTemplateFromVolume(Connection c, String secStorageMountPath, String installPath, String volumePath, int timeout) - throws XmlRpcException { - Object[] params = {secStorageMountPath, installPath, volumePath}; - String res = (String)c.callTimeoutInSec("OvmStoragePool.createTemplateFromVolume", params, timeout); - Map info = Coder.mapFromJson(res); - return info; - } - - public static String copyVolume(Connection c, String secStorageMountPath, String volumeFolderOnSecStorage, String volumePath, String storagePoolUuid, Boolean toSec, - int timeout) throws XmlRpcException { - Object[] params = {secStorageMountPath, volumeFolderOnSecStorage, volumePath, storagePoolUuid, toSec}; - String res = (String)c.callTimeoutInSec("OvmStoragePool.copyVolume", params, timeout); - Map info = Coder.mapFromJson(res); - return (String)info.get("installPath"); - } - - public static void delete(Connection c, String uuid) throws XmlRpcException { - Object[] params = {uuid}; - c.call("OvmStoragePool.delete", params); - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVif.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVif.java deleted file mode 100644 index 658dcc5926b6..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVif.java +++ /dev/null @@ -1,30 +0,0 @@ -// 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.ovm.object; - -public class OvmVif extends OvmObject { - public static final String NETFRONT = "netfront"; - public static final String IOEMU = "ioemu"; - - public static class Details { - public String name; - public String mac; - public String bridge; - public String type; - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVlan.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVlan.java deleted file mode 100644 index 915bcad3fea5..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVlan.java +++ /dev/null @@ -1,43 +0,0 @@ -// 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.ovm.object; - -import org.apache.xmlrpc.XmlRpcException; - -public class OvmVlan extends OvmObject { - public static class Details { - public String name; - public int vid; - public String pif; - - public String toJson() { - return Coder.toJson(this); - } - } - - public static String create(Connection c, Details d) throws XmlRpcException { - Object[] params = {d.toJson()}; - String res = (String)c.call("OvmNetwork.createVlan", params); - Details ret = Coder.fromJson(res, Details.class); - return ret.name; - } - - public static void delete(Connection c, String name) throws XmlRpcException { - Object[] params = {name}; - c.call("OvmNetwork.deleteVlan", params); - } -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVm.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVm.java deleted file mode 100644 index 7897427c5f13..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVm.java +++ /dev/null @@ -1,110 +0,0 @@ -// 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.ovm.object; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.xmlrpc.XmlRpcException; - -public class OvmVm extends OvmObject { - public static final String CD = "CD"; - public static final String HDD = "HDD"; - public static final String HVM = "HVM"; - public static final String PV = "PV"; - public static final String FROMCONFIGFILE = "FROMCONFIGFILE"; - - public static class Details { - public int cpuNum; - public long memory; - public OvmDisk.Details rootDisk; - public List disks; - public List vifs; - public String name; - public String uuid; - public String powerState; - public String bootDev; - public String type; - - public Details() { - disks = new ArrayList(); - vifs = new ArrayList(); - } - - public String toJson() { - return Coder.toJson(this); - } - } - - public OvmVm() { - } - - /*********** XML RPC Call **************/ - public static void create(Connection c, Details d) throws XmlRpcException { - Object[] params = {d.toJson()}; - c.call("OvmVm.create", params); - } - - public static Map reboot(Connection c, String vmName) throws XmlRpcException { - Object[] params = {vmName}; - String res = (String)c.call("OvmVm.reboot", params); - return Coder.mapFromJson(res); - } - - public static void stop(Connection c, String vmName) throws XmlRpcException { - Object[] params = {vmName}; - /* Agent will destroy vm if vm shutdowns failed due to timeout after 10 mins, so we set timeout to 20 mins here*/ - c.callTimeoutInSec("OvmVm.stop", params, 1200); - } - - public static Details getDetails(Connection c, String vmName) throws XmlRpcException { - Object[] params = {vmName}; - String res = (String)c.call("OvmVm.getDetails", params); - return Coder.fromJson(res, OvmVm.Details.class); - } - - public static Map getVmStats(Connection c, String vmName) throws XmlRpcException { - Object[] params = {vmName}; - String res = (String)c.call("OvmVm.getVmStats", params); - return Coder.mapFromJson(res); - } - - public static void migrate(Connection c, String vmName, String dest) throws XmlRpcException { - Object[] params = {vmName, dest}; - c.call("OvmVm.migrate", params); - } - - public static Map register(Connection c, String vmName) throws XmlRpcException { - Object[] params = {vmName}; - String res = (String)c.call("OvmVm.register", params); - return Coder.mapFromJson(res); - } - - public static Integer getVncPort(Connection c, String vmName) throws XmlRpcException { - Object[] params = {vmName}; - String res = (String)c.call("OvmVm.getVncPort", params); - Map result = Coder.mapFromJson(res); - return Integer.parseInt(result.get("vncPort")); - } - - public static void detachOrAttachIso(Connection c, String vmName, String iso, Boolean isAttach) throws XmlRpcException { - Object[] params = {vmName, iso, isAttach}; - c.call("OvmVm.detachOrAttachIso", params); - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVolume.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVolume.java deleted file mode 100644 index 5a665821dfe0..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/OvmVolume.java +++ /dev/null @@ -1,53 +0,0 @@ -// 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.ovm.object; - -import org.apache.xmlrpc.XmlRpcException; - -public class OvmVolume extends OvmObject { - public static class Details { - public String name; - public String uuid; - public String poolUuid; - public Long size; - public String path; - - public String toJson() { - return Coder.toJson(this); - } - } - - public static Details createDataDsik(Connection c, String poolUuid, String size, Boolean isRoot) throws XmlRpcException { - Object[] params = {poolUuid, size, isRoot}; - String res = (String)c.call("OvmVolume.createDataDisk", params); - Details result = Coder.fromJson(res, Details.class); - return result; - } - - public static Details createFromTemplate(Connection c, String poolUuid, String templateUrl) throws XmlRpcException { - Object[] params = {poolUuid, templateUrl}; - String res = (String)c.callTimeoutInSec("OvmVolume.createFromTemplate", params, 3600 * 3); - Details result = Coder.fromJson(res, Details.class); - return result; - } - - public static void destroy(Connection c, String poolUuid, String path) throws XmlRpcException { - Object[] params = {poolUuid, path}; - c.call("OvmVolume.destroy", params); - } - -} diff --git a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Test.java b/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Test.java deleted file mode 100644 index 32960a9616c6..000000000000 --- a/plugins/hypervisors/ovm/src/main/java/com/cloud/ovm/object/Test.java +++ /dev/null @@ -1,122 +0,0 @@ -// 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.ovm.object; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class Test { - public static void main(final String[] args) { - try { - final OvmVm.Details vm = new OvmVm.Details(); - vm.cpuNum = 1; - vm.memory = 512; - vm.name = "Test"; - vm.uuid = "This-is-a-test"; - final OvmDisk.Details rootDisk = new OvmDisk.Details(); - rootDisk.path = "/root/root.raw"; - rootDisk.type = OvmDisk.WRITE; - vm.rootDisk = rootDisk; - final OvmDisk.Details dataDisk = new OvmDisk.Details(); - dataDisk.path = "/tmp/data.raw"; - dataDisk.type = OvmDisk.SHAREDWRITE; - vm.disks.add(dataDisk); - vm.disks.add(dataDisk); - vm.disks.add(dataDisk); - vm.disks.add(dataDisk); - vm.disks.add(dataDisk); - final OvmVif.Details vif = new OvmVif.Details(); - vif.mac = "00:ff:ff:ff:ff:ee"; - vif.bridge = "xenbr0"; - vif.type = OvmVif.NETFRONT; - vm.vifs.add(vif); - vm.vifs.add(vif); - vm.vifs.add(vif); - vm.vifs.add(vif); - vm.vifs.add(vif); - final Connection c = new Connection("192.168.189.12", "oracle", "password"); - - String cmd = null; - System.out.println(args.length); - if (args.length >= 1) { - cmd = args[0]; - final OvmVm.Details d = new OvmVm.Details(); - d.cpuNum = 1; - d.memory = 512 * 1024 * 1024; - d.name = "MyTest"; - d.uuid = "1-2-3-4-5"; - final OvmDisk.Details r = new OvmDisk.Details(); - r.path = "/var/ovs/mount/60D0985974CA425AAF5D01A1F161CC8B/running_pool/36_systemvm/System.img"; - r.type = OvmDisk.WRITE; - d.rootDisk = r; - final OvmVif.Details v = new OvmVif.Details(); - v.mac = "00:16:3E:5C:B1:D1"; - v.bridge = "xenbr0"; - v.type = OvmVif.NETFRONT; - d.vifs.add(v); - System.out.println(d.toJson()); - - if (cmd.equalsIgnoreCase("create")) { - OvmVm.create(c, d); - } else if (cmd.equalsIgnoreCase("reboot")) { - final Map res = OvmVm.reboot(c, "MyTest"); - System.out.println(res.get("vncPort")); - } else if (cmd.equalsIgnoreCase("stop")) { - OvmVm.stop(c, "MyTest"); - } else if (cmd.equalsIgnoreCase("details")) { - final OvmVm.Details ddd = OvmVm.getDetails(c, "MyTest"); - System.out.println(ddd.vifs.size()); - System.out.println(ddd.rootDisk.path); - System.out.println(ddd.powerState); - } else if (cmd.equalsIgnoreCase("all")) { - System.out.println(OvmHost.getAllVms(c)); - } else if (cmd.equalsIgnoreCase("createBridge")) { - final OvmBridge.Details bd = new OvmBridge.Details(); - bd.name = "xenbr10"; - bd.attach = args[1]; - OvmBridge.create(c, bd); - } else if (cmd.equalsIgnoreCase("createVlan")) { - final OvmVlan.Details vd = new OvmVlan.Details(); - vd.pif = "eth0"; - vd.vid = 1000; - final String vname = OvmVlan.create(c, vd); - System.out.println(vname); - } else if (cmd.equalsIgnoreCase("delVlan")) { - OvmVlan.delete(c, args[1]); - } else if (cmd.equalsIgnoreCase("delBr")) { - OvmBridge.delete(c, args[1]); - } else if (cmd.equalsIgnoreCase("getBrs")) { - final List brs = OvmBridge.getAllBridges(c); - System.out.println(brs); - } else if (cmd.equalsIgnoreCase("getBrDetails")) { - final OvmBridge.Details brd = OvmBridge.getDetails(c, args[1]); - System.out.println(brd.interfaces); - } - - } - - final List l = new ArrayList(); - l.add("4b4d8951-f0b6-36c5-b4f3-a82ff2611c65"); - System.out.println(Coder.toJson(l)); - - } catch (final Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } -} diff --git a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/module.properties b/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/module.properties deleted file mode 100644 index 165a1c787992..000000000000 --- a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=ovm-compute -parent=compute diff --git a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/spring-ovm-compute-context.xml b/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/spring-ovm-compute-context.xml deleted file mode 100644 index 87676ef3a729..000000000000 --- a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-compute/spring-ovm-compute-context.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - diff --git a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/module.properties b/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/module.properties deleted file mode 100644 index 9f432a51c39c..000000000000 --- a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=ovm-discoverer -parent=discoverer diff --git a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/spring-ovm-discoverer-context.xml b/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/spring-ovm-discoverer-context.xml deleted file mode 100644 index a4a03f46542e..000000000000 --- a/plugins/hypervisors/ovm/src/main/resources/META-INF/cloudstack/ovm-discoverer/spring-ovm-discoverer-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/ConfigFileOps.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/ConfigFileOps.py deleted file mode 100755 index 6cfa6bb13960..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/ConfigFileOps.py +++ /dev/null @@ -1,174 +0,0 @@ -# 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. -import re -class ConfigFileOps: - class entry: - def __init__(self, name, value, op, separator): - self.name = name - self.value = value - self.state = "new" - self.op = op - self.separator = separator - def setState(self, state): - self.state = state - def getState(self): - return self.state - - def __init__(self, fileName, cfg=None): - self.fileName = fileName - self.entries = [] - self.backups = [] - - if cfg is not None: - cfg.cfoHandlers.append(self) - - def addEntry(self, name, value, separator="="): - e = self.entry(name, value, "add", separator) - self.entries.append(e) - - def rmEntry(self, name, value, separator="="): - entry = self.entry(name, value, "rm", separator) - self.entries.append(entry) - - def getEntry(self, name, separator="="): - try: - ctx = file(self.fileName).read(-1) - match = re.search("^" + name + ".*", ctx, re.MULTILINE) - if match is None: - return "" - line = match.group(0).split(separator, 1) - return line[1] - except: - return "" - - def save(self): - fp = open(self.fileName, "r") - newLines = [] - for line in fp.readlines(): - matched = False - for entry in self.entries: - if entry.op == "add": - if entry.separator == "=": - matchString = "^\ *" + entry.name + ".*" - elif entry.separator == " ": - matchString = "^\ *" + entry.name + "\ *" + entry.value - else: - if entry.separator == "=": - matchString = "^\ *" + entry.name + "\ *=\ *" + entry.value - else: - matchString = "^\ *" + entry.name + "\ *" + entry.value - - match = re.match(matchString, line) - if match is not None: - if entry.op == "add" and entry.separator == "=": - newline = entry.name + "=" + entry.value + "\n" - entry.setState("set") - newLines.append(newline) - self.backups.append([line, newline]) - matched = True - break - elif entry.op == "rm": - entry.setState("set") - self.backups.append([line, None]) - matched = True - break - - if not matched: - newLines.append(line) - - for entry in self.entries: - if entry.getState() != "set": - if entry.op == "add": - newline = entry.name + entry.separator + entry.value + "\n" - newLines.append(newline) - self.backups.append([None, newline]) - entry.setState("set") - - fp.close() - - file(self.fileName, "w").writelines(newLines) - - def replace_line(self, startswith,stanza,always_add=False): - lines = [ s.strip() for s in file(self.fileName).readlines() ] - newlines = [] - replaced = False - for line in lines: - if re.search(startswith, line): - if stanza is not None: - newlines.append(stanza) - self.backups.append([line, stanza]) - replaced = True - else: newlines.append(line) - if not replaced and always_add: - newlines.append(stanza) - self.backups.append([None, stanza]) - newlines = [ s + '\n' for s in newlines ] - file(self.fileName,"w").writelines(newlines) - - def replace_or_add_line(self, startswith,stanza): - return self.replace_line(startswith,stanza,always_add=True) - - def add_lines(self, lines, addToBackup=True): - fp = file(self.fileName).read(-1) - sh = re.escape(lines) - match = re.search(sh, fp, re.MULTILINE) - if match is not None: - return - - fp += lines - file(self.fileName, "w").write(fp) - self.backups.append([None, lines]) - - def replace_lines(self, src, dst, addToBackup=True): - fp = file(self.fileName).read(-1) - sh = re.escape(src) - if dst is None: - dst = "" - repl,nums = re.subn(sh, dst, fp) - if nums <=0: - return - file(self.fileName, "w").write(repl) - if addToBackup: - self.backups.append([src, dst]) - - def append_lines(self, match_lines, append_lines): - fp = file(self.fileName).read(-1) - sh = re.escape(match_lines) - match = re.search(sh, fp, re.MULTILINE) - if match is None: - return - - sh = re.escape(append_lines) - if re.search(sh, fp, re.MULTILINE) is not None: - return - - newlines = [] - for line in file(self.fileName).readlines(): - if re.search(match_lines, line) is not None: - newlines.append(line + append_lines) - self.backups.append([line, line + append_lines]) - else: - newlines.append(line) - - file(self.fileName, "w").writelines(newlines) - - def backup(self): - for oldLine, newLine in self.backups: - if newLine is None: - self.add_lines(oldLine, False) - else: - self.replace_lines(newLine, oldLine, False) diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmCommonModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmCommonModule.py deleted file mode 100755 index eb50a2e0b1c9..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmCommonModule.py +++ /dev/null @@ -1,158 +0,0 @@ -# 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. -''' -Created on May 17, 2011 - -''' - -try: - import json -except ImportError: - import simplejson as json - -from OvmObjectModule import * -import types -import logging -import popen2 -import subprocess -from OvmFaultConstants import toErrCode, dispatchErrCode, NoVmFoundException, ShellExceutedFailedException -from xmlrpclib import Fault as XmlRpcFault -from OVSCommons import * -from OvmLoggerModule import OvmLogger -from OVSXXenStore import xen_get_vm_path -from OVSSiteRMServer import get_master_ip - -HEARTBEAT_TIMESTAMP_FORMAT='%s' -HEARTBEAT_TIMESTAMP_PATTERN='(\\d+.\d+<\/timestamp\>)' -HEARTBEAT_DIR='heart_beat' -ETC_HOSTS='/etc/hosts' -HOSTNAME_FILE='/etc/sysconfig/network' -OWNER_FILE_PREFIX='host_' -OCFS2_CONF='/etc/ocfs2/cluster.conf' - -logger = OvmLogger('OvmCommon') - -def setAttrFromDict(obj, name, refDict, convertFunc=None): - if not convertFunc: - setattr(obj, name, refDict[name]) - else: - setattr(obj, name, convertFunc(refDict[name])) - -def safeSetAttr(obj, name, value): - if not hasattr(obj, name): raise Exception("%s doesn't have attribute %s"%(obj.__class__.__name__, name)) - setattr(obj, name, value) - -def toAscii(jstr): - return str(jstr).encode('ascii', 'ignore') - -def toAsciiHook(dct): - for k in dct: - v = dct[k] - if type(v) is types.UnicodeType: - v = toAscii(v) - del dct[k] - k = toAscii(k) - dct[k] = v - return dct - -def asciiLoads(jStr): - jStr = str(jStr).replace("'", '"').replace('False', 'false').replace('True', 'true') - return json.loads(jStr, object_hook=toAsciiHook) - -def exceptionIfNoSuccess(str, errMsg=None): - if not errMsg: errMsg = str - if "success" not in str: raise Exception("%s (%s)"%(errMsg, str)) - -def successToMap(str, sep=';'): - if not str.startswith("success"): raise Exception(str) - str = str[len('success:'):] - dct = {} - for pair in str.split(sep): - (key, value) = pair.split('=', 1) - dct[key] = value - return dct - -def jsonSuccessToMap(str): - dct = json.loads(str) - if dct['status'] != 'SUCC': raise Exception(str) - return dct['value'] - -def safeDictSet(obj, dct, name): - if not hasattr(obj, name): raise Exception("%s has no attribute %s for encoding"%(obj.__class__.__name__, name)) - dct[name] = getattr(obj, name) - -def normalizeToGson(str): - return str.replace('\\', '').strip('"').replace('"{', '{').replace('}"', '}'); - -def toGson(obj): - return normalizeToGson(json.dumps(obj)) - -def MtoBytes(M): - return M * 1024 * 1024 - -def BytesToM(bytes): - return bytes/(1024*1024) - -def BytesToG(bytes): - return bytes/(1024*1024*1024) - -def runCmd(cmds): - process = subprocess.Popen(cmds, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = process.communicate() - if process.returncode != 0: - raise ShellExceutedFailedException(stderr, process.returncode) - return stdout - -def doCmd(lst): - cmds = [str(i) for i in lst] - cmdStr = ' '.join(cmds) - logger.debug(doCmd, cmdStr) - res = runCmd(cmdStr) - logger.debug(doCmd, 'result:' + res) - return res - -def execute(cmd): - p = popen2.Popen3(cmd, True) - if (p.wait() != 0): - raise Exception("Failed to execute command. Command: " + cmd + ", Error: " + p.childerr.read()) - return p.fromchild.read() - -def getDomId(vm_name): - return execute("xm list | grep " + vm_name + " | awk '{print $2}'").strip() - -def raiseExceptionIfFail(res): - if "success" not in res and "SUCC" not in res: raise Exception(res) - -def ipToHeartBeatFileName(ip): - return ip.replace('.', '_') + "_HEARTBEAT" - -def getVmNameFromConfigureFile(cfgPath): - fd = open(cfgPath) - for i in fd.readlines(): - i = i.strip() - if i.startswith('name'): - (key, value) = i.split("=", 1) - value = value.strip().strip("'") - fd.close() - return value - fd.close() - raise Exception('Cannot find vm name in %s'%cfgPath) - -def makeOwnerFileName(): - hostIp = successToMap(get_master_ip())['ip'] - ownerFileName = OWNER_FILE_PREFIX + hostIp.replace('.', '_') - return ownerFileName diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDiskModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDiskModule.py deleted file mode 100755 index 69d7db425062..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDiskModule.py +++ /dev/null @@ -1,65 +0,0 @@ -# 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. -''' -Created on May 17, 2011 - -''' - -from OvmCommonModule import * - -class OvmDiskDecoder(json.JSONDecoder): - def decode(self, jStr): - deDict = asciiLoads(jStr) - disk = OvmDisk() - setAttrFromDict(disk, 'path', deDict) - setAttrFromDict(disk, 'type', deDict) - setAttrFromDict(disk, 'isIso', deDict) - return disk - -class OvmDiskEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmDisk): raise Exception("%s is not instance of OvmDisk"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'path') - safeDictSet(obj, dct, 'type') - return dct - -def fromOvmDisk(disk): - return normalizeToGson(json.dumps(disk, cls=OvmDiskEncoder)) - -def fromOvmDiskList(diskList): - return [fromOvmDisk(d) for d in diskList] - -def toOvmDisk(jStr): - return json.loads(jStr, cls=OvmDiskDecoder) - -def toOvmDiskList(jStr): - disks = [] - for i in jStr: - d = toOvmDisk(i) - disks.append(d) - return disks - -class OvmDisk(OvmObject): - path = '' - type = '' - isIso = False - - -if __name__ == "__main__": - print toOvmDisk('''{"type":"w","path":"/data/data.raw"}''') - print toOvmDisk('''{"path":"/data/data.raw'","type":"w"}''') diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDispatcher.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDispatcher.py deleted file mode 100755 index da77b064184b..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmDispatcher.py +++ /dev/null @@ -1,62 +0,0 @@ -# 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. -import types -from OvmCommonModule import * -from xmlrpclib import Fault -from OVSCommons import * -import OvmFaultConstants - -import OvmHostModule -import OvmStoragePoolModule -import OvmVmModule -import OvmNetworkModule -import OvmVolumeModule -import OvmSecurityGroupModule -from OvmHaHeartBeatModule import OvmHaHeartBeat - -ExposedClass = {} -logger = OvmLogger('OvmDispatcher') -def InitOvmDispacther(): - global ExposedClass - modules = [ eval(attr) for attr in globals() if isinstance(eval(attr), types.ModuleType) ] - for m in modules: - for name in dir(m): - clz = getattr(m, name) - if type(clz) is types.TypeType and issubclass(clz, OvmObject): - ExposedClass[name] = clz - logger.debug(InitOvmDispacther, "Discovered exposed class:\n\n%s"%"\n".join(ExposedClass)) - -@exposed -def OvmDispatch(methodName, *params): - global ExposedClass - p = methodName.split('.') - if len(p) != 2: - logger.error(OvmDispatch, "%s is not a valid format, should be classname.methodname"%p) - raise Fault(dispatchErrCode('InvalidCallMethodFormat'), "%s is not a valid format, should be classname.methodname"%p) - clzName = p[0] - funcName = p[1] - if clzName not in ExposedClass.keys(): - logger.error(OvmDispatch, "class %s is not exposed by agent"%clzName) - raise Fault(dispatchErrCode('InvalidClass'), "class %s is not exposed by agent"%clzName) - clz = ExposedClass[clzName] - if not hasattr(clz, funcName): - logger.error(OvmDispatch, "class %s has no function %s"%(clzName, funcName)) - raise Fault(dispatchErrCode('InvalidFunction'), "class %s has no function %s"%(clzName, funcName)) - logger.debug(OvmDispatch, "Entering %s.%s ===>"%(clzName, funcName)) - rs = getattr(clz, funcName)(*params) - logger.debug(OvmDispatch, "Exited %s.%s <==="%(clzName, funcName)) - return rs diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmFaultConstants.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmFaultConstants.py deleted file mode 100755 index 80b9c66cf9e4..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmFaultConstants.py +++ /dev/null @@ -1,99 +0,0 @@ -# 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. -OvmDispatcherStub = 0 -OvmHostErrCodeStub = 1000 -OvmVmErrCodeStub = 2000 -OvmStoragePoolErrCodeStub = 3000 -OvmNetworkErrCodeStub = 4000 -OvmVolumeErrCodeStub = 5000 -OvmOCFS2ErrCodeStub = 6000 - -class NoVmFoundException(Exception): - pass - -class ShellExceutedFailedException(Exception): - stderr = '' - errCode = -1000 - - def __init__(self, err, code): - Exception.__init__(self, "%s, return code:%s"%(err, code)) - self.stderr = err - self.errCode = code - -errCode = { - # OvmDispatch is not class, these error codes are reserved - "OvmDispatch.InvalidCallMethodFormat":OvmDispatcherStub+1, - "OvmDispatch.InvalidClass":OvmDispatcherStub+2, - "OvmDispatch.InvalidFunction":OvmDispatcherStub+3, - "OvmVm.reboot":OvmDispatcherStub+4, - - "OvmHost.registerAsPrimary":OvmHostErrCodeStub+1, - "OvmHost.registerAsVmServer":OvmHostErrCodeStub+2, - "OvmHost.ping":OvmHostErrCodeStub+3, - "OvmHost.getDetails":OvmHostErrCodeStub+4, - "OvmHost.getPerformanceStats":OvmHostErrCodeStub+5, - "OvmHost.getAllVms":OvmHostErrCodeStub+6, - "OvmHost.fence":OvmHostErrCodeStub+7, - "OvmHost.setupHeartBeat":OvmHostErrCodeStub+8, - "OvmHost.pingAnotherHost":OvmHostErrCodeStub+9, - - "OvmVm.create":OvmVmErrCodeStub+1, - "OvmVm.stop":OvmVmErrCodeStub+2, - "OvmVm.getDetails":OvmVmErrCodeStub+3, - "OvmVm.getVmStats":OvmVmErrCodeStub+4, - "OvmVm.migrate":OvmVmErrCodeStub+5, - "OvmVm.register":OvmVmErrCodeStub+6, - "OvmVm.getVncPort":OvmVmErrCodeStub+7, - "OvmVm.detachOrAttachIso":OvmVmErrCodeStub+8, - - "OvmStoragePool.create":OvmStoragePoolErrCodeStub+1, - "OvmStoragePool.getDetailsByUuid":OvmStoragePoolErrCodeStub+2, - "OvmStoragePool.downloadTemplate":OvmStoragePoolErrCodeStub+3, - "OvmStoragePool.prepareOCFS2Nodes":OvmStoragePoolErrCodeStub+4, - "OvmStoragePool.createTemplateFromVolume":OvmStoragePoolErrCodeStub+5, - "OvmStoragePool._umount":OvmStoragePoolErrCodeStub+6, - "OvmStoragePool.copyVolume":OvmStoragePoolErrCodeStub+7, - "OvmStoragePool.delete":OvmStoragePoolErrCodeStub+8, - - "OvmNetwork.createBridge":OvmNetworkErrCodeStub+1, - "OvmNetwork.deleteBridge":OvmNetworkErrCodeStub+2, - "OvmNetwork.createVlan":OvmNetworkErrCodeStub+3, - "OvmNetwork.deleteVlan":OvmNetworkErrCodeStub+4, - "OvmNetwork.getAllBridges":OvmNetworkErrCodeStub+5, - "OvmNetwork.getBridgeByIp":OvmNetworkErrCodeStub+6, - "OvmNetwork.createVlanBridge":OvmNetworkErrCodeStub+7, - "OvmNetwork.deleteVlanBridge":OvmNetworkErrCodeStub+8, - - "OvmVolume.createDataDisk":OvmVolumeErrCodeStub+1, - "OvmVolume.createFromTemplate":OvmVolumeErrCodeStub+2, - "OvmVolume.destroy":OvmVolumeErrCodeStub+3, - - "OvmOCFS2._addNode":OvmOCFS2ErrCodeStub+1, -} - - -def toErrCode(clz, func): - global errCode - if not callable(func): raise Exception("%s is not a callable, cannot get error code"%func) - name = clz.__name__ + '.' + func.__name__ - if name not in errCode.keys(): return -1 - return errCode[name] - -def dispatchErrCode(funcName): - name = "OvmDispatch." + funcName - if name not in errCode.keys(): return -1 - return errCode[name] diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py deleted file mode 100755 index 05e934184fbf..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHaHeartBeatModule.py +++ /dev/null @@ -1,104 +0,0 @@ -# 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. -''' -Created on Jun 6, 2011 - -''' -from OvmCommonModule import * -try: - from multiprocessing import Process, Manager -except ImportError: - from processing import Process, Manager -import signal - -logger = OvmLogger("OvmHaHeartBeat") - -class OvmHaHeartBeat(object): - ''' - classdocs - ''' - def __init__(self, mountPoint, ip): - self.mountPoint = mountPoint - self.ip = ip - - def mark(self, file): - timestamp = HEARTBEAT_TIMESTAMP_FORMAT % time.time() - try: - fd = open(file, 'w') - fd.write(timestamp) - fd.close() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHaHeartBeat.mark, errmsg) - - def run(self): - ''' - Constructor - ''' - heartBeatDir = join(self.mountPoint, HEARTBEAT_DIR) - if not exists(heartBeatDir): - os.makedirs(heartBeatDir) - hearBeatFile = join(heartBeatDir, ipToHeartBeatFileName(self.ip)) - while True: - self.mark(hearBeatFile) - time.sleep(120) - - @staticmethod - def start(poolPath, ip): - pidFile = join(PID_DIR, "heartbeat.pid") - - def isLive(): - if exists(pidFile): - f = open(pidFile) - pid = f.read().strip() - f.close() - if isdir("/proc/%s" % pid): - return long(pid) - return None - - def stopOldHeartBeat(pid): - os.kill(pid, signal.SIGTERM) - time.sleep(5) - pid = isLive() - if pid != None: - logger.debug(OvmHaHeartBeat.start, "SIGTERM cannot stop heartbeat process %s, will try SIGKILL"%pid) - os.kill(pid, signal.SIGKILL) - time.sleep(5) - pid = isLive() - if pid != None: - raise Exception("Cannot stop old heartbeat process %s, setup heart beat failed"%pid) - - def heartBeat(hb): - hb.run() - - def setupHeartBeat(): - hb = OvmHaHeartBeat(poolPath, ip) - p = Process(target=heartBeat, args=(hb,)) - p.start() - pid = p.pid - if not isdir(PID_DIR): - os.makedirs(PID_DIR) - pidFd = open(pidFile, 'w') - pidFd.write(str(pid)) - pidFd.close() - logger.info(OvmHaHeartBeat.start, "Set up heart beat successfully, pid is %s" % pid) - - pid = isLive() - if pid != None: - stopOldHeartBeat(pid) - - setupHeartBeat() diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHostModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHostModule.py deleted file mode 100755 index d0e0b5895d3a..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmHostModule.py +++ /dev/null @@ -1,307 +0,0 @@ -# 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. - -from OvmCommonModule import * -from OVSSiteRMServer import get_master_ip, register_server -from OVSCommons import * -from OVSXMonitor import xen_get_xm_info -from OVSXSysInfo import get_agent_version -from OVSSiteRMServer import get_srv_agent_status -from OVSXMonitor import sys_perf_info -from OVSDB import db_get_vm -from OvmStoragePoolModule import OvmStoragePool -from OvmHaHeartBeatModule import OvmHaHeartBeat -import re - -logger = OvmLogger('OvmHost') - -class OvmHostEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmHost): raise Exception("%s is not instance of OvmHost"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'masterIp') - safeDictSet(obj, dct, 'cpuNum') - safeDictSet(obj, dct, 'cpuSpeed') - safeDictSet(obj, dct, 'totalMemory') - safeDictSet(obj, dct, 'freeMemory') - safeDictSet(obj, dct, 'dom0Memory') - safeDictSet(obj, dct, 'agentVersion') - safeDictSet(obj, dct, 'name') - safeDictSet(obj, dct, 'dom0KernelVersion') - safeDictSet(obj, dct, 'hypervisorVersion') - return dct - - -def fromOvmHost(host): - return normalizeToGson(json.dumps(host, cls=OvmHostEncoder)) - -class OvmHost(OvmObject): - masterIp = '' - cpuNum = 0 - cpuSpeed = 0 - totalMemory = 0 - freeMemory = 0 - dom0Memory = 0 - agentVersion = '' - name = '' - dom0KernelVersion = '' - hypervisorVersion = '' - - def _getVmPathFromPrimaryStorage(self, vmName): - ''' - we don't have a database to store vm states, so there is no way to retrieve information of a vm - when it was already stopped. The trick is to try to find the vm path in primary storage then we - can read information from its configure file. - ''' - mps = OvmStoragePool()._getAllMountPoints() - vmPath = None - for p in mps: - vmPath = join(p, 'running_pool', vmName) - if exists(vmPath): break - if not vmPath: - logger.error(self._getVmPathFromPrimaryStorage, "Cannot find link for %s in any primary storage, the vm was really gone!"%vmName) - raise Exception("Cannot find link for %s in any primary storage, the vm was really gone!"%vmName) - return vmPath - - def _vmNameToPath(self, vmName): - # the xen_get_vm_path always sucks!!! - #return successToMap((vmName))['path'] - return self._getVmPathFromPrimaryStorage(vmName) - - def _getAllDomains(self): - stdout = timeout_command(["xm", "list"]) - l = [ line.split()[:2] for line in stdout.splitlines() ] - l = [ (name, id) for (name, id) in l if name not in ("Name", "Domain-0") ] - return l - - def _getDomainIdByName(self, vmName): - l = self._getAllDomains() - for name, id in l: - if vmName == name: return id - raise NoVmFoundException("No domain id for %s found"%vmName) - - @staticmethod - def registerAsPrimary(hostname, username="oracle", password="password", port=8899, isSsl=False): - try: - logger.debug(OvmHost.registerAsPrimary, "ip=%s, username=%s, password=%s, port=%s, isSsl=%s"%(hostname, username, password, port, isSsl)) - exceptionIfNoSuccess(register_server(hostname, 'site', False, username, password, port, isSsl), - "Register %s as site failed"%hostname) - exceptionIfNoSuccess(register_server(hostname, 'utility', False, username, password, port, isSsl), - "Register %s as utility failed"%hostname) - rs = SUCC() - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.registerAsPrimary, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.registerAsPrimary), errmsg) - - @staticmethod - def registerAsVmServer(hostname, username="oracle", password="password", port=8899, isSsl=False): - try: - logger.debug(OvmHost.registerAsVmServer, "ip=%s, username=%s, password=%s, port=%s, isSsl=%s"%(hostname, username, password, port, isSsl)) - exceptionIfNoSuccess(register_server(hostname, 'xen', False, username, password, port, isSsl), - "Register %s as site failed"%hostname) - rs = SUCC() - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.registerAsVmServer, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.registerAsVmServer), errmsg) - - @staticmethod - def ping(hostname): - try: - logger.debug(OvmHost.ping, "ping %s"%hostname) - exceptionIfNoSuccess(get_srv_agent_status(hostname), "Ovs agent is down") - rs = SUCC() - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.ping, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.ping, errmsg)) - - @staticmethod - def getDetails(): - try: - obj = OvmHost() - masterIp = successToMap(get_master_ip()) - safeSetAttr(obj, 'masterIp', masterIp['ip']) - xmInfo = successToMap(xen_get_xm_info()) - totalMemory = MtoBytes(long(xmInfo['total_memory'])) - safeSetAttr(obj, 'totalMemory', totalMemory) - freeMemory = MtoBytes(long(xmInfo['free_memory'])) - safeSetAttr(obj, 'freeMemory', freeMemory) - dom0Memory = totalMemory - freeMemory - safeSetAttr(obj, 'dom0Memory', dom0Memory) - cpuNum = int(xmInfo['nr_cpus']) - safeSetAttr(obj, 'cpuNum', cpuNum) - cpuSpeed = int(xmInfo['cpu_mhz']) - safeSetAttr(obj, 'cpuSpeed', cpuSpeed) - name = xmInfo['host'] - safeSetAttr(obj, 'name', name) - dom0KernelVersion = xmInfo['release'] - safeSetAttr(obj, 'dom0KernelVersion', dom0KernelVersion) - hypervisorVersion = xmInfo['xen_major'] + '.' + xmInfo['xen_minor'] + xmInfo['xen_extra'] - safeSetAttr(obj, 'hypervisorVersion', hypervisorVersion) - agtVersion = successToMap(get_agent_version()) - safeSetAttr(obj, 'agentVersion', agtVersion['agent_version']) - res = fromOvmHost(obj) - logger.debug(OvmHost.getDetails, res) - return res - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.getDetails, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.getDetails), errmsg) - - @staticmethod - def getPerformanceStats(bridgeName): - try: - rxBytesPath = join("/sys/class/net/", bridgeName, "statistics/rx_bytes") - txBytesPath = join("/sys/class/net/", bridgeName, "statistics/tx_bytes") - if not exists(rxBytesPath): raise Exception("Cannot find %s"%rxBytesPath) - if not exists(txBytesPath): raise Exception("Cannot find %s"%txBytesPath) - rxBytes = long(doCmd(['cat', rxBytesPath])) / 1000 - txBytes = long(doCmd(['cat', txBytesPath])) / 1000 - sysPerf = successToMap(sys_perf_info()) - cpuUtil = float(100 - float(sysPerf['cpu_idle']) * 100) - freeMemory = MtoBytes(long(sysPerf['mem_free'])) - xmInfo = successToMap(xen_get_xm_info()) - totalMemory = MtoBytes(long(xmInfo['total_memory'])) - rs = toGson({"cpuUtil":cpuUtil, "totalMemory":totalMemory, "freeMemory":freeMemory, "rxBytes":rxBytes, "txBytes":txBytes}) - logger.info(OvmHost.getPerformanceStats, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.getPerformanceStats, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.getPerformanceStats), errmsg) - - @staticmethod - def getAllVms(): - def scanStoppedVmOnPrimaryStorage(vms): - def isMyVmDirLink(path): - return (islink(path) and exists(join(path, 'vm.cfg')) and ('-' in basename(path)) and (exists(join(path, makeOwnerFileName())))) - - mps = OvmStoragePool()._getAllMountPoints() - for mountPoint in mps: - runningPool = join(mountPoint, 'running_pool') - if not exists(runningPool): - logger.debug(OvmHost.getAllVms, "Primary storage %s not existing, skip it. this should be first getAllVms() called from Ovm resource configure"%runningPool) - continue - - for dir in os.listdir(runningPool): - vmDir = join(runningPool, dir) - if not isMyVmDirLink(vmDir): - logger.debug(OvmHost.getAllVms, "%s is not our vm directory, skip it"%vmDir) - continue - if vms.has_key(dir): - logger.debug(OvmHost.getAllVms, "%s is already in running list, skip it"%dir) - continue - - logger.debug(OvmHost.getAllVms, "Found a stopped vm %s on primary storage %s, report it to management server" % (dir, mountPoint)) - vms[dir] = "DOWN" - - - try: - l = OvmHost()._getAllDomains() - dct = {} - host = OvmHost() - for name, id in l: - try: - vmPath = host._getVmPathFromPrimaryStorage(name) - vmStatus = db_get_vm(vmPath) - dct[name] = vmStatus['status'] - except Exception, e: - logger.debug(OvmHost.getAllVms, "Cannot find link for %s on primary storage, treat it as Error"%name) - dct[name] = 'ERROR' - - scanStoppedVmOnPrimaryStorage(dct) - rs = toGson(dct) - logger.info(OvmHost.getAllVms, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.getAllVms, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.getAllVms), errmsg) - - @staticmethod - def fence(ip): - # try 3 times to avoid race condition that read when heartbeat file is being written - def getTimeStamp(hbFile): - for i in range(1, 3): - f = open(hbFile, 'r') - str = f.readline() - items = re.findall(HEARTBEAT_TIMESTAMP_PATTERN, str) - if len(items) == 0: - logger.debug(OvmHost.fence, "Get an incorrect heartbeat data %s, will retry %s times" % (str, 3-i)) - f.close() - time.sleep(5) - else: - f.close() - timestamp = items[0] - return timestamp.lstrip('').rstrip('') - - # totally check in 6 mins, the update frequency is 2 mins - def check(hbFile): - for i in range(1, 6): - ts = getTimeStamp(hbFile) - time.sleep(60) - nts = getTimeStamp(hbFile) - if ts != nts: return True - else: logger.debug(OvmHost.fence, '%s is not updated, old value=%s, will retry %s times'%(hbFile, ts, 6-i)) - return False - - try: - mountpoints = OvmStoragePool()._getAllMountPoints() - hbFile = None - for m in mountpoints: - p = join(m, HEARTBEAT_DIR, ipToHeartBeatFileName(ip)) - if exists(p): - hbFile = p - break - - if not hbFile: raise Exception('Can not find heartbeat file for %s in pools %s'%(ip, mountpoints)) - rs = toGson({"isLive":check(hbFile)}) - logger.debug(OvmHost.fence, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.fence, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.fence), errmsg) - - @staticmethod - def setupHeartBeat(poolUuid, ip): - try: - sr = OvmStoragePool()._getSrByNameLable(poolUuid) - OvmHaHeartBeat.start(sr.mountpoint, ip) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.setupHeartBeat, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.setupHeartBeat), errmsg) - - @staticmethod - def pingAnotherHost(ip): - try: - doCmd(['ping', '-c', '1', '-n', '-q', ip]) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmHost.pingAnotherHost, errmsg) - raise XmlRpcFault(toErrCode(OvmHost, OvmHost.pingAnotherHost), errmsg) - -if __name__ == "__main__": - print OvmHost.getAllVms() diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmLoggerModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmLoggerModule.py deleted file mode 100755 index ede2a8764fd0..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmLoggerModule.py +++ /dev/null @@ -1,54 +0,0 @@ -# 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. -''' -Created on May 19, 2011 - -''' -import logging - -class OvmLogger(object): - ''' - classdocs - ''' - - - def __init__(self, className): - ''' - Constructor - ''' - self.className = className - self.logger = logging.getLogger(className) - - def info(self, func, msg=None): - assert callable(func), "%s is not a function"%func - fmt = "[%s.%s]: "%(self.className, func.__name__) - self.logger.info("%s%s"%(fmt,msg)) - - def debug(self, func, msg=None): - assert callable(func), "%s is not a function"%func - fmt = "[%s.%s]: "%(self.className, func.__name__) - self.logger.debug("%s%s"%(fmt,msg)) - - def error(self, func, msg=None): - assert callable(func), "%s is not a function"%func - fmt = "[%s.%s]: "%(self.className, func.__name__) - self.logger.error("%s%s"%(fmt,msg)) - - def warning(self, func, msg=None): - assert callable(func), "%s is not a function"%func - fmt = "[%s.%s]: "%(self.className, func.__name__) - self.logger.warning("%s%s"%(fmt,msg)) diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmNetworkModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmNetworkModule.py deleted file mode 100755 index edb65bbebcbb..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmNetworkModule.py +++ /dev/null @@ -1,433 +0,0 @@ -# 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. -from OvmCommonModule import * -import traceback -import time -import re - -logger = OvmLogger("OvmNetwork") - -class Filter: - class Network: - IFNAME_LO = r'(lo)' - IFNAME_BRIDGE = r'(xenbr\d+|vlan\d+)' - IFNAME_PIF = r'(eth\d+$|bond\d+$)' - IFNAME_VLAN = r'(eth\d+.\d+$|bond\d+.\d+$)' - - -class Parser(object): - ''' - classdocs - ''' - def findall(self, pattern, samples): - """ - @param pattern: search pattern - @param result: Parser line execution result - @return : list of search - find result of Parser which has same pattern - findall Parser find all pattern in a string - """ - result = [] - for line in samples: - items = re.findall(pattern, line) - for item in items: - result.append(item) - return result - - def checkPattern(self, pattern, cmd_result): - """ - @param pattern: search pattern - @param cmd_result: Parser line execution result - @return : True (if pattern is occurred) - """ - for line in cmd_result: - items = re.findall(pattern, line) - if len(items) > 0: - return True - return False - - def search(self, cmd_result, pattern): - return None - -class OvmVlanDecoder(json.JSONDecoder): - def decode(self, jStr): - deDict = asciiLoads(jStr) - vlan = OvmVlan() - setAttrFromDict(vlan, 'vid', deDict, int) - setAttrFromDict(vlan, 'pif', deDict) - return vlan - -class OvmVlanEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmVlan): raise Exception("%s is not instance of OvmVlan"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'name') - safeDictSet(obj, dct, 'vid') - safeDictSet(obj, dct, 'pif') - return dct - -def toOvmVlan(jStr): - return json.loads(jStr, cls=OvmVlanDecoder) - -def fromOvmVlan(vlan): - return normalizeToGson(json.dumps(vlan, cls=OvmVlanEncoder)) - -class OvmBridgeDecoder(json.JSONDecoder): - def decode(self, jStr): - deDic = asciiLoads(jStr) - bridge = OvmBridge() - setAttrFromDict(bridge, 'name', deDic) - setAttrFromDict(bridge, 'attach', deDic) - return bridge - -class OvmBridgeEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmBridge): raise Exception("%s is not instance of OvmBridge"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'name') - safeDictSet(obj, dct, 'attach') - safeDictSet(obj, dct, 'interfaces') - return dct - -def toOvmBridge(jStr): - return json.loads(jStr, cls=OvmBridgeDecoder) - -def fromOvmBridge(bridge): - return normalizeToGson(json.dumps(bridge, cls=OvmBridgeEncoder)) - -class OvmInterface(OvmObject): - name = '' - -class OvmVlan(OvmInterface): - vid = 0 - pif = '' - -class OvmBridge(OvmInterface): - attach = '' - interfaces = [] - - -class OvmNetwork(OvmObject): - ''' - Network - ''' - - @property - def pifs(self): - return self._getInterfaces("pif") - - @property - def vlans(self): - return self._getInterfaces("vlan") - - @property - def bridges(self): - return self._getInterfaces("bridge") - - def __init__(self): - self.Parser = Parser() - - def _createVlan(self, vlan): - """ - @param jsonString : parameter from client side - @return : succ xxxxx - ex. jsonString => {vid:100, pif:eth0} - ex. return => - """ - - #Pre-condition - #check Physical Interface Name - if vlan.pif not in self.pifs.keys(): - msg = "Physical Interface(%s) does not exist" % vlan.pif - logger.debug(self._createVlan, msg) - raise Exception(msg) - - #Pre-condition - #check Vlan Interface Name - ifName = "%s.%s" % (vlan.pif, vlan.vid) - if ifName in self.vlans.keys(): - msg = "Vlan Interface(%s) already exist, return it" % ifName - logger.debug(self._createVlan, msg) - return self.vlans[ifName] - - doCmd(['vconfig', 'add', vlan.pif, vlan.vid]) - self.bringUP(ifName) - logger.debug(self._createVlan, "Create vlan %s successfully"%ifName) - return self.vlans[ifName] - - def _deleteVlan(self, name): - if name not in self.vlans.keys(): - raise Exception("No vlan device %s found"%name) - - vlan = self.vlans[name] - self.bringDown(vlan.name) - doCmd(['vconfig', 'rem', vlan.name]) - logger.debug(self._deleteVlan, "Delete vlan %s successfully"%vlan.name) - - - def _createBridge(self, bridge): - """ - @return : success - ex. {bridge:xapi100, attach:eth0.100} - create bridge interface, and attached it - cmd 1: ip link add bridge - cmd 2: ip link set dev - """ - - if "xenbr" not in bridge.name and "vlan" not in bridge.name: - raise Exception("Invalid bridge name %s. Bridge name must be in partten xenbr/vlan, e.g. xenbr0"%bridge.name) - - #pre-condition - #check Bridge Interface Name - if bridge.name in self.bridges.keys(): - msg = "Bridge(%s) already exist, return it" % bridge.name - logger.debug(self._createBridge, msg) - return self.bridges[bridge.name] - - #pre-condition - #check attach must exist - #possible to attach in PIF or VLAN - if bridge.attach not in self.vlans.keys() and bridge.attach not in self.pifs.keys(): - msg = "%s is not either pif or vlan" % bridge.attach - logger.error(self._createBridge, msg) - raise Exception(msg) - - doCmd(['ip', 'link', 'add', 'name', bridge.name, 'type', 'bridge']) - doCmd(['ip', 'link', 'set', 'dev', bridge.attach, 'master', bridge.name]) - self.bringUP(bridge.name) - logger.debug(self._createBridge, "Create bridge %s on %s successfully"%(bridge.name, bridge.attach)) - return self.bridges[bridge.name] - - def _getBridges(self): - return self.bridges.keys() - - def _getVlans(self): - return self.vlans.keys() - - def _deleteBridge(self, name): - if name not in self.bridges.keys(): - raise Exception("Can not find bridge %s"%name) - - bridge = self.bridges[name] - if bridge.attach in bridge.interfaces: bridge.interfaces.remove(bridge.attach) - if len(bridge.interfaces) != 0: - logger.debug(self._deleteBridge, "There are still some interfaces(%s) on bridge %s"%(bridge.interfaces, bridge.name)) - return False - self.bringDown(bridge.name) - doCmd(['ip', 'link', 'del', bridge.name]) - logger.debug(self._deleteBridge, "Delete bridge %s successfully"%bridge.name) - return True - - def _getInterfaces(self, type): - """ - @param type : ["pif", "bridge", "tap"] - @return : dictionary of Interface Objects - get All Interfaces based on type - """ - devices = os.listdir('/sys/class/net') - ifs = {} - if type == "pif": - devs = self.Parser.findall(Filter.Network.IFNAME_PIF, devices) - for dev in set(devs): - ifInst = OvmInterface() - ifInst.name = dev - ifs[dev] = ifInst - - elif type == "vlan": - devs = self.Parser.findall(Filter.Network.IFNAME_VLAN, devices) - for dev in set(devs): - ifInst = OvmVlan() - ifInst.name = dev - (pif, vid) = dev.split('.') - ifInst.pif = pif - ifInst.vid = vid - ifs[dev] = ifInst - - elif type == "bridge": - devs = self.Parser.findall(Filter.Network.IFNAME_BRIDGE, devices) - for dev in set(devs): - ifInst = OvmBridge() - ifInst.name = dev - devs = os.listdir(join('/sys/class/net', dev, 'brif')) - ifInst.interfaces = devs - attches = self.Parser.findall(Filter.Network.IFNAME_PIF, devs) + self.Parser.findall(Filter.Network.IFNAME_VLAN, devs) - if len(attches) > 1: raise Exception("Multiple PIF on bridge %s (%s)"%(dev, attches)) - elif len(attches) == 0: ifInst.attach = "null" - elif len(attches) == 1: ifInst.attach = attches[0] - ifs[dev] = ifInst - - return ifs - - def bringUP(self, ifName): - doCmd(['ifconfig', ifName, 'up']) - - def bringDown(self, ifName): - doCmd(['ifconfig', ifName, 'down']) - - @staticmethod - def createBridge(jStr): - try: - network = OvmNetwork() - network._createBridge(toOvmBridge(jStr)) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.createBridge, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.createBridge), errmsg) - - @staticmethod - def deleteBridge(name): - try: - network = OvmNetwork() - network._deleteBridge(name) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.deleteBridge, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.deleteBridge), errmsg) - - @staticmethod - def getAllBridges(): - try: - network = OvmNetwork() - rs = toGson(network._getBridges()) - logger.debug(OvmNetwork.getAllBridges, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.getAllBridges, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.getAllBridges), errmsg) - - @staticmethod - def getBridgeByIp(ip): - try: - routes = doCmd(['ip', 'route']).split('\n') - brName = None - for r in routes: - if ip in r and "xenbr" in r or "vlan" in r: - brName = r.split(' ')[2] - break - if not brName: raise Exception("Cannot find bridge with IP %s"%ip) - logger.debug(OvmNetwork.getBridgeByIp, "bridge:%s, ip:%s"%(brName, ip)) - return toGson({"bridge":brName}) - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.getBridgeByIp, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.getBridgeByIp), errmsg) - - @staticmethod - def getVlans(): - try: - network = OvmNetwork() - rs = toGson(network._getVlans()) - logger.debug(OvmNetwork.getVlans, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.getVlans, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.getVlans), errmsg) - - @staticmethod - def createVlan(jStr): - try: - network = OvmNetwork() - vlan = network._createVlan(toOvmVlan(jStr)) - rs = fromOvmVlan(vlan) - logger.debug(OvmNetwork.createVlan, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.createVlan, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.createVlan), errmsg) - - @staticmethod - def createVlanBridge(bridgeDetails, vlanDetails): - try: - network = OvmNetwork() - v = toOvmVlan(vlanDetails) - b = toOvmBridge(bridgeDetails) - vlan = network._createVlan(v) - b.attach = vlan.name - network._createBridge(b) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.createVlanBridge, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.createVlanBridge), errmsg) - - @staticmethod - def deleteVlanBridge(name): - try: - network = OvmNetwork() - if name not in network.bridges.keys(): - logger.debug(OvmNetwork.deleteVlanBridge, "No bridge %s found"%name) - return SUCC() - - bridge = network.bridges[name] - vlanName = bridge.attach - if network._deleteBridge(name): - if vlanName != "null": - network._deleteVlan(vlanName) - else: - logger.warning(OvmNetwork.deleteVlanBridge, "Bridge %s has no vlan device"%name) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.deleteVlanBridge, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.deleteVlanBridge), errmsg) - - @staticmethod - def getBridgeDetails(name): - try: - network = OvmNetwork() - if name not in network.bridges.keys(): - raise Exception("No bridge %s found"%name) - bridge = network.bridges[name] - rs = fromOvmBridge(bridge) - logger.debug(OvmNetwork.getBridgeDetails, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.getBridgeDetails, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.getBridgeDetails), errmsg) - - @staticmethod - def deleteVlan(name): - try: - network = OvmNetwork() - network._deleteVlan(name) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmNetwork.deleteVlan, errmsg) - raise XmlRpcFault(toErrCode(OvmNetwork, OvmNetwork.deleteVlan), errmsg) - -if __name__ == "__main__": - try: - OvmNetwork.getBridgeDetails(sys.argv[1]) - #======================================================================= - # txt = json.dumps({"vid":104, "pif":"eth0"}) - # txt2 = json.dumps({"name":"xapi3", "attach":"eth0.104"}) - # print nw.createVlan(txt) - # print nw.createBridge(txt2) - # - # nw.deleteBridge("xapi3") - # nw.deleteVlan("eth0.104") - #======================================================================= - - except Exception, e: - print e diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py deleted file mode 100755 index 06e1e28f28e8..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmOCFS2Module.py +++ /dev/null @@ -1,79 +0,0 @@ -# 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. -from OvmCommonModule import * - -logger = OvmLogger('OvmOCFS2') -class OvmOCFS2(OvmObject): - def _prepareConf(self, cluster): - conf = '''cluster: - node_count = 0 - name = %s - '''%cluster - dir = dirname(OCFS2_CONF) - if not isdir(dir): - os.makedirs(dir) - - fd = open(OCFS2_CONF, 'w') - fd.write(conf) - fd.close() - - def _addNode(self, name, nodeNum, ip, port, cluster, isOnline=True): - nodePath = '/sys/kernel/config/cluster/%s/node/%s'%(cluster, name) - if exists(nodePath): - logger.debug(OvmOCFS2._addNode, "node %s already exists, skip it(%s)"%(name, nodePath)) - return - - if not isOnline: - cmds = ['o2cb_ctl -C -n', name, '-t node', '-a number=%s'%nodeNum, '-a ip_address=%s'%ip, '-a ip_port=%s'%port, '-a cluster=%s'%cluster] - else: - cmds = ['o2cb_ctl -C -i -n', name, '-t node', '-a number=%s'%nodeNum, '-a ip_address=%s'%ip, '-a ip_port=%s'%port, '-a cluster=%s'%cluster] - - try: - doCmd(cmds) - except ShellExceutedFailedException, e: - if e.errCode == 239 or "already exists" in e.stderr: - logger.debug(OvmOCFS2._addNode, "node %s already exists, skip it(%s)"%(name, e.stderr)) - else: - raise e - - def _isClusterOnline(self, cluster): - cmds = ['service o2cb status', cluster] - res = doCmd(cmds) - for line in res.split('\n'): - if not 'Checking O2CB cluster' in line: continue - return not 'Offline' in line - - def _load(self): - cmd = ['service o2cb load'] - doCmd(cmd) - - def _start(self, cluster): - #blank line are answer by clicking enter - config=''' -y -o2cb -%s - - - - -EOF -'''%cluster - cmd = ['service o2cb configure', '< (free_storage_size + 1024 * 1024 * 1024): - raise Exception("No space on dir %s (free storage:%s, vm size:%s)"%(dir, free_storage_size, image_size)) - - def _getAllMountPoints(self): - mps = [] - d = db_dump('sr') - for uuid, sr in d.items(): - mps.append(sr.mountpoint) - return mps - - def _isMounted(self, path): - res = doCmd(['mount']) - return (path in res) - - def _mount(self, target, mountpoint, readonly=False): - if not exists(mountpoint): - os.makedirs(mountpoint) - - if not OvmStoragePool()._isMounted(mountpoint): - if readonly: - doCmd(['mount', target, mountpoint, '-r']) - else: - doCmd(['mount', target, mountpoint]) - - def _umount(self, mountpoint): - umountCmd = ['umount', '-f', mountpoint] - doCmd(umountCmd) - ls = os.listdir(mountpoint) - if len(ls) == 0: - rmDirCmd = ['rm', '-r', mountpoint] - doCmd(rmDirCmd) - else: - logger.warning(OvmStoragePool._umount, "Something wrong when umount %s, there are still files in directory:%s", mountpoint, " ".join(ls)) - - @staticmethod - def create(jStr): - try: - pool = toOvmStoragePool(jStr) - logger.debug(OvmStoragePool.create, fromOvmStoragePool(pool)) - spUuid = jsonSuccessToMap(sp_create(pool.type, pool.path))['uuid'] - srUuid = jsonSuccessToMap(sr_create(spUuid, name_label=pool.uuid))['uuid'] - sr_do(srUuid, "initialize") - rs = SUCC() - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.create, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.create), errmsg) - - @staticmethod - def getDetailsByUuid(uuid): - try: - sr = OvmStoragePool()._getSrByNameLable(uuid) - pool = OvmStoragePool() - safeSetAttr(pool, 'uuid', uuid) - #Note: the sr.sp.fs_type is not mapped to its class name which we use in mgmt server - safeSetAttr(pool, 'type', sr.sp.__class__.__name__) - safeSetAttr(pool, 'path', sr.sp.get_fs_spec()) - safeSetAttr(pool, 'mountPoint', sr.mountpoint) - (totalSpace, freeSpace) = OvmStoragePool()._getSpaceinfoOfDir(sr.mountpoint) - safeSetAttr(pool, 'totalSpace', totalSpace) - safeSetAttr(pool, 'freeSpace', freeSpace) - safeSetAttr(pool, 'usedSpace', totalSpace - freeSpace) - res = fromOvmStoragePool(pool) - logger.debug(OvmStoragePool.getDetailsByUuid, res) - return res - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.getDetailsByUuid, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.getDetailsByUuid), errmsg) - - @staticmethod - def downloadTemplate(uuid, secPath): - secMountPoint = None - try: - logger.debug(OvmStoragePool.downloadTemplate, "download %s to pool %s"%(secPath, uuid)) - try: - tmpUuid = get_uuid() - secMountPoint = join("/var/cloud/", tmpUuid) - if not exists(secMountPoint): - os.makedirs(secMountPoint) - - templateFile = None - if secPath.endswith("raw"): - secPathDir = os.path.dirname(secPath) - templateFile = os.path.basename(secPath) - else: - secPathDir = secPath - - # mount as read-only - mountCmd = ['mount.nfs', secPathDir, secMountPoint, '-r'] - doCmd(mountCmd) - - if not templateFile: - for f in os.listdir(secMountPoint): - if isfile(join(secMountPoint, f)) and f.endswith('raw'): - templateFile = f - break - - if not templateFile: - raise Exception("Can not find raw template in secondary storage") - templateSecPath = join(secMountPoint, templateFile) - - sr = OvmStoragePool()._getSrByNameLable(uuid) - priStorageMountPoint = sr.mountpoint - # Although mgmt server will check the size, we check again for safety - OvmStoragePool()._checkDirSizeForImage(priStorageMountPoint, templateSecPath) - seedDir = join(priStorageMountPoint, 'seed_pool', tmpUuid) - if exists(seedDir): - raise Exception("%s already here, cannot override existing template" % seedDir) - os.makedirs(seedDir) - - tgt = join(seedDir, templateFile) - cpTemplateCmd = ['cp', templateSecPath, tgt] - logger.info(OvmStoragePool.downloadTemplate, " ".join(cpTemplateCmd)) - doCmd(cpTemplateCmd) - templateSize = os.path.getsize(tgt) - logger.info(OvmStoragePool.downloadTemplate, "primary_storage_download success:installPath:%s, templateSize:%s"%(tgt,templateSize)) - rs = toGson({"installPath":tgt, "templateSize":templateSize}) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.downloadTemplate, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.downloadTemplate), errmsg) - finally: - if exists(secMountPoint): - try: - OvmStoragePool()._umount(secMountPoint) - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.downloadTemplate, 'unmount secondary storage at %s failed, %s'%(secMountPoint, errmsg)) - - @staticmethod - def prepareOCFS2Nodes(clusterName, nodeString): - def configureEtcHosts(nodes): - if not exists(ETC_HOSTS): - originalConf = "" - else: - fd = open(ETC_HOSTS, "r") - originalConf = fd.read() - fd.close() - - pattern = r"(.*%s.*)|(.*%s.*)" - newlines = [] - for n in nodes: - p = pattern % (n["ip_address"], n["name"]) - originalConf = re.sub(p, "", originalConf) - newlines.append("%s\t%s\n"%(n["ip_address"], n["name"])) - - originalConf = originalConf + "".join(newlines) - # remove extra empty lines - originalConf = re.sub(r"\n\s*\n*", "\n", originalConf) - logger.debug(OvmStoragePool.prepareOCFS2Nodes, "Configure /etc/hosts:%s\n"%originalConf) - fd = open(ETC_HOSTS, "w") - fd.write(originalConf) - fd.close() - - def configureHostName(nodes): - myIp = successToMap(get_master_ip())['ip'] - nodeName = None - for n in nodes: - if myIp == n["ip_address"]: - nodeName = n["name"] - break - - if nodeName == None: raise Exception("Cannot find node equals to my ip address:%s"%myIp) - if not exists(HOSTNAME_FILE): - originalConf = "" - else: - fd = open(HOSTNAME_FILE, "r") - originalConf = fd.read() - fd.close() - - pattern = r"HOSTNAME=(.*)" - # remove any old hostname - originalConf = re.sub(pattern, "", originalConf) - # remove extra empty lines - originalConf = re.sub(r"\n\s*\n*", "\n", originalConf) + "\n" + "HOSTNAME=%s"%nodeName - logger.debug(OvmStoragePool.prepareOCFS2Nodes, "Configure %s:%s\n"%(HOSTNAME_FILE,originalConf)) - fd = open(HOSTNAME_FILE, "w") - fd.write(originalConf) - fd.close() - doCmd(['hostname', nodeName]) - - def addNodes(nodes, clusterName): - ocfs2 = OvmOCFS2() - ocfs2._load() - isOnline = ocfs2._isClusterOnline(clusterName) - if not isOnline: - ocfs2._prepareConf(clusterName) - - for n in nodes: - ocfs2._addNode(n['name'], n['number'], n['ip_address'], 7777, clusterName, isOnline) - - def checkStaleCluster(clusterName): - if exists('/sys/kernel/config/cluster/'): - dirs = os.listdir('/sys/kernel/config/cluster/') - for dir in dirs: - if dir != clusterName: - errMsg = '''CloudStack detected there is a stale cluster(%s) on host %s. Please manually clean up it first then add again by -1) remove the host from cloudstack -2) umount all OCFS2 device on host -3) /etc/init.d/o2cb offline %s -4) /etc/init.d/o2cb restart -if this doesn't resolve the problem, please check oracle manual to see how to offline a cluster - ''' % (dir, successToMap(get_master_ip())['ip'], dir) - raise Exception(errMsg) - - try: - checkStaleCluster(clusterName) - nodeString = nodeString.strip(";") - nodes = [] - for n in nodeString.split(";"): - params = n.split(":") - if len(params) != 3: raise Exception("Wrong parameter(%s) in node string(%s)"%(n, nodeString)) - dict = {"number":params[0], "ip_address":params[1], "name":params[2]} - nodes.append(dict) - - if len(nodes) > 255: - raise Exception("%s nodes beyond maximum 255 allowed by OCFS2"%len(nodes)) - - configureHostName(nodes) - configureEtcHosts(nodes) - addNodes(nodes, clusterName) - OvmOCFS2()._start(clusterName) - fd = open(OCFS2_CONF, 'r') - conf = fd.readlines() - fd.close() - logger.debug(OvmStoragePool.prepareOCFS2Nodes, "Configure cluster.conf to:\n%s"%' '.join(conf)) - rs = SUCC() - return rs - - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.prepareOCFS2Nodes, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.prepareOCFS2Nodes), errmsg) - - @staticmethod - def createTemplateFromVolume(secStorageMountPath, installPath, volumePath): - try: - secMountPoint = "" - if not isfile(volumePath): raise Exception("Cannot find %s"%volumePath) - vmCfg = join(dirname(volumePath), 'vm.cfg') - vmName = getVmNameFromConfigureFile(vmCfg) - if vmName in doCmd(['xm', 'list']): - raise Exception("%s is still running, please stop it first then create template again"%vmName) - - tmpUuid = get_uuid() - secMountPoint = join("/var/cloud/", tmpUuid) - OvmStoragePool()._mount(secStorageMountPath, secMountPoint) - installPath = installPath.lstrip('/') - destPath = join(secMountPoint, installPath) - #This prevent us deleting whole secondary in case we got a wrong installPath - if destPath == secMountPoint: raise Exception("Install path equals to root of secondary storage(%s)"%destPath) - if exists(destPath): - logger.warning(OvmStoragePool.createTemplateFromVolume, "%s is already here, delete it since it is most likely stale"%destPath) - doCmd(['rm', '-rf', destPath]) - OvmStoragePool()._checkDirSizeForImage(secMountPoint, volumePath) - - os.makedirs(destPath) - newName = get_uuid() + ".raw" - destName = join(destPath, newName) - doCmd(['cp', volumePath, destName]) - size = os.path.getsize(destName) - resInstallPath = join(installPath, newName) - OvmStoragePool()._umount(secMountPoint) - rs = toGson({"installPath":resInstallPath, "templateFileName":newName, "virtualSize":size, "physicalSize":size}) - return rs - - except Exception, e: - try: - if exists(secMountPoint): - OvmStoragePool()._umount(secMountPoint) - except Exception, e: - logger.warning(OvmStoragePool.createTemplateFromVolume, "umount %s failed"%secMountPoint) - - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.createTemplateFromVolume, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.createTemplateFromVolume), errmsg) - - @staticmethod - def delete(uuid): - try: - sr = OvmStoragePool()._getSrByNameLable(uuid) - primaryStoragePath = sr.mountpoint - OvmStoragePool()._umount(primaryStoragePath) - rs = SUCC() - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.delete, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.delete), errmsg) - - @staticmethod - def copyVolume(secStorageMountPath, volumeFolderOnSecStorage, volumePath, storagePoolUuid, toSec): - def copyToSecStorage(secMountPoint, volumeFolderOnSecStorage, volumePath): - if not isfile(volumePath): raise Exception("Cannot find volume at %s"%volumePath) - OvmStoragePool()._checkDirSizeForImage(secMountPoint, volumePath) - volumeFolderOnSecStorage = volumeFolderOnSecStorage.lstrip("/") - destPath = join(secMountPoint, volumeFolderOnSecStorage) - #This prevent us deleting whole secondary in case we got a wrong volumeFolderOnSecStorage - if destPath == secMountPoint: raise Exception("volume path equals to root of secondary storage(%s)"%destPath) - if exists(destPath): - logger.warning(OvmStoragePool.copyVolume, "%s already exists, delete it first"%destPath) - doCmd(['rm', '-rf', destPath]) - os.makedirs(destPath) - newName = get_uuid() + ".raw" - destName = join(destPath, newName) - doCmd(['cp', volumePath, destName]) - return destName - - def copyToPrimary(secMountPoint, volumeFolderOnSecStorage, volumePath, primaryMountPath): - srcPath = join(secMountPoint, volumeFolderOnSecStorage.lstrip("/"), volumePath.lstrip("/")) - if not srcPath.endswith(".raw"): srcPath = srcPath + ".raw" - if not isfile(srcPath): raise Exception("Cannot find volume at %s"%srcPath) - if not exists(primaryMountPath): raise Exception("Primary storage(%s) seems to have gone"%primaryMountPath) - OvmStoragePool()._checkDirSizeForImage(primaryMountPath, srcPath) - destPath = join(primaryMountPath, "sharedDisk") - newName = get_uuid() + ".raw" - destName = join(destPath, newName) - doCmd(['cp', srcPath, destName]) - return destName - - secMountPoint = "" - try: - tmpUuid = get_uuid() - secMountPoint = join("/var/cloud/", tmpUuid) - OvmStoragePool()._mount(secStorageMountPath, secMountPoint) - if toSec: - resultPath = copyToSecStorage(secMountPoint, volumeFolderOnSecStorage, volumePath) - else: - sr = OvmStoragePool()._getSrByNameLable(storagePoolUuid) - primaryStoragePath = sr.mountpoint - resultPath = copyToPrimary(secMountPoint, volumeFolderOnSecStorage, volumePath, primaryStoragePath) - OvmStoragePool()._umount(secMountPoint) - - # ingratiate bad mgmt server design, it asks 'installPath' but it only wants the volume name without suffix - volumeUuid = basename(resultPath).rstrip(".raw") - rs = toGson({"installPath":volumeUuid}) - return rs - except Exception, e: - try: - if exists(secMountPoint): - OvmStoragePool()._umount(secMountPoint) - except Exception, e: - logger.warning(OvmStoragePool.copyVolume, "umount %s failed"%secMountPoint) - - errmsg = fmt_err_msg(e) - logger.error(OvmStoragePool.copyVolume, errmsg) - raise XmlRpcFault(toErrCode(OvmStoragePool, OvmStoragePool.copyVolume), errmsg) diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVifModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVifModule.py deleted file mode 100755 index 1519843d08d5..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVifModule.py +++ /dev/null @@ -1,65 +0,0 @@ -# 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. -''' -Created on May 17, 2011 - -''' -from OvmCommonModule import * - -class OvmVifDecoder(json.JSONDecoder): - def decode(self, jStr): - deDict = asciiLoads(jStr) - vif = OvmVif() - vif.mac = deDict['mac'] - vif.bridge = deDict['bridge'] - return vif - -class OvmVifEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmVif): raise Exception("%s is not instance of OvmVif"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'mac') - safeDictSet(obj, dct, 'bridge') - safeDictSet(obj, dct, 'type') - safeDictSet(obj, dct, 'name') - return dct - -def fromOvmVif(vif): - return normalizeToGson(json.dumps(vif, cls=OvmVifEncoder)) - -def fromOvmVifList(vifList): - return [fromOvmVif(v) for v in vifList] - -def toOvmVif(jStr): - return json.loads(jStr, cls=OvmVifDecoder) - -def toOvmVifList(jStr): - vifs = [] - for i in jStr: - vif = toOvmVif(i) - vifs.append(vif) - return vifs - -class OvmVif(OvmObject): - name = '' - mac = '' - bridge = '' - type = '' - mode = '' - - def toXenString(self): - return "%s,%s,%s"%(self.mac, self.bridge, self.type) diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVmModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVmModule.py deleted file mode 100755 index e713f623edb1..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVmModule.py +++ /dev/null @@ -1,541 +0,0 @@ -# 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. -''' -Created on May 17, 2011 - -''' -from OvmCommonModule import * -from OvmDiskModule import * -from OvmVifModule import * -from OvmHostModule import OvmHost -from string import Template -from OVSXXenVMConfig import * -from OVSSiteVM import start_vm, stop_vm, reset_vm -from OVSSiteCluster import * -from OvmStoragePoolModule import OvmStoragePool -from OVSXXenStore import xen_get_vm_path, xen_get_vnc_port -from OVSDB import db_get_vm -from OVSXMonitor import xen_get_vm_perf_metrics, xen_get_xm_info -from OVSXXenVM import xen_migrate_vm -from OVSSiteRMVM import unregister_vm, register_vm, set_vm_status -from OVSSiteVMInstall import install_vm_hvm -from OVSSiteRMServer import get_master_ip -from OVSXXenVMInstall import xen_change_vm_cdrom -from OVSXAPIUtil import XenAPIObject, session_login, session_logout - - -logger = OvmLogger("OvmVm") - -class OvmVmDecoder(json.JSONDecoder): - def decode(self, jStr): - deDict = asciiLoads(jStr) - vm = OvmVm() - setAttrFromDict(vm, 'cpuNum', deDict, int) - setAttrFromDict(vm, 'memory', deDict, long) - setattr(vm, 'rootDisk', toOvmDisk(deDict['rootDisk'])) - setattr(vm, 'vifs', toOvmVifList(deDict['vifs'])) - setattr(vm, 'disks', toOvmDiskList(deDict['disks'])) - setAttrFromDict(vm, 'name', deDict) - setAttrFromDict(vm, 'uuid', deDict) - setAttrFromDict(vm, 'bootDev', deDict) - setAttrFromDict(vm, 'type', deDict) - return vm - -class OvmVmEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmVm): raise Exception("%s is not instance of OvmVm"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'cpuNum') - safeDictSet(obj, dct, 'memory') - safeDictSet(obj, dct, 'powerState') - safeDictSet(obj, dct, 'name') - safeDictSet(obj, dct, 'type') - vifs = fromOvmVifList(obj.vifs) - dct['vifs'] = vifs - rootDisk = fromOvmDisk(obj.rootDisk) - dct['rootDisk'] = rootDisk - disks = fromOvmDiskList(obj.disks) - dct['disks'] = disks - return dct - -def toOvmVm(jStr): - return json.loads(jStr, cls=OvmVmDecoder) - -def fromOvmVm(vm): - return normalizeToGson(json.dumps(vm, cls=OvmVmEncoder)) - -class OvmVm(OvmObject): - cpuNum = 0 - memory = 0 - rootDisk = None - vifs = [] - disks = [] - powerState = '' - name = '' - bootDev = '' - type = '' - - def _getVifs(self, vmName): - vmPath = OvmHost()._vmNameToPath(vmName) - domId = OvmHost()._getDomainIdByName(vmName) - vifs = successToMap(xen_get_vifs(vmPath)) - lst = [] - for k in vifs: - v = vifs[k] - vifName = 'vif' + domId + '.' + k[len('vif'):] - vif = OvmVif() - (mac, bridge, type) = v.split(',') - safeSetAttr(vif, 'name', vifName) - safeSetAttr(vif, 'mac', mac) - safeSetAttr(vif, 'bridge', bridge) - safeSetAttr(vif, 'type', type) - lst.append(vif) - - return lst - - def _getVifsFromConfig(self, vmPath): - vifs = successToMap(xen_get_vifs(vmPath)) - lst = [] - for k in vifs: - v = vifs[k] - vif = OvmVif() - (mac, bridge, type) = v.split(',') - safeSetAttr(vif, 'name', k) - safeSetAttr(vif, 'mac', mac) - safeSetAttr(vif, 'bridge', bridge) - safeSetAttr(vif, 'type', type) - lst.append(vif) - return lst - - def _getIsoMountPath(self, vmPath): - vmName = basename(vmPath) - priStoragePath = vmPath.rstrip(join('running_pool', vmName)) - return join(priStoragePath, 'iso_pool', vmName) - - def _getVmTypeFromConfigFile(self, vmPath): - vmType = successToMap(xen_get_vm_type(vmPath))['type'] - return vmType.replace('hvm', 'HVM').replace('para', 'PV') - - def _tapAOwnerFile(self, vmPath): - # Create a file with name convention 'host_ip_address' in vmPath - # Because xm list doesn't return vm that has been stopped, we scan - # primary storage for stopped vm. This file tells us which host it belongs - # to. The file is used in OvmHost.getAllVms() - self._cleanUpOwnerFile(vmPath) - ownerFileName = makeOwnerFileName() - fd = open(join(vmPath, ownerFileName), 'w') - fd.write(ownerFileName) - fd.close() - - def _cleanUpOwnerFile(self, vmPath): - for f in os.listdir(vmPath): - fp = join(vmPath, f) - if isfile(fp) and f.startswith(OWNER_FILE_PREFIX): - os.remove(fp) - - @staticmethod - def create(jsonString): - def dumpCfg(vmName, cfgPath): - cfgFd = open(cfgPath, 'r') - cfg = cfgFd.readlines() - cfgFd.close() - logger.info(OvmVm.create, "Start %s with configure:\n\n%s\n"%(vmName, "".join(cfg))) - - def setVifsType(vifs, type): - for vif in vifs: - vif.type = type - - def hddBoot(vm, vmPath): - vmType = vm.type - if vmType == "FROMCONFIGFILE": - vmType = OvmVm()._getVmTypeFromConfigFile(vmPath) - - cfgDict = {} - if vmType == "HVM": - cfgDict['builder'] = "'hvm'" - cfgDict['acpi'] = "1" - cfgDict['apic'] = "1" - cfgDict['device_model'] = "'/usr/lib/xen/bin/qemu-dm'" - cfgDict['kernel'] = "'/usr/lib/xen/boot/hvmloader'" - vifType = 'ioemu' - else: - cfgDict['bootloader'] = "'/usr/bin/pygrub'" - vifType = 'netfront' - - cfgDict['name'] = "'%s'"%vm.name - cfgDict['disk'] = "[]" - cfgDict['vcpus'] = "''" - cfgDict['memory'] = "''" - cfgDict['on_crash'] = "'destroy'" - cfgDict['on_reboot'] = "'restart'" - cfgDict['vif'] = "[]" - - items = [] - for k in cfgDict.keys(): - item = " = ".join([k, cfgDict[k]]) - items.append(item) - vmSpec = "\n".join(items) - - vmCfg = open(join(vmPath, 'vm.cfg'), 'w') - vmCfg.write(vmSpec) - vmCfg.close() - - setVifsType(vm.vifs, vifType) - raiseExceptionIfFail(xen_set_vcpus(vmPath, vm.cpuNum)) - raiseExceptionIfFail(xen_set_memory(vmPath, BytesToM(vm.memory))) - raiseExceptionIfFail(xen_add_disk(vmPath, vm.rootDisk.path, mode=vm.rootDisk.type)) - vifs = [OvmVif.toXenString(v) for v in vm.vifs] - for vif in vifs: - raiseExceptionIfFail(xen_set_vifs(vmPath, vif)) - - for disk in vm.disks: - raiseExceptionIfFail(xen_add_disk(vmPath, disk.path, mode=disk.type)) - - raiseExceptionIfFail(xen_set_vm_vnc_password(vmPath, "")) - cfgFile = join(vmPath, 'vm.cfg') - # only HVM supports attaching cdrom - if vmType == 'HVM': - # Add an empty "hdc:cdrom" entry in config. Fisrt we set boot order to 'd' that is cdrom boot, - # then 'hdc:cdrom' entry will be in disk list. Second, change boot order to 'c' which - # is harddisk boot. VM can not start with an empty 'hdc:cdrom' when boot order is 'd'. - # it's tricky ! - raiseExceptionIfFail(xen_config_boot_sequence(vmPath, 'd')) - raiseExceptionIfFail(xen_config_boot_sequence(vmPath, 'c')) - - raiseExceptionIfFail(xen_correct_cfg(cfgFile, vmPath)) - xen_correct_qos_cfg(cfgFile) - dumpCfg(vm.name, cfgFile) - server = successToMap(get_master_ip())['ip'] - raiseExceptionIfFail(start_vm(vmPath, server)) - rs = SUCC() - return rs - - def cdBoot(vm, vmPath): - isoMountPath = None - try: - cdrom = None - for disk in vm.disks: - if disk.isIso == True: - cdrom = disk - break - if not cdrom: raise Exception("Cannot find Iso in disks") - - isoOnSecStorage = dirname(cdrom.path) - isoName = basename(cdrom.path) - isoMountPath = OvmVm()._getIsoMountPath(vmPath) - OvmStoragePool()._mount(isoOnSecStorage, isoMountPath) - isoPath = join(isoMountPath, isoName) - if not exists(isoPath): - raise Exception("Cannot found iso %s at %s which mounts to %s"%(isoName, isoOnSecStorage, isoMountPath)) - - stdout = run_cmd(args=['file', isoPath]) - if not stdout.strip().endswith("(bootable)"): raise Exception("ISO %s is not bootable"%cdrom.path) - - #now alter cdrom to correct path - cdrom.path = isoPath - if len(vm.vifs) != 0: - vif = vm.vifs[0] - #ISO boot must be HVM - vifCfg = ','.join([vif.mac, vif.bridge, 'ioemu']) - else: - vifCfg = '' - - rootDiskSize = os.path.getsize(vm.rootDisk.path) - rooDiskCfg = ':'.join([join(vmPath, basename(vm.rootDisk.path)), str(BytesToG(rootDiskSize)), 'True']) - disks = [rooDiskCfg] - for d in vm.disks: - if d.isIso: continue - size = os.path.getsize(d.path) - cfg = ':'.join([d.path, str(BytesToG(size)), 'True']) - disks.append(cfg) - disksCfg = ','.join(disks) - server = successToMap(get_master_ip())['ip'] - - raiseExceptionIfFail(install_vm_hvm(vmPath, BytesToM(vm.memory), vm.cpuNum, vifCfg, disksCfg, cdrom.path, vncpassword='', dedicated_server=server)) - rs = SUCC() - return rs - except Exception, e: - if isoMountPath and OvmStoragePool()._isMounted(isoMountPath): - doCmd(['umount', '-f', isoMountPath]) - errmsg = fmt_err_msg(e) - raise Exception(errmsg) - - try: - vm = toOvmVm(jsonString) - logger.debug(OvmVm.create, "creating vm, spec:%s"%jsonString) - rootDiskPath = vm.rootDisk.path - if not exists(rootDiskPath): raise Exception("Cannot find root disk %s"%rootDiskPath) - - rootDiskDir = dirname(rootDiskPath) - vmPath = join(dirname(rootDiskDir), vm.name) - if not exists(vmPath): - doCmd(['ln', '-s', rootDiskDir, vmPath]) - vmNameFile = open(join(rootDiskDir, 'vmName'), 'w') - vmNameFile.write(vm.name) - vmNameFile.close() - - OvmVm()._tapAOwnerFile(rootDiskDir) - # set the VM to DOWN before starting, OVS agent will check this status - set_vm_status(vmPath, 'DOWN') - if vm.bootDev == "HDD": - return hddBoot(vm, vmPath) - elif vm.bootDev == "CD": - return cdBoot(vm, vmPath) - else: - raise Exception("Unkown bootdev %s for %s"%(vm.bootDev, vm.name)) - - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.create, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.create), errmsg) - - @staticmethod - def stop(vmName): - try: - try: - OvmHost()._getDomainIdByName(vmName) - except NoVmFoundException, e: - logger.info(OvmVm.stop, "vm %s is already stopped"%vmName) - return SUCC() - - logger.info(OvmVm.stop, "Stop vm %s"%vmName) - try: - vmPath = OvmHost()._vmNameToPath(vmName) - except Exception, e: - errmsg = fmt_err_msg(e) - logger.info(OvmVm.stop, "Cannot find link for vm %s on primary storage, treating it as stopped\n %s"%(vmName, errmsg)) - return SUCC() - # set the VM to RUNNING before stopping, OVS agent will check this status - set_vm_status(vmPath, 'RUNNING') - raiseExceptionIfFail(stop_vm(vmPath)) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.stop, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.stop), errmsg) - - @staticmethod - def reboot(vmName): - try: - #=================================================================== - # Xend has a bug of reboot. If reboot vm too quick, xend return success - # but actually it refused reboot (seen from log) - # vmPath = successToMap(xen_get_vm_path(vmName))['path'] - # raiseExceptionIfFail(reset_vm(vmPath)) - #=================================================================== - vmPath = OvmHost()._vmNameToPath(vmName) - OvmVm.stop(vmName) - raiseExceptionIfFail(start_vm(vmPath)) - vncPort= successToMap(xen_get_vnc_port(vmName))['vnc_port'] - logger.info(OvmVm.stop, "reboot vm %s, new vncPort is %s"%(vmName, vncPort)) - return toGson({"vncPort":str(vncPort)}) - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.reboot, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.reboot), errmsg) - - @staticmethod - def getDetails(vmName): - try: - vm = OvmVm() - - try: - OvmHost()._getDomainIdByName(vmName) - vmPath = OvmHost()._vmNameToPath(vmName) - vifsFromConfig = False - except NoVmFoundException, e: - vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName) - vifsFromConfig = True - - - if not isdir(vmPath): - # The case is, when vm starting was not completed at primaryStorageDownload or createVolume(e.g. mgmt server stop), the mgmt - # server will keep vm state in staring, then a stop command will be sent. The stop command will delete bridges that vm attaches, - # by retriving birdge info by OvmVm.getDetails(). In this case, the vm doesn't exists, so returns a fake object here. - fakeDisk = OvmDisk() - vm.rootDisk = fakeDisk - else: - if vifsFromConfig: - vm.vifs.extend(vm._getVifsFromConfig(vmPath)) - else: - vm.vifs.extend(vm._getVifs(vmName)) - - safeSetAttr(vm, 'name', vmName) - disks = successToMap(xen_get_vdisks(vmPath))['vdisks'].split(',') - rootDisk = None - #BUG: there is no way to get type of disk, assume all are "w" - for d in disks: - if vmName in d: - rootDisk = OvmDisk() - safeSetAttr(rootDisk, 'path', d) - safeSetAttr(rootDisk, 'type', "w") - continue - disk = OvmDisk() - safeSetAttr(disk, 'path', d) - safeSetAttr(disk, 'type', "w") - vm.disks.append(disk) - if not rootDisk: raise Exception("Cannot find root disk for vm %s"%vmName) - safeSetAttr(vm, 'rootDisk', rootDisk) - vcpus = int(successToMap(xen_get_vcpus(vmPath))['vcpus']) - safeSetAttr(vm, 'cpuNum', vcpus) - memory = MtoBytes(int(successToMap(xen_get_memory(vmPath))['memory'])) - safeSetAttr(vm, 'memory', memory) - vmStatus = db_get_vm(vmPath) - safeSetAttr(vm, 'powerState', vmStatus['status']) - vmType = successToMap(xen_get_vm_type(vmPath))['type'].replace('hvm', 'HVM').replace('para', 'PV') - safeSetAttr(vm, 'type', vmType) - - rs = fromOvmVm(vm) - logger.info(OvmVm.getDetails, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.getDetails, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.getDetails), errmsg) - - @staticmethod - def getVmStats(vmName): - def getVcpuNumAndUtils(): - try: - session = session_login() - refs = session.xenapi.VM.get_by_name_label(vmName) - if len(refs) == 0: - raise Exception("No ref for %s found in xenapi VM objects"%vmName) - vm = XenAPIObject('VM', session, refs[0]) - VM_metrics = XenAPIObject("VM_metrics", session, vm.get_metrics()) - items = VM_metrics.get_VCPUs_utilisation().items() - nvCpus = len(items) - if nvCpus == 0: - raise Exception("vm %s has 0 vcpus !!!"%vmName) - - xmInfo = successToMap(xen_get_xm_info()) - nCpus = int(xmInfo['nr_cpus']) - totalUtils = 0.0 - # CPU utlization of VM = (total cpu utilization of each vcpu) / number of physical cpu - for num, util in items: - totalUtils += float(util) - avgUtils = float(totalUtils/nCpus) * 100 - return (nvCpus, avgUtils) - finally: - session_logout() - - - try: - try: - OvmHost()._getDomainIdByName(vmName) - vmPath = OvmHost()._vmNameToPath(vmName) - (nvcpus, avgUtils) = getVcpuNumAndUtils() - vifs = successToMap(xen_get_vifs(vmPath)) - rxBytes = 0 - txBytes = 0 - vifs = OvmVm()._getVifs(vmName) - for vif in vifs: - rxp = join('/sys/class/net', vif.name, 'statistics/rx_bytes') - txp = join("/sys/class/net/", vif.name, "statistics/tx_bytes") - if not exists(rxp): raise Exception('can not find %s'%rxp) - if not exists(txp): raise Exception('can not find %s'%txp) - rxBytes += long(doCmd(['cat', rxp])) / 1000 - txBytes += long(doCmd(['cat', txp])) / 1000 - except NoVmFoundException, e: - vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName) - nvcpus = int(successToMap(xen_get_vcpus(vmPath))['vcpus']) - avgUtils = 0 - rxBytes = 0 - txBytes = 0 - - rs = toGson({"cpuNum":nvcpus, "cpuUtil":avgUtils, "rxBytes":rxBytes, "txBytes":txBytes}) - logger.debug(OvmVm.getVmStats, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.getVmStats, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.getVmStats), errmsg) - - @staticmethod - def migrate(vmName, targetHost): - try: - vmPath = OvmHost()._vmNameToPath(vmName) - raiseExceptionIfFail(xen_migrate_vm(vmPath, targetHost)) - unregister_vm(vmPath) - OvmVm()._cleanUpOwnerFile(vmPath) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.migrate, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.migrate), errmsg) - - @staticmethod - def register(vmName): - try: - vmPath = OvmHost()._vmNameToPath(vmName) - raiseExceptionIfFail(register_vm(vmPath)) - OvmVm()._tapAOwnerFile(vmPath) - vncPort= successToMap(xen_get_vnc_port(vmName))['vnc_port'] - rs = toGson({"vncPort":str(vncPort)}) - logger.debug(OvmVm.register, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.register, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.register), errmsg) - - @staticmethod - def getVncPort(vmName): - try: - vncPort= successToMap(xen_get_vnc_port(vmName))['vnc_port'] - rs = toGson({"vncPort":vncPort}) - logger.debug(OvmVm.getVncPort, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.getVncPort, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.getVncPort), errmsg) - - @staticmethod - def detachOrAttachIso(vmName, iso, isAttach): - try: - if vmName in OvmHost.getAllVms(): - scope = 'both' - vmPath = OvmHost()._vmNameToPath(vmName) - else: - scope = 'cfg' - vmPath = OvmHost()._getVmPathFromPrimaryStorage(vmName) - - vmType = OvmVm()._getVmTypeFromConfigFile(vmPath) - if vmType != 'HVM': - raise Exception("Only HVM supports attaching/detaching ISO") - - if not isAttach: - iso = '' - else: - isoName = basename(iso) - isoMountPoint = OvmVm()._getIsoMountPath(vmPath) - isoOnSecStorage = dirname(iso) - OvmStoragePool()._mount(isoOnSecStorage, isoMountPoint) - iso = join(isoMountPoint, isoName) - - exceptionIfNoSuccess(xen_change_vm_cdrom(vmPath, iso, scope)) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVm.detachOrAttachIso, errmsg) - raise XmlRpcFault(toErrCode(OvmVm, OvmVm.detachOrAttachIso), errmsg) - -if __name__ == "__main__": - import sys - print OvmVm.getDetails(sys.argv[1]) - #print OvmVm.getVmStats(sys.argv[1]) diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVolumeModule.py b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVolumeModule.py deleted file mode 100755 index d2152b1c806a..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/OvmVolumeModule.py +++ /dev/null @@ -1,155 +0,0 @@ -# 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. -''' -Created on June 2, 2011 - -''' -from OvmCommonModule import * -from OvmStoragePoolModule import OvmStoragePool -from OVSXUtility import xen_create_disk -from OvmHostModule import OvmHost -import os - -logger = OvmLogger("OvmVolume") - -class OvmVolumeDecoder(json.JSONDecoder): - def decode(self, jStr): - deDict = asciiLoads(jStr) - vol = OvmVolume() - setAttrFromDict(vol, 'uuid', deDict) - setAttrFromDict(vol, 'size', deDict, long) - setAttrFromDict(vol, 'poolUuid', deDict) - return vol - -class OvmVolumeEncoder(json.JSONEncoder): - def default(self, obj): - if not isinstance(obj, OvmVolume): raise Exception("%s is not instance of OvmVolume"%type(obj)) - dct = {} - safeDictSet(obj, dct, 'name') - safeDictSet(obj, dct, 'uuid') - safeDictSet(obj, dct, 'poolUuid') - safeDictSet(obj, dct, 'path') - safeDictSet(obj, dct, 'size') - return dct - -def toOvmVolume(jStr): - return json.loads(jStr, cls=OvmVolumeDecoder) - -def fromOvmVolume(vol): - return normalizeToGson(json.dumps(vol, cls=OvmVolumeEncoder)) - -class OvmVolume(OvmObject): - name = '' - uuid = '' - poolUuid = '' - path = '' - size = 0 - - @staticmethod - def createDataDisk(poolUuid, size, isRoot): - try: - vol = OvmVolume() - vol.size = long(size) - vol.poolUuid = poolUuid - pool = OvmStoragePool() - sr = pool._getSrByNameLable(vol.poolUuid) - if isRoot: - path = join(sr.mountpoint, 'running_pool', get_uuid()) - else: - path = join(sr.mountpoint, 'shareDisk') - if not exists(path): os.makedirs(path) - freeSpace = pool._getSpaceinfoOfDir(path) - if freeSpace < vol.size: - raise Exception("%s has not enough space (available:%s, required:%s"%(path, freeSpace, vol.size)) - - vol.uuid = get_uuid() - vol.name = vol.uuid + '.raw' - filePath = join(path, vol.name) - exceptionIfNoSuccess(xen_create_disk(filePath, BytesToM(vol.size)), "Create datadisk %s failed"%filePath) - vol.path = filePath - rs = fromOvmVolume(vol) - logger.debug(OvmVolume.createDataDisk, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVolume.createDataDisk, errmsg) - raise XmlRpcFault(toErrCode(OvmVolume, OvmVolume.createDataDisk, errmsg)) - - @staticmethod - def createFromTemplate(poolUuid, templateUrl): - try: - if not exists(templateUrl): - raise Exception("Cannot find template:%s"%templateUrl) - sr = OvmStoragePool()._getSrByNameLable(poolUuid) - volDirUuid = get_uuid() - volUuid = get_uuid() - priStorageMountPoint = sr.mountpoint - volDir = join(priStorageMountPoint, 'running_pool', volDirUuid) - if exists(volDir): - raise Exception("Volume dir %s already existed, can not override"%volDir) - os.makedirs(volDir) - OvmStoragePool()._checkDirSizeForImage(volDir, templateUrl) - volName = volUuid + '.raw' - tgt = join(volDir, volName) - cpVolCmd = ['cp', templateUrl, tgt] - doCmd(cpVolCmd) - volSize = os.path.getsize(tgt) - vol = OvmVolume() - vol.name = volName - vol.path = tgt - vol.size = volSize - vol.uuid = volUuid - vol.poolUuid = poolUuid - rs = fromOvmVolume(vol) - logger.debug(OvmVolume.createFromTemplate, rs) - return rs - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVolume.createFromTemplate, errmsg) - raise XmlRpcFault(toErrCode(OvmVolume, OvmVolume.createFromTemplate), errmsg) - - @staticmethod - def destroy(poolUuid, path): - try: - OvmStoragePool()._getSrByNameLable(poolUuid) - if not exists(path): raise Exception("Cannot find %s"%path) - dir = dirname(path) - if exists(join(dir, 'vm.cfg')): - # delete root disk - vmNamePath = join(dir, 'vmName') - if exists(vmNamePath): - vmNameFd = open(vmNamePath, 'r') - vmName = vmNameFd.readline() - vmName = vmName.rstrip('\n') - link = join(dirname(dir), vmName) - doCmd(['rm', '-rf', link]) - vmNameFd.close() - else: - logger.warning(OvmVolume.destroy, "Can not find vmName file in %s"%dir) - doCmd(['rm','-rf', dir]) - else: - doCmd(['rm', path]) - return SUCC() - except Exception, e: - errmsg = fmt_err_msg(e) - logger.error(OvmVolume.destroy, errmsg) - raise XmlRpcFault(toErrCode(OvmVolume, OvmVolume.destroy), errmsg) - - - -if __name__ == "__main__": - print OvmVolume.detachOrAttachIso(sys.argv[1], '', False) diff --git a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/configureOvm.sh b/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/configureOvm.sh deleted file mode 100755 index ccd1704b3225..000000000000 --- a/plugins/hypervisors/ovm/src/main/scripts/vm/hypervisor/ovm/configureOvm.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/bin/sh -# 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. - -errExit() { - echo $@ - exit 1 -} - -stopHeartbeat() { - pidFile="/var/run/ovs-agent/heartbeat.pid" - if [ -f $pidFile ]; then - pid=`cat $pidFile` - ps -p $pid &>/dev/null - if [ $? -eq 0 ]; then - kill $pid &>/dev/null - fi - fi -} - -openPortOnIptables() { - port="$1" - protocol="$2" - chkconfig --list iptables | grep "on" - if [ $? -eq 0 ]; then - iptables-save | grep "A INPUT -p $protocol -m $protocol --dport $port -j ACCEPT" >/dev/null - if [ $? -ne 0 ]; then - iptables -I INPUT 1 -p $protocol --dport $port -j ACCEPT - if [ $? -ne 0 ]; then - exit_with_error "iptables -I INPUT 1 -p $protocol --dport $port -j ACCEPT failed" - fi - echo "iptables:Open $protocol port $port for DHCP" - fi - fi -} - -applyPatch() { - patchFile="$1" - level="$2" - - [ ! -f $patchFile ] && errExit "Can not find $patchFile" - - if [ $? -ne 0 ]; then - pushd /opt/ovs-agent-latest &>/dev/null - test=`patch -p$level --dry-run -N < $patchFile` - if [ $? -ne 0 ]; then - tmp=`mktemp` - echo $test > $tmp - grep "Reversed (or previously applied) patch detected" $tmp &>/dev/null - if [ $? -eq 0 ]; then - # The file has been patched - rm $tmp -f - popd &>/dev/null - return - else - rm $tmp -f - popd &>/dev/null - errExit "Can not apply $patchFile beacuse $test" - fi - fi - patch -p$level < $patchFile - [ $? -ne 0 ] && errExit "Patch to $target failed" - popd &>/dev/null - fi -} - -postSetup() { - openPortOnIptables 7777 tcp # for OCFS2, maybe tcp only - openPortOnIptables 7777 udp - openPortOnIptables 3260 tcp # for ISCSI, maybe tcp only - openPortOnIptables 3260 udp - applyPatch "/opt/ovs-agent-latest/OvmPatch.patch" 2 - applyPatch "/opt/ovs-agent-latest/OvmDontTouchOCFS2ClusterWhenAgentStart.patch" 1 - applyPatch "/opt/ovs-agent-latest/Fixget_storage_reposExceptionDueToWrongReturnValueCheck.patch" 1 - - stopHeartbeat - - /etc/init.d/ovs-agent restart --disable-nowayout - [ $? -ne 0 ] && errExit "Restart ovs agent failed" - exit 0 -} - -preSetup() { - agentConfig="/etc/ovs-agent/agent.ini" - agentInitScript="/etc/init.d/ovs-agent" - - [ ! -f $agentConfig ] && errExit "Can not find $agentConfig" - [ ! -f $agentInitScript ] && errExit "Can not find $agentInitScript" - - version=`grep "version=" $agentInitScript | cut -d "=" -f 2` - [ x"$version" != x"2.3" ] && errExit "The OVS agent version is $version, we only support 2.3 now" - - # disable SSL - sed -i 's/ssl=enable/ssl=disable/g' $agentConfig - [ $? -ne 0 ] && errExit "configure ovs agent to non ssl failed" - - if [ ! -L /opt/ovs-agent-latest ]; then - eval $agentInitScript status | grep 'down' && $agentInitScript start - [ $? -ne 0 ] && errExit "Start ovs agent failed" - [ ! -L /opt/ovs-agent-latest ] && errExit "No link at /opt/ovs-agent-latest" - fi - exit 0 -} - -[ $# -ne 1 ] && errExit "Usage: configureOvm.sh command" - -case "$1" in - preSetup) - preSetup - ;; - postSetup) - postSetup - ;; - *) - errExit "Valid commands: preSetup postSetup" -esac diff --git a/plugins/hypervisors/ovm3/.gitignore b/plugins/hypervisors/ovm3/.gitignore deleted file mode 100644 index ae3c1726048c..000000000000 --- a/plugins/hypervisors/ovm3/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/plugins/hypervisors/ovm3/pom.xml b/plugins/hypervisors/ovm3/pom.xml deleted file mode 100644 index 4214ee8a71b3..000000000000 --- a/plugins/hypervisors/ovm3/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - 4.0.0 - cloud-plugin-hypervisor-ovm3 - Apache CloudStack Plugin - Hypervisor OracleVM3 - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - org.apache.xmlrpc - xmlrpc-client - ${cs.xmlrpc.version} - - - org.apache.xmlrpc - xmlrpc-common - ${cs.xmlrpc.version} - - - org.apache.commons - commons-lang3 - ${cs.commons-lang3.version} - - - org.apache.logging.log4j - log4j-core - - - org.apache.logging.log4j - log4j-api - - - - - - - maven-surefire-plugin - - true - - - - - - - - integration - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - integration-test - verify - - - - - - - - - diff --git a/plugins/hypervisors/ovm3/sonar-project.properties b/plugins/hypervisors/ovm3/sonar-project.properties deleted file mode 100644 index 7cc3a41f2a5f..000000000000 --- a/plugins/hypervisors/ovm3/sonar-project.properties +++ /dev/null @@ -1,36 +0,0 @@ -# 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. - -# Required metadata -sonar.projectKey=cloud-plugin-hypervisor-ovm3 -sonar.projectName=Ovm3 integration for CS -sonar.projectVersion=1.0 - -# Comma-separated paths to directories with sources (required) -sonar.sources=src -sonar.binaries=target/classes - -# Exclusions -sonar.exclusions=**/*Test.java - -# Language -sonar.language=java - -# Encoding of the source files -sonar.sourceEncoding=UTF-8 - -# sonar.doxygen.generateDocumentation=enable diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/ha/Ovm3Investigator.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/ha/Ovm3Investigator.java deleted file mode 100644 index a24ff3b1d364..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/ha/Ovm3Investigator.java +++ /dev/null @@ -1,81 +0,0 @@ -// 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.ha; - -import java.util.List; - -import javax.inject.Inject; - - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckOnHostCommand; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor; -import com.cloud.resource.ResourceManager; -import com.cloud.utils.component.AdapterBase; - -public class Ovm3Investigator extends AdapterBase implements Investigator { - @Inject - HostDao hostDao; - @Inject - AgentManager agentMgr; - @Inject - ResourceManager resourceMgr; - - @Override - public boolean isVmAlive(com.cloud.vm.VirtualMachine vm, Host host) throws UnknownVM { - logger.debug("isVmAlive: " + vm.getHostName() + " on " + host.getName()); - if (host.getHypervisorType() != Hypervisor.HypervisorType.Ovm3) { - throw new UnknownVM(); - } - Status status = isAgentAlive(host); - if (status == null) { - return false; - } - return status == Status.Up ? true : false; - } - - @Override - public Status isAgentAlive(Host agent) { - logger.debug("isAgentAlive: " + agent.getName()); - if (agent.getHypervisorType() != Hypervisor.HypervisorType.Ovm3) { - return null; - } - CheckOnHostCommand cmd = new CheckOnHostCommand(agent); - List neighbors = resourceMgr.listHostsInClusterByStatus(agent.getClusterId(), Status.Up); - for (HostVO neighbor : neighbors) { - if (neighbor.getId() == agent.getId() || neighbor.getHypervisorType() != Hypervisor.HypervisorType.Ovm3) { - continue; - } - try { - Answer answer = agentMgr.easySend(neighbor.getId(), cmd); - if (answer != null) { - return answer.getResult() ? Status.Down : Status.Up; - } - } catch (Exception e) { - logger.error("Failed to send command to host: " + neighbor.getId(), e); - } - } - - return null; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/CloudstackPlugin.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/CloudstackPlugin.java deleted file mode 100644 index 298420a04b2a..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/CloudstackPlugin.java +++ /dev/null @@ -1,183 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.HashMap; -import java.util.Map; - - -public class CloudstackPlugin extends OvmObject { - private boolean checkstoragestarted = false; - public CloudstackPlugin(Connection c) { - setClient(c); - } - - public String getVncPort(String vmName) throws Ovm3ResourceException { - return (String) callWrapper("get_vncport", vmName); - } - - public boolean ovsUploadSshKey(String key, String content) throws Ovm3ResourceException{ - return nullIsFalseCallWrapper("ovs_upload_ssh_key", key, content); - } - - public boolean ovsUploadFile(String path, String file, String content) throws Ovm3ResourceException { - return nullIsFalseCallWrapper("ovs_upload_file", path, file, content); - } - - public boolean ovsDomrUploadFile(String domr, String path, String file, - String content) throws Ovm3ResourceException { - return nullIsFalseCallWrapper("ovs_domr_upload_file", domr, path, file, - content); - } - - public class ReturnCode { - private Map returnCode = new HashMap() { - { - put("rc", null); - put("exit", null); - put("err", null); - put("out", null); - } - private static final long serialVersionUID = 5L; - }; - public ReturnCode() { - } - - public void setValues(Map m) { - returnCode.putAll(m); - } - - public Boolean getRc() throws Ovm3ResourceException { - Object rc = returnCode.get("rc"); - Long c = 1L; - if (rc instanceof Integer) { - c = new Long((Integer) rc); - } else if (rc instanceof Long) { - c = (Long) rc; - } else { - logger.debug("Incorrect return code: " + rc); - return false; - } - returnCode.put("exit", c); - if (c != 0) { - return false; - } - return true; - } - - public String getStdOut() { - return (String) returnCode.get("out"); - } - - public String getStdErr() { - return (String) returnCode.get("err"); - } - - public Integer getExit() { - if (returnCode.get("exit") == null) { - returnCode.put("exit", returnCode.get("rc")); - } - return ((Long) returnCode.get("exit")).intValue(); - } - } - - public ReturnCode domrExec(String ip, String cmd) throws Ovm3ResourceException { - ReturnCode rc = new ReturnCode(); - rc.setValues((Map) callWrapper("exec_domr", ip, cmd)); - return rc; - } - - /** - * Checks a tcp port of a host reachable from dom0 - * @param ip - * @param port - * @param retries - * @param interval - * @return - * @throws Ovm3ResourceException - */ - public boolean dom0CheckPort(String ip, Integer port, Integer retries, - Integer interval) throws Ovm3ResourceException { - Boolean x = false; - /* should deduct the interval from the timeout and sleep on it */ - Integer sleep = interval; - try { - while (!x && retries > 0) { - x = nullIsFalseCallWrapper("check_dom0_port", ip, port, interval); - retries--; - Thread.sleep(sleep * 1000); - } - } catch (Exception e) { - logger.error("Dom0 port check failed: " + e); - } - return x; - } - - public Map ovsDom0Stats(String bridge) throws Ovm3ResourceException { - return (Map) callWrapper( - "ovs_dom0_stats", bridge); - } - - public Map ovsDomUStats(String domain) throws Ovm3ResourceException { - return (Map) callWrapper( - "ovs_domU_stats", domain); - } - - public boolean domrCheckPort(String ip, Integer port) throws Ovm3ResourceException{ - return (Boolean) callWrapper("check_domr_port", ip, port); - } - - public boolean domrCheckSsh(String ip) throws Ovm3ResourceException { - return (Boolean) callWrapper("check_domr_ssh", ip); - } - - public boolean ovsControlInterface(String dev, String cidr) throws Ovm3ResourceException { - return (Boolean) callWrapper("ovs_control_interface", dev, cidr); - } - - public boolean ping(String host) throws Ovm3ResourceException { - return (Boolean) callWrapper("ping", host); - } - - public boolean ovsCheckFile(String file) throws Ovm3ResourceException { - return (Boolean) callWrapper("ovs_check_file", file); - } - - public boolean dom0HasIp(String ovm3PoolVip) throws Ovm3ResourceException { - return (Boolean) callWrapper("check_dom0_ip", ovm3PoolVip); - } - public boolean dom0CheckStorageHealthCheck(String path, String script, String guid, Integer timeout, Integer interval) throws Ovm3ResourceException { - Object[] x = (Object[]) callWrapper("check_dom0_storage_health_check", path, script, guid, timeout, interval); - Boolean running = (Boolean) x[0]; - checkstoragestarted = (Boolean) x[1]; - return running; - } - public boolean dom0CheckStorageHealthCheck() { - return checkstoragestarted; - } - /* return something else in the future */ - public boolean dom0CheckStorageHealth(String path, String script, String guid, Integer timeout) throws Ovm3ResourceException { - return (Boolean) callWrapper("check_dom0_storage_health", path, script, guid, timeout); - } - public boolean ovsMkdirs(String dir) throws Ovm3ResourceException{ - return nullIsTrueCallWrapper("ovs_mkdirs", dir); - } - public boolean ovsMkdirs(String dir, Integer mode) throws Ovm3ResourceException{ - return nullIsTrueCallWrapper("ovs_mkdirs", dir, mode); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Cluster.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Cluster.java deleted file mode 100644 index 0d108069388c..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Cluster.java +++ /dev/null @@ -1,126 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -public class Cluster extends OvmObject { - public Cluster(Connection c) { - setClient(c); - } - - /* - * leave_cluster, argument: - * self - default: None argument: poolfsUuid - default: None - */ - public Boolean leaveCluster(String poolfsUuid) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("leave_cluster", poolfsUuid); - } - - /* - * configure_server_for_cluster, argument: self - default: None <( ? - * argument: o2cb_conf - default: None <( ? argument: clusterConf - default: - * None <( ? argument: poolfs_type - default: None argument: poolfs_target - - * default: None argument: poolfsUuid - default: None argument: - * poolfs_nfsbase_uuid - default: None - */ - public Boolean configureServerForCluster(String poolfsUuid) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("configure_server_for_cluster", poolfsUuid); - } - - /* - * deconfigure_server_for_cluster, argument: self - default: None - * argument: poolfsUuid - default: None - */ - public Boolean deconfigureServerForCluster(String poolfsUuid) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("deconfigure_server_for_cluster", poolfsUuid); - } - - /* - * join_cluster, argument: self - * - default: None argument: poolfsUuid - default: None - */ - public Boolean joinCLuster(String poolfsUuid) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("join_cluster", poolfsUuid); - } - - /* - * discover_cluster, argument: - * self - default: None - */ - /* - * < - * 61 - * 2000 - * 2000 - * ba9aaf00ae5e2d73 - * 60000 - * true o2cb - * - * ba9aaf00ae5e2d73 1 - * global - * - * 0004FB0000050000E70FBDDEB802208F - * ba9aaf00ae5e2d73 - * 0 7777 - * 192.168.1.64 ovm-1 - * ba9aaf00ae5e2d73 - * - */ - /* TODO: Intepret existing clusters... */ - public Boolean discoverCluster() throws Ovm3ResourceException { - return nullIsTrueCallWrapper("discover_cluster"); - } - - /* - * update_clusterConfiguration, - * argument: self - default: None argument: cluster_conf - default: None <( - * ? cluster_conf can be a "dict" or a plain file: print - * primary.update_clusterConfiguration( - * "heartbeat:\n\tregion = 0004FB0000050000E70FBDDEB802208F\n\tcluster = ba9aaf00ae5e2d72\n\nnode:\n\tip_port = 7777\n\tip_address = 192.168.1.64\n\tnumber = 0\n\tname = ovm-1\n\tcluster = ba9aaf00ae5e2d72\n\nnode:\n\tip_port = 7777\n\tip_address = 192.168.1.65\n\tnumber = 1\n\tname = ovm-2\n\tcluster = ba9aaf00ae5e2d72\n\ncluster:\n\tnode_count = 2\n\theartbeat_mode = global\n\tname = ba9aaf00ae5e2d72\n" - * ) - */ - public Boolean updateClusterConfiguration(String clusterConf) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("update_clusterConfiguration", clusterConf); - } - - /* - * destroy_cluster, argument: - * self - default: None argument: poolfsUuid - default: None - */ - public Boolean destroyCluster(String poolfsUuid) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("destroy_cluster", poolfsUuid); - } - - /* - * is_cluster_online, argument: - * self - default: None - */ - public Boolean isClusterOnline() throws Ovm3ResourceException { - Object x = callWrapper("is_cluster_online"); - return Boolean.valueOf(x.toString()); - } - - /* - * create_cluster, argument: - * self - default: None argument: poolfsUuid - default: None - */ - public Boolean createCluster(String poolfsUuid) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("create_cluster", poolfsUuid); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Common.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Common.java deleted file mode 100644 index 59a2af68fe06..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Common.java +++ /dev/null @@ -1,60 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -public class Common extends OvmObject { - public Common(Connection c) { - setClient(c); - } - - /* - * get_api_version, - */ - public Integer getApiVersion() throws Ovm3ResourceException { - Object[] x = (Object[]) callWrapper("get_api_version"); - return (Integer) x[0]; - } - - /* - * sleep, argument: secs - default: None - */ - public Boolean sleep(int seconds) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("sleep", seconds); - } - - /* - * dispatch, argument: uri - default: None - * argument: func - default: None - */ - /* - * normally used to push commands to other hosts in a cluster: * dispatch - * function join_server_pool to server - * https://oracle:******@192.168.1.67:8899/api/3/ - */ - public String dispatch(String url, String function, T... args) throws Ovm3ResourceException { - return callString("dispatch", url, function, args); - } - - /* - * echo, argument: msg - default: None - */ - public String echo(String msg) throws Ovm3ResourceException { - return callString("echo", msg); - } - -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Connection.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Connection.java deleted file mode 100644 index c43d36c934b1..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Connection.java +++ /dev/null @@ -1,196 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.TimeZone; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.apache.xmlrpc.XmlRpcException; -import org.apache.xmlrpc.client.TimingOutCallback; -import org.apache.xmlrpc.client.XmlRpcClient; -import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; -import org.apache.xmlrpc.client.XmlRpcClientRequestImpl; - -public class Connection extends XmlRpcClient { - protected Logger logger = LogManager.getLogger(getClass()); - private final XmlRpcClientConfigImpl xmlClientConfig = new XmlRpcClientConfigImpl(); - private XmlRpcClient xmlClient; - private String hostUser = null; - private String hostPass = null; - private String hostIp; - private String hostName; - private Integer hostPort = 8899; - private Boolean hostUseSsl = false; - private String cert = ""; - private String key = ""; - /* default to 20 mins ? */ - private Integer timeoutMs = 1200; - private Integer timeoutS = timeoutMs * 1000; - - public Connection() { - } - - public Connection(String ip, Integer port, String username, String password) { - hostIp = ip; - hostPort = port; - hostUser = username; - hostPass = password; - xmlClient = setupXmlClient(); - } - - public Connection(String ip, String username, String password) { - hostIp = ip; - hostUser = username; - hostPass = password; - xmlClient = setupXmlClient(); - } - - private XmlRpcClient setupXmlClient() { - final XmlRpcClient client = new XmlRpcClient(); - - URL url; - try { - /* TODO: should add SSL checking here! */ - String prot = "http"; - if (hostUseSsl) { - prot = "https"; - } - url = new URL(prot + "://" + hostIp + ":" + hostPort.toString()); - xmlClientConfig.setTimeZone(TimeZone.getTimeZone("UTC")); - xmlClientConfig.setServerURL(url); - /* disable, we use asyncexecute to control timeout */ - xmlClientConfig.setReplyTimeout(0); - /* default to 60 secs */ - xmlClientConfig.setConnectionTimeout(60000); - /* reply time is 5 mins */ - xmlClientConfig.setReplyTimeout(60 * 15000); - if (hostUser != null && hostPass != null) { - logger.debug("Setting username " + hostUser); - xmlClientConfig.setBasicUserName(hostUser); - xmlClientConfig.setBasicPassword(hostPass); - } - xmlClientConfig.setXmlRpcServer(null); - client.setConfig(xmlClientConfig); - client.setTypeFactory(new RpcTypeFactory(client)); - } catch (MalformedURLException e) { - logger.info("Incorrect URL: ", e); - } - return client; - } - - public Object call(String method, List params) throws XmlRpcException { - return callTimeoutInSec(method, params, this.timeoutS); - } - - public Object call(String method, List params, boolean debug) - throws XmlRpcException { - return callTimeoutInSec(method, params, this.timeoutS, debug); - } - - public Object callTimeoutInSec(String method, List params, int timeout, - boolean debug) throws XmlRpcException { - TimingOutCallback callback = new TimingOutCallback(timeout * 1000); - if (debug) { - logger.debug("Call Ovm3 agent " + hostName + "(" + hostIp +"): " + method - + " with " + params); - } - long startTime = System.currentTimeMillis(); - try { - /* returns actual xml */ - XmlRpcClientRequestImpl req = new XmlRpcClientRequestImpl( - xmlClient.getClientConfig(), method, params); - xmlClient.executeAsync(req, callback); - return callback.waitForResponse(); - } catch (TimingOutCallback.TimeoutException e) { - logger.info("Timeout: ", e); - throw new XmlRpcException(e.getMessage()); - } catch (XmlRpcException e) { - logger.info("XML RPC Exception occurred: ", e); - throw e; - } catch (RuntimeException e) { - logger.info("Runtime Exception: ", e); - throw new XmlRpcException(e.getMessage()); - } catch (Throwable e) { - logger.error("Holy crap batman!: ", e); - throw new XmlRpcException(e.getMessage(), e); - } finally { - long endTime = System.currentTimeMillis(); - /* in seconds */ - float during = (endTime - startTime) / (float) 1000; - logger.debug("Ovm3 call " + method + " finished in " + during - + " secs, on " + hostIp + ":" + hostPort); - } - } - - public Object callTimeoutInSec(String method, List params, int timeout) - throws XmlRpcException { - return callTimeoutInSec(method, params, timeout, true); - } - - public String getIp() { - return hostIp; - } - - public Integer getPort() { - return hostPort; - } - - public String getUserName() { - return hostUser; - } - - public void setUserName(String s) { - hostUser = s; - } - - public String getPassword() { - return hostPass; - } - - public Boolean getUseSsl() { - return hostUseSsl; - } - - public String getCert() { - return cert; - } - - public String getKey() { - return key; - } - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public void setIp(String agentIp) { - hostIp = agentIp; - } - - public void setPassword(String agentPassword) { - hostPass = agentPassword; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Linux.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Linux.java deleted file mode 100644 index 50e2574eb54b..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Linux.java +++ /dev/null @@ -1,454 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.w3c.dom.Document; - -public class Linux extends OvmObject { - private static final String DEVICE = "Device"; - private static final String REMOTEDIR = "Remote_Dir"; - private static final String MOUNTPOINT = "Mount_Point"; - private Integer initMaps = 1; - - /** - * use capabilities to match things later, perhaps also hardware discovery ? - * wrap getters and setters.... for Mapps... - */ - private Map ovmCapabilities = new HashMap(); - /** - * MAX_CONCURRENT_MIGRATION_IN=1, ALL_VM_CPU_OVERSUBSCRIBE=True, - * HIGH_AVAILABILITY=True, LOCAL_STORAGE_ELEMENT=True, NFS=True, - * MTU_CONFIGURATION=True, CONCURRENT_MIGRATION=False, - * VM_MEMORY_ALIGNMENT=1048576, CLUSTERS=True, VM_SUSPEND=True, - * BOND_MODE_LINK_AGGREGATION=True, YUM_PACKAGE_MANAGEMENT=True, - * VM_VNC_CONSOLE=True, BOND_MODE_ACTIVE_BACKUP=True, - * MAX_CONCURRENT_MIGRATION_OUT=1, MIGRATION_SETUP=False, - * PER_VM_CPU_OVERSUBSCRIBE=True, POWER_ON_WOL=True, FIBRE_CHANNEL=True, - * ISCSI=True, HVM_MAX_VNICS=8} - */ - private Map ovmHypervisorDetails = new HashMap(); - private Map ovmHypervisor = new HashMap(); - private Map ovmNTP = new HashMap(); - private Map ovmDateTime = new HashMap(); - private Map ovmGeneric = new HashMap(); - /** - * {OS_Major_Version=5, Statistic=20, Membership_State=Unowned, - * OVM_Version=3.2.1-517, OS_Type=Linux, Hypervisor_Name=Xen, - * CPU_Type=x86_64, Manager_Core_API_Version=3.2.1.516, - * Is_Primary=false, OS_Name=Oracle VM Server, - * Server_Roles=xen,utility, Pool_Unique_Id=none, - * Host_Kernel_Release=2.6.39-300.22.2.el5uek, OS_Minor_Version=7, - * Agent_Version=3.2.1-183, Boot_Time=1392366638, RPM_Version=3.2.1-183, - * Exports=, Hypervisor_Type=xen, Host_Kernel_Version=#1 SMP Fri Jan 4 - * 12:40:29 PST 2013, - * Unique_Id=1d:d5:e8:91:d9:d0:ed:bd:81:c2:a6:9a:b3:d1:b7:ea, - * Manager_Unique_Id=none, Cluster_State=Offline, Hostname=ovm-1} - */ - private Map hwPhysicalInfo = new HashMap(); - private Map hwSystemInfo = new HashMap(); - private int localTime; - private int lastBootTime; - private String timeZ; - private String timeUTC; - private List mounts = null; - private Map fsMap = null; - - public Linux(Connection c) { - setClient(c); - } - - /* - * discover_server, argument: self - - * default: None - */ - public Boolean discoverServer() throws Ovm3ResourceException { - Object result = callWrapper("discover_server"); - if (result == null) { - return false; - } - Document xmlDocument = prepParse((String) result); - /* could be more subtle */ - String path = "//Discover_Server_Result/Server"; - ovmCapabilities = xmlToMap(path + "/Capabilities", xmlDocument); - ovmHypervisorDetails = xmlToMap(path + "/VMM/Version", xmlDocument); - ovmHypervisor = xmlToMap(path + "/VMM", xmlDocument); - ovmNTP = xmlToMap(path + "/NTP", xmlDocument); - ovmDateTime = xmlToMap(path + "/Date_Time", xmlDocument); - ovmGeneric = xmlToMap(path, xmlDocument); - return true; - } - - public String getAgentVersion() throws Ovm3ResourceException { - return get("Agent_Version"); - } - - public String getHostKernelRelease() throws Ovm3ResourceException { - return get("Host_Kernel_Release"); - } - - public String getHostOs() throws Ovm3ResourceException { - return get("OS_Name"); - } - - public String getHostOsVersion() throws Ovm3ResourceException { - return get("OS_Major_Version") + "." - + get("OS_Minor_Version"); - } - - public String getHypervisorName() throws Ovm3ResourceException { - return get("Hypervisor_Name"); - } - - public String getHypervisorVersion() throws Ovm3ResourceException { - return getHypervisorMajor() + "." - + getHypervisorMinor() + "." + getHypervisorExtra(); - } - - public String getCapabilities() throws Ovm3ResourceException { - return get("Capabilities"); - } - - public String getHypervisorMajor() throws Ovm3ResourceException { - return get("Major"); - } - - public String getHypervisorMinor() throws Ovm3ResourceException{ - return get("Minor"); - } - - public String getHypervisorExtra() throws Ovm3ResourceException { - return get("Extra").replace(".", ""); - } - - public String getManagerUuid() throws Ovm3ResourceException { - return get("Manager_Unique_Id"); - } - - public String getMembershipState() throws Ovm3ResourceException { - return get("Membership_State"); - } - - public String getServerRoles() throws Ovm3ResourceException{ - return get("Server_Roles"); - } - - public boolean getIsPrimary() throws Ovm3ResourceException { - return Boolean.parseBoolean(get("Is_Primary")); - } - - public String getOvmVersion() throws Ovm3ResourceException { - return get("OVM_Version"); - } - - public String getHostName() throws Ovm3ResourceException { - return get("Hostname"); - } - - public Integer getCpuKhz() throws Ovm3ResourceException { - return Integer.valueOf(get("CPUKHz")); - } - - public Integer getCpuSockets() throws Ovm3ResourceException { - return Integer.valueOf(get("SocketsPerNode")); - } - - public Integer getCpuThreads() throws Ovm3ResourceException { - return Integer.valueOf(get("ThreadsPerCore")); - } - - public Integer getCpuCores() throws Ovm3ResourceException { - return Integer.valueOf(get("CoresPerSocket")); - } - - public Integer getTotalThreads() throws Ovm3ResourceException { - return getCpuSockets() * getCpuCores() * getCpuThreads(); - } - - public Double getMemory() throws Ovm3ResourceException { - return Double.valueOf(get("TotalPages")) * 4096; - } - - public Double getFreeMemory() throws Ovm3ResourceException { - return Double.valueOf(get("FreePages")) * 4096; - } - - public String getUuid() throws Ovm3ResourceException { - return get("Unique_Id"); - } - - private void initMaps() throws Ovm3ResourceException { - if (initMaps == 1) { - discoverHardware(); - discoverServer(); - initMaps = 0; - } - } - - public String get(String element) throws Ovm3ResourceException { - try { - initMaps(); - } catch (Ovm3ResourceException e) { - logger.info("Unable to discover host: " + e.getMessage(), e); - throw e; - } - if (ovmGeneric.containsKey(element)) { - return ovmGeneric.get(element); - } else if (ovmHypervisor.containsKey(element)) { - return ovmHypervisor.get(element); - } else if (ovmHypervisorDetails.containsKey(element)) { - return ovmHypervisorDetails.get(element); - } else if (hwPhysicalInfo.containsKey(element)) { - return hwPhysicalInfo.get(element); - } else if (hwSystemInfo.containsKey(element)) { - return hwSystemInfo.get(element); - } else if (ovmCapabilities.containsKey(element)) { - return ovmCapabilities.get(element); - } - return ""; - } - - /* - * get_last_boot_time, argument: self - - * default: None - */ - public Integer getLastBootTime() throws Ovm3ResourceException { - Map result = callMap("get_last_boot_time"); - if (result == null) { - return null; - } - lastBootTime = result.get("last_boot_time").intValue(); - localTime = result.get("local_time").intValue(); - return lastBootTime; - } - - /* - * get_support_files, argument: self - - * default: None - */ - - public Boolean copyFile(String src, String dst) throws Ovm3ResourceException { - /* sparse is set to true by default ? */ - Object x = callWrapper("copy_file", src, dst, true); - if (x == null) { - return true; - } - return false; - } - - public Boolean copyFile(String src, String dst, Boolean sparse) throws Ovm3ResourceException { - Object x = callWrapper("copy_file", src, dst, sparse); - if (x == null) { - return true; - } - return false; - } - - public Map getFileSystemMap(String type) throws Ovm3ResourceException { - if (fsMap == null) { - discoverMountedFs(type); - } - return fsMap; - } - public FileSystem getFileSystem(String mountpoint, String type) throws Ovm3ResourceException { - getFileSystemMap(type); - if (getFileSystemMap(type).containsKey(mountpoint)) { - return getFileSystemMap(type).get(mountpoint); - } - return null; - } - public FileSystem getFileSystemByUuid(String uuid, String type) throws Ovm3ResourceException { - getFileSystemMap(type); - for (final Map.Entry fs : fsMap.entrySet()) { - if (fs.getValue().getUuid().matches(uuid)) { - return fs.getValue(); - } - } - return null; - } - public void setFileSystemMap(Map map) { - fsMap = map; - } - public List getFileSystemList() { - return mounts; - } - - public static class FileSystem { - private Map fileSys = new HashMap() { - { - put("Mount_Options", null); - put("Name", null); - put(DEVICE, null); - put("Host", null); - put(REMOTEDIR, null); - put(MOUNTPOINT, null); - put("Uuid", null); - } - private static final long serialVersionUID = 123L; - }; - - public Boolean setDetails(Map fs) { - fileSys = fs; - return true; - } - public Map getDetails() { - return fileSys; - } - public String getUuid() { - return (String) fileSys.get("Uuid"); - } - - public String setUuid(String uuid) { - return (String) fileSys.put("Uuid", uuid); - } - - public String getDevice() { - return (String) fileSys.get(DEVICE); - } - - public String setDevice(String dev) { - return (String) fileSys.put(DEVICE, dev); - } - - public String getHost() { - if (getDevice() != null && getDevice().contains(":")) { - String[] spl = getDevice().split(":"); - setHost(spl[0]); - setRemoteDir(spl[1]); - } else { - return null; - } - return (String) fileSys.get("Host"); - } - - public String setHost(String host) { - return (String) fileSys.put("Host", host); - } - - public String setRemoteDir(String dir) { - return (String) fileSys.put(REMOTEDIR, dir); - } - - public String getRemoteDir() { - if (getHost() != null) { - return (String) fileSys.get(REMOTEDIR); - } - return null; - } - - public String setMountPoint(String pnt) { - return (String) fileSys.put(MOUNTPOINT, pnt); - } - public String getMountPoint() { - return (String) fileSys.get(MOUNTPOINT); - } - } - - /* should actually be called "getMountedsFsDevice" or something */ - /* takes nfs,ext3 etc as parameter it reads from /proc/mounts */ - public Map discoverMountedFs(String type) throws Ovm3ResourceException { - fsMap = new HashMap(); - Object x = callWrapper("discover_mounted_file_systems", type); - if (x == null) { - return fsMap; - } - Document xmlDocument = prepParse((String) x); - String bpath = "//Discover_Mounted_File_Systems_Result/Filesystem"; - String mpath = bpath + "/Mount/@Dir"; - mounts = xmlToList(mpath, xmlDocument); - for (String mnt : mounts) { - String dpath = bpath + "/Mount[@Dir='" + mnt + "']"; - Map fs = xmlToMap(dpath, xmlDocument); - FileSystem f = new FileSystem(); - f.setDetails(fs); - String[] spl = mnt.split("/"); - String uuid = spl[spl.length - 1]; - f.setUuid(uuid); - f.setMountPoint(mnt); - /* sets it up per mountpoint, not the ID!!! */ - fsMap.put(mnt, f); - } - setFileSystemMap(fsMap); - return fsMap; - } - - /* TODO: in 3.3.x this changed to user, pass, oldpass */ - public Boolean updateAgentPassword(String user, String pass) throws Ovm3ResourceException { - Object x = callWrapper("update_agent_password", user, pass); - if (x == null) { - return true; - } - return false; - } - - public Boolean discoverHardware() throws Ovm3ResourceException { - Object result = callWrapper("discover_hardware"); - if (result == null) { - return false; - } - Document xmlDocument; - xmlDocument = prepParse((String) result); - /* could be more subtle */ - String path = "//Discover_Hardware_Result/NodeInformation"; - /* we don't care a bout IO/SCSI for now..., we might care about - * CPUs later: NodeInformation/CPUInfo/Proc_Info/CPU[@ID=0] - */ - hwPhysicalInfo = xmlToMap(path + "/VMM/PhysicalInfo", xmlDocument); - hwSystemInfo = xmlToMap(path + "/DMTF/System", xmlDocument); - return true; - } - - public Integer getDateTime() throws Ovm3ResourceException { - getLastBootTime(); - return localTime; - } - - /* Pushes the statistics out to a url, the statistics are in the form of a dict */ - public Boolean setStatisticsInterval(int val) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("set_statistics_interval", val); - } - - public Boolean getTimeZone() throws Ovm3ResourceException { - Object[] result = (Object[]) callWrapper("get_timezone"); - if (result != null) { - setTimeZ(result[0].toString()); - setTimeUTC(result[1].toString()); - return true; - } - return false; - } - - public String getTimeUTC() { - return timeUTC; - } - - private void setTimeUTC(String timeUTC) { - this.timeUTC = timeUTC; - } - - public String getTimeZ() { - return timeZ; - } - - private void setTimeZ(String timeZ) { - this.timeZ = timeZ; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Network.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Network.java deleted file mode 100644 index 158416c27a4a..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Network.java +++ /dev/null @@ -1,329 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.w3c.dom.Document; - -public class Network extends OvmObject { - private static final String START = "start"; - private static final String BRIDGE = "Bridge"; - private static final String ADDRESS = "Address"; - private static final String PHYSICAL = "Physical"; - private Map interfaceList = null; - private Object postDiscovery = null; - private List netInterfaces = new ArrayList(); - - public Network(Connection c) { - setClient(c); - } - - public Map getInterfaceList() - throws Ovm3ResourceException { - discoverNetwork(); - return interfaceList; - } - - public static class Interface { - private final Map iFace = new HashMap() { - { - put("Type", null); - put(PHYSICAL, null); - put("Name", null); - put(ADDRESS, null); - put("Broadcast", null); - put("MAC", null); - put("Vlan", null); - } - private static final long serialVersionUID = 6L; - }; - - public Interface() { - } - - public void setIfType(String t) { - iFace.put("Type", t); - } - - public String getIfType() { - return iFace.get("Type"); - } - - public void setInterface(Map itf) { - iFace.putAll(itf); - } - - public String getName() { - return iFace.get("Name"); - } - - public String getPhysical() { - return iFace.get(PHYSICAL); - } - - public String getAddress() { - return iFace.get(ADDRESS); - } - - public String getBroadcast() { - return iFace.get("Broadcast"); - } - - public String getMac() { - return iFace.get("MAC"); - } - - public String setName(String name) { - return iFace.put("Name", name); - } - - public String setPhysical(String ph) { - return iFace.put(PHYSICAL, ph); - } - - public String setMac(String mac) { - return iFace.put("MAC", mac); - } - } - - private Network.Interface getNetIface(String key, String val) - throws Ovm3ResourceException { - Map ifaces = getInterfaceList(); - for (final Entry iface : ifaces.entrySet()) { - String match = "default"; - if (ADDRESS.equals(key)) { - match = iface.getValue().getAddress(); - } - if ("Name".equals(key)) { - match = iface.getKey(); - } - if (match != null && match.equals(val)) { - return iface.getValue(); - } - } - logger.debug("Unable to find " + key + " Interface by value: " + val); - setSuccess(false); - return null; - } - - public Network.Interface getInterfaceByIp(String ip) - throws Ovm3ResourceException { - return getNetIface(ADDRESS, ip); - } - - public Network.Interface getInterfaceByName(String name) - throws Ovm3ResourceException { - return getNetIface("Name", name); - } - - /* check if it is a BRIDGE */ - public String getPhysicalByBridgeName(String name) - throws Ovm3ResourceException { - return getInterfaceByName(name).getPhysical(); - } - - public Network.Interface getBridgeByName(String name) - throws Ovm3ResourceException { - if (getNetIface("Name", name) != null - && getNetIface("Name", name).getIfType().contentEquals(BRIDGE)) { - return getNetIface("Name", name); - } - logger.debug("Unable to find bridge by name: " + name); - setSuccess(false); - return null; - } - - public Network.Interface getBridgeByIp(String ip) - throws Ovm3ResourceException { - if (getNetIface(ADDRESS, ip) != null - && getNetIface(ADDRESS, ip).getIfType().contentEquals(BRIDGE)) { - return getNetIface(ADDRESS, ip); - } - logger.debug("Unable to find bridge by IP: " + ip); - setSuccess(false); - return null; - } - - /* - * configure_virtual_ip, argument: self - default: - * None argument: virtual_ip - default: None argument: base_ip - default: - * None - */ - public Boolean configureVip(String vip, String baseip) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("configure_virtual_ip", vip, baseip); - } - - public Boolean ovsIpConfig(String net, String optype, String ip, - String netmask) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("ovs_ip_config", net, optype, ip, netmask); - } - - /* - * Restriction: - data string that starts with leading spaces will be - * rejected ovs_if_meta('bond0', - * 'ethernet:c0a80100{192.168.1.0}:MANAGEMENT,CLUSTER_HEARTBEAT,LIVE_MIGRATE,VIRTUAL_MACHINE,STORAGE') - */ - - public Boolean discoverNetwork() throws Ovm3ResourceException { - postDiscovery = callWrapper("discover_network"); - if (postDiscovery == null) { - return false; - } - interfaceList = new HashMap(); - Document xmlDocument = prepParse((String) postDiscovery); - String path = "//Discover_Network_Result/Network/Active"; - String bpath = path + "/Bridges/Device"; - - netInterfaces = new ArrayList(); - netInterfaces.addAll(xmlToList(bpath + "/@Name", xmlDocument)); - for (String b : netInterfaces) { - Map br = xmlToMap(bpath + "[@Name='" + b - + "']/Family", xmlDocument); - /* vifs are here too */ - String phyInt = (String) this.xmlToMap( - bpath + "[@Name='" + b + "']/Interfaces", xmlDocument).get( - "PhyInterface"); - Interface iface = new Interface(); - iface.setInterface(br); - iface.setName(b); - iface.setIfType(BRIDGE); - if (phyInt == null) { - iface.setIfType("Local"); - } - iface.setPhysical(phyInt); - interfaceList.put(b, iface); - } - /* add "physical" interfaces */ - bpath = path + "/Network/Device"; - netInterfaces = new ArrayList(); - netInterfaces.addAll(xmlToList(bpath + "/@Name", xmlDocument)); - for (String p : netInterfaces) { - Map nf = xmlToMap("//Device[@Name='" + p + "']", - xmlDocument); - Interface iface = new Interface(); - iface.setPhysical(nf.get("Basename")); - iface.setName(p); - iface.setMac(nf.get("MAC")); - iface.setIfType(PHYSICAL); - interfaceList.put(p, iface); - } - /* add virtual interfaces ? */ - return true; - } - - public Boolean startOvsLocalConfig(String br) throws Ovm3ResourceException { - String s = (String) ovsLocalConfig(START, br); - if (s.startsWith(START)) { - return true; - } - return false; - } - - public Boolean stopOvsLocalConfig(String br) throws Ovm3ResourceException { - String s = (String) ovsLocalConfig("stop", br); - if (s.startsWith("stop")) { - return true; - } - return false; - } - - private Object ovsLocalConfig(String action, String br) - throws Ovm3ResourceException { - return callWrapper("ovs_local_config", action, br); - } - - public Boolean startOvsVlanConfig(String dev, int vlan) - throws Ovm3ResourceException { - return ovsVlanConfig("add", dev, vlan); - } - - public Boolean stopOvsVlanConfig(String dev, int vlan) - throws Ovm3ResourceException { - return ovsVlanConfig("remove", dev, vlan); - } - - private Boolean ovsVlanConfig(String action, String net, int vlan) - throws Ovm3ResourceException { - Object x = callWrapper("ovs_vlan_config", action, net, vlan); - if (x == null) { - return true; - } - return false; - } - - public Boolean startOvsBrConfig(String br, String dev) - throws Ovm3ResourceException { - String s = (String) ovsBrConfig(START, br, dev); - if (s.startsWith(START)) { - return true; - } - return false; - } - - public Boolean stopOvsBrConfig(String br, String dev) - throws Ovm3ResourceException { - String s = (String) ovsBrConfig("stop", br, dev); - if (s.startsWith("stop")) { - return true; - } - return false; - } - - public Object ovsBrConfig(String action, String br, String net) - throws Ovm3ResourceException { - return callWrapper("ovs_br_config", action, br, net); - } - - /* 1 is untagged, goes till 4095 */ - public Boolean stopOvsVlanBridge(String br, String net, int vlan) - throws Ovm3ResourceException { - String s = (String) ovsVlanBridge("stop", br, net, vlan); - if (s.startsWith("stop")) { - return true; - } - return false; - } - - public Boolean startOvsVlanBridge(String br, String net, int vlan) - throws Ovm3ResourceException { - String s = (String) ovsVlanBridge(START, br, net, vlan); - /* 3.2.1 uses start, 3.3.1 and up uses added... */ - if (s.startsWith(START) || s.startsWith("Added")) { - return true; - } - return false; - } - - private Object ovsVlanBridge(String action, String br, String net, int vlan) - throws Ovm3ResourceException { - return callWrapper("ovs_vlan_bridge", action, br, net, vlan); - } - - /* - * deconfigure_virtual_ip, argument: self - default: - * None argument: virtual_ip - default: None - */ -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ntp.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ntp.java deleted file mode 100644 index 9852a7d1fb3f..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ntp.java +++ /dev/null @@ -1,119 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.List; - -public class Ntp extends OvmObject { - private List ntpHosts = new ArrayList(); - private Boolean isServer = null; - private Boolean isRunning = null; - - public Ntp(Connection c) { - setClient(c); - } - - public List addServer(String server) { - if (!ntpHosts.contains(server)) { - ntpHosts.add(server); - } - return ntpHosts; - } - - public List removeServer(String server) { - if (ntpHosts.contains(server)) { - ntpHosts.remove(server); - } - return ntpHosts; - } - - public List getServers() { - return ntpHosts; - } - public void setServers(List s) { - ntpHosts = s; - } - - public Boolean isRunning() { - return isRunning; - } - - public Boolean isServer() { - return isServer; - } - - public Boolean getDetails() throws Ovm3ResourceException { - return getNtp(); - } - - /* - * get_ntp, argument: self - default: - * None - */ - public Boolean getNtp() throws Ovm3ResourceException { - Object[] v = (Object[]) callWrapper("get_ntp"); - int c = 0; - for (Object o : v) { - if (o instanceof java.lang.Boolean) { - if (c == 0) { - isServer = (Boolean) o; - } - if (c == 1) { - isRunning = (Boolean) o; - } - c += 1; - } else if (o instanceof java.lang.Object) { - Object[] s = (Object[]) o; - for (Object m : s) { - addServer((String) m); - } - } - } - return true; - } - - public Boolean setNtp(List ntpHosts, Boolean running) - throws Ovm3ResourceException { - if (ntpHosts.isEmpty()) { - return false; - } - return nullIsTrueCallWrapper("set_ntp", ntpHosts, running); - } - - /* also cleans the vector */ - public Boolean setNtp(String server, Boolean running) - throws Ovm3ResourceException { - ntpHosts = new ArrayList(); - ntpHosts.add(server); - return setNtp(ntpHosts, running); - } - - public Boolean setNtp(Boolean running) throws Ovm3ResourceException { - return setNtp(ntpHosts, running); - } - - public Boolean disableNtp() throws Ovm3ResourceException { - return nullIsTrueCallWrapper("disable_ntp"); - - } - - public Boolean enableNtp() throws Ovm3ResourceException { - return nullIsTrueCallWrapper("enable_ntp"); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ovm3ResourceException.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ovm3ResourceException.java deleted file mode 100644 index 7e184435f107..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Ovm3ResourceException.java +++ /dev/null @@ -1,39 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -public class Ovm3ResourceException extends Exception { - private static final long serialVersionUID = 1L; - private static final Throwable CAUSE = null; - public Ovm3ResourceException() { - super(); - } - - public Ovm3ResourceException(String message) { - super(message); - } - - public Ovm3ResourceException(String message, Throwable cause) { - super(message, cause); - } - - @Override - public Throwable getCause() { - return CAUSE; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/OvmObject.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/OvmObject.java deleted file mode 100644 index d98f3bb6d3f9..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/OvmObject.java +++ /dev/null @@ -1,248 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.io.IOException; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import com.cloud.utils.UuidUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.apache.xmlrpc.XmlRpcException; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class OvmObject { - private volatile Connection client; - private static List emptyParams = new ArrayList(); - protected Logger logger = LogManager.getLogger(getClass()); - private boolean success = false; - - public OvmObject() { - } - - public Connection getClient() { - return client; - } - - public synchronized void setClient(Connection c) { - client = c; - } - - /* remove dashes from uuids */ - public String deDash(String str) { - return str.replaceAll("-", ""); - } - /* generate a uuid */ - public String newUuid() { - return UUID.randomUUID().toString(); - } - - /* generate a uuid */ - public String newUuid(String str) { - return UuidUtils.nameUUIDFromBytes(str.getBytes(Charset.defaultCharset())).toString(); - } - - /* capture most of the calls here */ - public Object callWrapper(String call) throws Ovm3ResourceException { - try { - return client.call(call, emptyParams); - } catch (XmlRpcException e) { - String msg = "Client call " + call + " to " + client.getIp() + " went wrong: " + e.getMessage(); - throw new Ovm3ResourceException(msg, e); - } - } - - public void setSuccess(boolean s) { - success = s; - } - - public Boolean getSuccess() { - return success; - } - - /* nice try but doesn't work like that .. */ - @SafeVarargs - public final Object callWrapper(String call, T... args) - throws Ovm3ResourceException { - List params = new ArrayList(); - for (T param : args) { - params.add(param); - } - try { - return client.call(call, params); - } catch (XmlRpcException e) { - String msg = "Client call " + call + " to " + client.getIp() + " with " + params + " went wrong: " + e.getMessage(); - throw new Ovm3ResourceException(msg, e); - } - } - - /* should check on nil ? */ - @SafeVarargs - public final Boolean nullCallWrapper(String call, Boolean nullReturn, T... args) throws Ovm3ResourceException { - Object x = callWrapper(call, args); - if (x == null) { - return nullReturn; - } else if (!nullReturn) { - return true; - } - return false; - } - - @SafeVarargs - public final Boolean nullIsFalseCallWrapper(String call, T... args) throws Ovm3ResourceException { - return nullCallWrapper(call, false, args); - } - @SafeVarargs - public final Boolean nullIsTrueCallWrapper(String call, T... args) throws Ovm3ResourceException { - return nullCallWrapper(call, true, args); - } - - /* returns a single string */ - public Map callMap(String call) throws Ovm3ResourceException { - return (HashMap) callWrapper(call); - } - - public String callString(String call, T... args) throws Ovm3ResourceException { - Object result = callWrapper(call, args); - if (result == null) { - return null; - } - if (result instanceof String || result instanceof Integer || result instanceof Long || result instanceof HashMap) { - return result.toString(); - } - - Object[] results = (Object[]) result; - - if (results.length == 0) { - return null; - } - if (results.length == 1) { - return results[0].toString(); - } - return null; - } - - /* was String, Object before */ - public Map xmlToMap(String path, Document xmlDocument) - throws Ovm3ResourceException { - XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); - XPath xPath = factory.newXPath(); - try { - XPathExpression xPathExpression = xPath.compile(path); - NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument, - XPathConstants.NODESET); - Map myMap = new HashMap(); - for (int ind = 0; ind < nodeList.getLength(); ind++) { - NodeList nodeListFor = nodeList.item(ind).getChildNodes(); - for (int index = 0; index < nodeListFor.getLength(); index++) { - String rnode = nodeListFor.item(index).getNodeName(); - NodeList nodeListFor2 = nodeListFor.item(index).getChildNodes(); - if (nodeListFor2.getLength() > 1) { - /* Do we need to figure out all the sub elements here and put them in a map? */ - } else { - String element = nodeListFor.item(index).getNodeValue(); - myMap.put(rnode, (E) element); - } - } - } - return myMap; - } catch (XPathExpressionException e) { - throw new Ovm3ResourceException("Problem parsing XML to Map:", e); - } - } - - public List xmlToList(String path, Document xmlDocument) - throws Ovm3ResourceException { - List list = new ArrayList(); - XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); - XPath xPath = factory.newXPath(); - try { - XPathExpression xPathExpression = xPath.compile(path); - NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument, - XPathConstants.NODESET); - for (int ind = 0; ind < nodeList.getLength(); ind++) { - if (!nodeList.item(ind).getNodeValue().isEmpty()) { - list.add("" + nodeList.item(ind).getNodeValue()); - } else { - list.add("" + nodeList.item(ind).getNodeValue()); - } - } - return list; - } catch (XPathExpressionException e) { - throw new Ovm3ResourceException("Problem parsing XML to List: ", e); - } - } - - public String xmlToString(String path, Document xmlDocument) - throws Ovm3ResourceException { - XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); - XPath xPath = factory.newXPath(); - try { - XPathExpression xPathExpression = xPath.compile(path); - NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument, - XPathConstants.NODESET); - return nodeList.item(0).getNodeValue(); - } catch (NullPointerException e) { - logger.info("Got no items back from parsing, returning null: " + e); - return null; - } catch (XPathExpressionException e) { - throw new Ovm3ResourceException("Problem parsing XML to String: ", e); - } - } - - public Document prepParse(String input) - throws Ovm3ResourceException { - DocumentBuilderFactory builderfactory = DocumentBuilderFactory - .newInstance(); - builderfactory.setNamespaceAware(true); - - DocumentBuilder builder; - try { - builder = builderfactory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new Ovm3ResourceException("Unable to create document Builder: ", e); - } - Document xmlDocument; - try { - xmlDocument = builder.parse(new InputSource(new StringReader( - input))); - } catch (SAXException | IOException e) { - logger.info(e.getClass() + ": ", e); - throw new Ovm3ResourceException("Unable to parse XML: ", e); - } - return xmlDocument; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Pool.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Pool.java deleted file mode 100644 index a95664499bbb..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Pool.java +++ /dev/null @@ -1,270 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.w3c.dom.Document; - -/* - * synonym to the pool python lib in the ovs-agent - */ -public class Pool extends OvmObject { - - private final List validRoles = new ArrayList() { - { - add("xen"); - add("utility"); - } - private static final long serialVersionUID = 1L; - }; - private List poolHosts = new ArrayList(); - private final List poolRoles = new ArrayList(); - private String poolPrimaryVip; - private String poolAlias; - private String poolId = null; - - public Pool(Connection c) { - setClient(c); - } - - public String getPoolPrimaryVip() { - return poolPrimaryVip; - } - - public String getPoolAlias() { - return poolAlias; - } - - public String getPoolId() { - return poolId; - } - - public List getValidRoles() { - return validRoles; - } - - public Boolean isInPool(String id) throws Ovm3ResourceException { - if (poolId == null) { - discoverServerPool(); - } - if (poolId == null) { - return false; - } - if (isInAPool() && poolId.equals(id)) { - return true; - } - return false; - } - - public Boolean isInAPool() throws Ovm3ResourceException { - if (poolId == null) { - discoverServerPool(); - } - if (poolId == null) { - return false; - } - return true; - } - - private Boolean createServerPool(String alias, String id, String vip, - int num, String name, String host, List roles) throws Ovm3ResourceException{ - String role = StringUtils.join(roles, ","); - if (!isInAPool()) { - Object x = callWrapper("create_server_pool", alias, id, vip, num, name, - host, role); - if (x == null) { - return true; - } - return false; - } else if (isInPool(id)) { - return true; - } else { - throw new Ovm3ResourceException("Unable to add host is already in a pool with id : " + poolId); - } - } - - public Boolean createServerPool(String alias, String id, String vip, - int num, String name, String ip) throws Ovm3ResourceException { - return createServerPool(alias, id, vip, num, name, ip, - getValidRoles()); - } - - /* - * public Boolean updatePoolVirtualIp(String ip) throws - * Ovm3ResourceException { Object x = callWrapper("update_pool_virtual_ip", - * ip); if (x == null) { poolPrimaryVip = ip; return true; } return false; } - */ - - public Boolean leaveServerPool(String uuid) throws Ovm3ResourceException{ - return nullIsTrueCallWrapper("leave_server_pool", uuid); - } - /** - * Ownership prior to 3.3.x used to be simpler.... - * @param uuid - * @param apiurl - * @return - * @throws Ovm3ResourceException - */ - public Boolean takeOwnership(String uuid, String apiurl) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("take_ownership", uuid, apiurl); - } - /** - * New style ownership, we need a dict to go in. - * manager_uuid - * manager_event_url - * manager_statistic_url - * manager_certificate - * signed_server_certificate - * @param uuid - * @param apiurl - * @return - * @throws Ovm3ResourceException - */ - public Boolean takeOwnership33x(final String uuid, - final String eventUrl, - final String statUrl, - final String managerCert, - final String signedCert) throws Ovm3ResourceException { - final Map mgrConfig = new HashMap() { - { - put("manager_uuid", uuid); - put("manager_event_url", eventUrl); - put("manager_statistic_url", statUrl); - put("manager_certificate", managerCert); - put("signed_server_certificate", signedCert); - } - private static final long serialVersionUID = 1L; - }; - Boolean rc = nullIsTrueCallWrapper("take_ownership", mgrConfig); - /* because it restarts when it's done.... 2000? -sigh- */ - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - throw new Ovm3ResourceException(e.getMessage()); - } - return rc; - } - - /* - * destroy_server_pool, argument: - * self - default: None argument: pool_uuid - default: None - */ - public Boolean destroyServerPool(String uuid) throws Ovm3ResourceException{ - return nullIsTrueCallWrapper("destroy_server_pool", uuid); - } - - /* - * release_ownership, argument: - * self - default: None argument: manager_uuid - default: None - */ - public Boolean releaseOwnership(String uuid) throws Ovm3ResourceException{ - return nullIsTrueCallWrapper("release_ownership", uuid); - } - - /* server.discover_pool_filesystem */ - /* - * discover_server_pool, argument: - * self - default: None - */ - public Boolean discoverServerPool() throws Ovm3ResourceException { - Object x = callWrapper("discover_server_pool"); - if (x == null) { - return false; - } - - Document xmlDocument = prepParse((String) x); - String path = "//Discover_Server_Pool_Result/Server_Pool"; - poolId = xmlToString(path + "/Unique_Id", xmlDocument); - poolAlias = xmlToString(path + "/Pool_Alias", xmlDocument); - poolPrimaryVip = xmlToString(path + "/Primary_Virtual_Ip", - xmlDocument); - poolHosts.addAll(xmlToList(path + "//Registered_IP", xmlDocument)); - if (poolId == null) { - return false; - } - return true; - } - - private Boolean setServerRoles() throws Ovm3ResourceException{ - String roles = StringUtils.join(poolRoles.toArray(), ","); - return nullIsTrueCallWrapper("update_server_roles", roles); - } - - /* do some sanity check on the valid poolroles */ - public Boolean setServerRoles(List roles) throws Ovm3ResourceException { - poolRoles.addAll(roles); - return setServerRoles(); - } - - private Boolean joinServerPool(String alias, String id, String vip, int num, - String name, String host, List roles) throws Ovm3ResourceException{ - String role = StringUtils.join(roles.toArray(), ","); - if (!isInAPool()) { - Object x = callWrapper("join_server_pool", alias, id, vip, num, name, - host, role); - if (x == null) { - return true; - } - return false; - } else if (isInPool(id)) { - return true; - } else { - throw new Ovm3ResourceException("Unable to add host is already in a pool with id : " + poolId); - } - } - - public Boolean joinServerPool(String alias, String id, String vip, int num, - String name, String host) throws Ovm3ResourceException { - return joinServerPool(alias, id, vip, num, name, host, getValidRoles()); - } - - private Boolean setPoolMemberList() throws Ovm3ResourceException { - // should throw exception if no poolHosts set - return nullIsTrueCallWrapper("set_pool_member_ip_list", poolHosts); - } - - public List getPoolMemberList() throws Ovm3ResourceException { - if (poolId == null) { - discoverServerPool(); - } - return poolHosts; - } - - public Boolean setPoolMemberList(List hosts) throws Ovm3ResourceException { - poolHosts = new ArrayList(); - poolHosts.addAll(hosts); - return setPoolMemberList(); - } - - public Boolean addPoolMember(String host) throws Ovm3ResourceException { - getPoolMemberList(); - poolHosts.add(host); - return setPoolMemberList(); - } - - public Boolean removePoolMember(String host) throws Ovm3ResourceException { - getPoolMemberList(); - poolHosts.remove(host); - return setPoolMemberList(); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2.java deleted file mode 100644 index 256f08d13d76..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2.java +++ /dev/null @@ -1,139 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.HashMap; -import java.util.Map; - -import org.w3c.dom.Document; - -public class PoolOCFS2 extends OvmObject { - private Map poolFileSystem = new HashMap(); - private String poolFsTarget; - private String poolFsType; - private String poolFsNFSBaseId; - private String poolFsId; - private String poolFsVersion; - private String poolFsManagerUuid; - private String poolPoolFsId; - - public PoolOCFS2(Connection c) { - setClient(c); - } - - public String getPoolFsNFSBaseId() { - return poolFsNFSBaseId; - } - - public String getPoolFsId() { - return poolFsId; - } - - public String getPoolFsUuid() { - return poolFsId; - } - - public String getPoolFsTarget() { - return poolFsTarget; - } - public String getPoolFsManagerUuid() { - return poolFsManagerUuid; - } - public String getPoolFsVersion() { - return poolFsVersion; - } - public String getPoolPoolFsId() { - return poolPoolFsId; - } - public String getPoolFsType() { - return poolFsType; - } - public Boolean hasPoolFs(String id) throws Ovm3ResourceException { - if (poolFsId == null) { - discoverPoolFs(); - } - if (hasAPoolFs() && poolFsId.equals(id)) { - return true; - } - return false; - } - public Boolean hasAPoolFs() throws Ovm3ResourceException { - if (poolFsId == null) { - discoverPoolFs(); - } - if (poolFsId == null) { - return false; - } - return true; - } - - public Boolean destroyPoolFs(String type, String target, String uuid, - String nfsbaseuuid) throws Ovm3ResourceException { - // should throw exception if no poolIps set - return nullIsTrueCallWrapper("destroy_pool_filesystem", type, target, uuid, - nfsbaseuuid); - } - - public Boolean destroyPoolFs() throws Ovm3ResourceException { - // should throw exception if no poolIps set - return nullIsTrueCallWrapper("destroy_pool_filesystem", poolFsType, - poolFsTarget, poolFsId, poolFsNFSBaseId); - } - - public Boolean createPoolFs(String type, String target, String clustername, - String fsid, String nfsbaseid, String managerid) throws Ovm3ResourceException { - if (!hasAPoolFs()) { - return nullIsTrueCallWrapper("create_pool_filesystem", type, target, - clustername, fsid, nfsbaseid, managerid, fsid); - } else if (hasPoolFs(fsid)) { - logger.debug("PoolFs already exists on this host: " + fsid); - return true; - } else { - throw new Ovm3ResourceException("Unable to add pool filesystem to host, "+ - "pool filesystem with other id found: " + poolFsId); - } - } - - /* Assume a single pool can be used for a host... */ - public Boolean discoverPoolFs() throws Ovm3ResourceException{ - // should throw exception if no poolIps set - Object x = callWrapper("discover_pool_filesystem"); - if (x == null) { - return false; - } - Document xmlDocument = prepParse((String) x); - String path = "//Discover_Pool_Filesystem_Result"; - poolFileSystem = xmlToMap(path + "/Pool_Filesystem", xmlDocument); - poolFsTarget = poolFileSystem.get("Pool_Filesystem_Target"); - poolFsType = poolFileSystem.get("Pool_Filesystem_Type"); - poolFsNFSBaseId = poolFileSystem.get("Pool_Filesystem_Nfsbase_Uuid"); - poolFsId = poolFileSystem.get("Pool_Filesystem_Uuid"); - poolPoolFsId = poolFileSystem.get("Pool_Filesystem_Pool_Uuid"); - poolFsManagerUuid = poolFileSystem.get("Pool_Filesystem_Manager_Uuid"); - poolFsVersion = poolFileSystem.get("Pool_Filesystem_Version"); - return true; - } - - public Boolean ocfs2GetMetaData(String device, String filename) throws Ovm3ResourceException { - Object x = callWrapper("ocfs2_get_meta_data", device, filename); - if (x == null) { - return true; - } - return false; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Remote.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Remote.java deleted file mode 100644 index 2556b782d87c..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Remote.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -public class Remote extends OvmObject { - - public Remote(Connection c) { - setClient(c); - } - - public Boolean sysShutdown() throws Ovm3ResourceException { - return nullIsTrueCallWrapper("sys_shutdown"); - } - - public Boolean sysReboot() throws Ovm3ResourceException { - return nullIsTrueCallWrapper("sys_reboot"); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Repository.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Repository.java deleted file mode 100644 index ba4d62e3b795..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Repository.java +++ /dev/null @@ -1,334 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.w3c.dom.Document; - -public class Repository extends OvmObject { - private static final String VERSION = "Version"; - private static final String NAMETAG = "[@Name='"; - private Object postDiscovery = null; - private Object postDbDiscovery = null; - private Map repoDbs = new HashMap(); - private Map repos = new HashMap(); - private List repoDbList = new ArrayList(); - private List repoList = new ArrayList(); - - public Repository(Connection c) { - setClient(c); - } - - public RepoDbDetails getRepoDb(String id) throws Ovm3ResourceException { - if (repoDbs.containsKey(id)) { - return repoDbs.get(id); - } - return null; - } - - public List getRepoDbList() throws Ovm3ResourceException { - return repoDbList; - } - - public RepoDetails getRepo(String id) throws Ovm3ResourceException { - if (repos.containsKey(id)) { - return repos.get(id); - } - return null; - } - - public List getRepoList() throws Ovm3ResourceException { - return repoList; - } - - public static class RepoDbDetails { - private static final long serialVersionUID = 2L; - private final Map dbEntry = new HashMap() { - { - put("Uuid", null); - put("Fs_location", null); - put("Mount_point", null); - put("Filesystem_type", null); - put(VERSION, null); - put("Alias", null); - put("Manager_uuid", null); - put("Status", null); - } - private static final long serialVersionUID = 1L; - }; - - public RepoDbDetails() { - } - - public void setRepoDbDetails(Map det) { - dbEntry.putAll(det); - } - - public void setUuid(String id) { - dbEntry.put("Uuid", id); - } - - public String getStatus() { - return dbEntry.get("Status"); - } - - public String getManagerUuid() { - return dbEntry.get("Manager_uuid"); - } - - public String getAlias() { - return dbEntry.get("Alias"); - } - - public String getVersion() { - return dbEntry.get(VERSION); - } - - public String getFilesystemType() { - return dbEntry.get("Filesystem_type"); - } - - public String getMountPoint() { - return dbEntry.get("Mount_point"); - } - - public String getFsLocation() { - return dbEntry.get("Fs_location"); - } - - public String getUuid() { - return dbEntry.get("Uuid"); - } - - } - - public static class RepoDetails { - private List templates = new ArrayList(); - private List virtualMachines = new ArrayList(); - private List virtualDisks = new ArrayList(); - private List isos = new ArrayList(); - private final Map dbEntry = new HashMap() { - private static final long serialVersionUID = 1L; - { - put("Repository_UUID", null); - put(VERSION, null); - put("Repository_Alias", null); - put("Manager_UUID", null); - } - }; - - public RepoDetails() { - } - - public String getManagerUuid() { - return dbEntry.get("Manager_UUID"); - } - - public String getAlias() { - return dbEntry.get("Repository_Alias"); - } - - public String getVersion() { - return dbEntry.get(VERSION); - } - - public String getUuid() { - return dbEntry.get("Repository_UUID"); - } - - public void setRepoDetails(Map det) { - dbEntry.putAll(det); - } - - public void setRepoTemplates(List temp) { - templates.addAll(temp); - } - - public List getRepoTemplates() { - return templates; - } - - public void setRepoVirtualMachines(List vms) { - virtualMachines.addAll(vms); - } - - public List getRepoVirtualMachines() { - return virtualMachines; - } - - public void setRepoVirtualDisks(List disks) { - virtualDisks.addAll(disks); - } - - public List getRepoVirtualDisks() { - return virtualDisks; - } - - public void setRepoISOs(List isolist) { - isos.addAll(isolist); - } - - public List getRepoISOs() { - return isos; - } - } - - /* - * delete_repository, argument: - * repo_uuid - default: None argument: erase - default: None - */ - public Boolean deleteRepo(String id, Boolean erase) - throws Ovm3ResourceException { - Object res = callWrapper("delete_repository", id, erase); - if (res == null) { - return true; - } - return false; - } - - /* - * import_virtual_disk, argument: - * url - default: None argument: virtual_disk_id - default: None argument: - * repo_uuid - default: None argument: option - default: None - */ - /* should add timeout ? */ - public Boolean importVirtualDisk(String url, String vdiskid, String repoid, - String option) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("import_virtual_disk", url, vdiskid, - repoid, option); - } - - public Boolean importVirtualDisk(String url, String vdiskid, String repoid) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("import_virtual_disk", url, vdiskid, - repoid); - } - - /* - * discover_repositories, - * argument: args - default: None - */ - /* - * args are repo ids - * - */ - public Boolean discoverRepo(String id) throws Ovm3ResourceException { - postDiscovery = callWrapper("discover_repositories", id); - if (postDiscovery == null) { - return false; - } - Document xmlDocument = prepParse((String) postDiscovery); - String path = "//Discover_Repositories_Result/RepositoryList/Repository"; - repoList = new ArrayList(); - repoList.addAll(xmlToList(path + "/@Name", xmlDocument)); - for (String name : repoList) { - RepoDetails repo = new RepoDetails(); - repo.setRepoTemplates(xmlToList(path + NAMETAG + id - + "']/Templates/Template/File", xmlDocument)); - repo.setRepoVirtualMachines(xmlToList(path + NAMETAG + id - + "']/VirtualMachines/VirtualMachine/@Name", xmlDocument)); - repo.setRepoVirtualDisks(xmlToList(path + NAMETAG + name - + "']/VirtualDisks/Disk", xmlDocument)); - repo.setRepoISOs(xmlToList( - path + NAMETAG + name + "']/ISOs/ISO", xmlDocument)); - Map details = xmlToMap(path + NAMETAG + name - + "']", xmlDocument); - repo.setRepoDetails(details); - repos.put(name, repo); - } - return true; - } - - /* - * add_repository, argument: - * fs_location - default: None argument: mount_point - default: None - */ - public Boolean addRepo(String remote, String local) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("add_repository", remote, local); - } - - /** - * is the same as discoverRepoDb in principle (takes an id or mountpoint) - * get_repository_meta_data, - * argument: repo_mount_point - default: None - */ - - /* - * mount_repository_fs, argument: - * fs_location - default: None argument: mount_point - default: None - */ - public Boolean mountRepoFs(String remote, String local) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("mount_repository_fs", remote, local); - } - - /* - * unmount_repository_fs, - * argument: mount_point - default: None - */ - public Boolean unmountRepoFs(String local) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("unmount_repository_fs", local); - } - - /* - * create_repository, argument: - * fs_location - default: None argument: mount_point - default: None - * argument: repo_uuid - default: None argument: repo_alias - default: None - */ - public Boolean createRepo(String remote, String local, String repoid, - String repoalias) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("create_repository", remote, local, - repoid, repoalias); - } - - /* - * discover_repository_db, - * - * cs-mgmt:/volumes/cs-data/primary - * / - * OVS/Repositories/0004fb0000030000aeaca859e4a8f8c0 - * nfs 3.0 - * MyRepo - * 0004fb00000100000af70d20dcce7d65 - * Unmounted ... - * - */ - public Boolean discoverRepoDb() throws Ovm3ResourceException { - postDbDiscovery = callWrapper("discover_repository_db"); - Document xmlDocument = prepParse((String) postDbDiscovery); - String path = "//Discover_Repository_Db_Result/RepositoryDbList/Repository"; - repoDbList = new ArrayList(); - repoDbList.addAll(xmlToList(path + "/@Uuid", xmlDocument)); - for (String id : repoDbList) { - RepoDbDetails repoDb = new RepoDbDetails(); - Map rep = xmlToMap(path + "[@Uuid='" + id + "']", - xmlDocument); - repoDb.setRepoDbDetails(rep); - repoDb.setUuid(id); - repoDbs.put(id, repoDb); - } - return true; - } - -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/RpcTypeFactory.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/RpcTypeFactory.java deleted file mode 100644 index f5818781b0f3..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/RpcTypeFactory.java +++ /dev/null @@ -1,87 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import org.apache.ws.commons.util.NamespaceContextImpl; -import org.apache.xmlrpc.common.TypeFactoryImpl; -import org.apache.xmlrpc.common.XmlRpcController; -import org.apache.xmlrpc.common.XmlRpcStreamConfig; -import org.apache.xmlrpc.parser.NullParser; -import org.apache.xmlrpc.parser.TypeParser; -import org.apache.xmlrpc.parser.AtomicParser; -import org.apache.xmlrpc.serializer.NullSerializer; -import org.apache.xmlrpc.serializer.TypeSerializer; -import org.apache.xmlrpc.serializer.TypeSerializerImpl; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.ContentHandler; - -public class RpcTypeFactory extends TypeFactoryImpl { - - public RpcTypeFactory(XmlRpcController pController) { - super(pController); - } - - @Override - public TypeParser getParser(XmlRpcStreamConfig pConfig, - NamespaceContextImpl pContext, String pURI, String pLocalName) { - if ("".equals(pURI) && NullSerializer.NIL_TAG.equals(pLocalName)) { - return new NullParser(); - } else if ("i8".equals(pLocalName)) { - return new LongTypeParser(); - } else { - return super.getParser(pConfig, pContext, pURI, pLocalName); - } - } - - public TypeSerializer getSerializer(XmlRpcStreamConfig pConfig, - Object pObject) throws SAXException { - if (pObject instanceof Long) { - return new LongTypeSerializer(); - } else { - return super.getSerializer(pConfig, pObject); - } - } - - private class LongTypeSerializer extends TypeSerializerImpl { - /* - * Tag name of an i8 value. - */ - public static final String I8_TAG = "i8"; - /* - * Fully qualified name of an i8 value. - */ - public static final String EX_I8_TAG = "i8"; - @Override - public void write(ContentHandler pHandler, Object pObject) - throws SAXException { - write(pHandler, I8_TAG, EX_I8_TAG, pObject.toString()); - } - } - - private class LongTypeParser extends AtomicParser { - protected void setResult(String pResult) throws SAXException { - try { - super.setResult(Long.valueOf(pResult.trim())); - } catch (NumberFormatException e) { - throw new SAXParseException("Failed to parse long value: " - + pResult, getDocumentLocator()); - } - } - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/StoragePlugin.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/StoragePlugin.java deleted file mode 100644 index 5bfacd275a7f..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/StoragePlugin.java +++ /dev/null @@ -1,884 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.w3c.dom.Document; - -/* - * should become an interface implementation - */ -public class StoragePlugin extends OvmObject { - private static final String EMPTY_STRING = ""; - private static final String PLUGINPATH = "//Discover_Storage_Plugins_Result/storage_plugin_info_list/storage_plugin_info"; - private static final String NFSPLUGIN = "oracle.generic.NFSPlugin.GenericNFSPlugin"; - private static final String FILESYS = "FileSys"; - private static final String STATUS = "status"; - private static final String UUID = "uuid"; - private static final String SSUUID = "ss_uuid"; - private static final String SIZE = "size"; - private static final String FREESIZE = "free_sz"; - private static final String STATE = "state"; - private static final String ACCESSGROUPNAMES = "access_grp_names"; - private static final String ACCESSPATH = "access_path"; - private static final String NAME = "name"; - private static final String MOUNTOPTIONS = "mount_options"; - private static final String ADMINUSER = "admin_user"; - private static final String ADMINHOST = "admin_host"; - private static final String TOTALSIZE = "total_sz"; - private static final String ADMINPASSWORD = "admin_passwd"; - private static final String STORAGEDESC = "storage_desc"; - private static final String ACCESSHOST = "access_host"; - private static final String STORAGETYPE = "storage_type"; - private static final String ALLOCSIZE = "alloc_sz"; - private static final String ACCESSGROUPS = "access_grps"; - private static final String USEDSIZE = "used_sz"; - private static final String FRTYPE = "fr_type"; - private static final String ONDISKSIZE = "ondisk_sz"; - private static final String FSUUID = "fs_uuid"; - private static final String FILEPATH = "file_path"; - private static final String FILESIZE = "file_sz"; - private static final Boolean ACTIVE = true; - - private String getPluginType = NFSPLUGIN; - private List supportedPlugins = new ArrayList(); - private final List someList = new ArrayList(); /* empty */ - private FileProperties fileProperties = new FileProperties(); - private StorageDetails storageDetails = new StorageDetails(); - private StorageServer storageServer = new StorageServer(); - - public StoragePlugin(Connection c) { - setClient(c); - } - - /* uuid has dashes here!, and ss_uuid is the relation to the storage source uuid */ - public class StorageDetails { - private Map storageDetails = new HashMap() { - { - put(STATUS, EMPTY_STRING); - put(UUID, EMPTY_STRING); - put(SSUUID, EMPTY_STRING); - put(SIZE, EMPTY_STRING); - put(FREESIZE, 0); - put(STATE, 0); - put(ACCESSGROUPNAMES, new ArrayList()); - put(ACCESSPATH, EMPTY_STRING); - put(NAME, EMPTY_STRING); - put(MOUNTOPTIONS, new ArrayList()); - } - private static final long serialVersionUID = 3L; - }; - public Map getDetails() { - return storageDetails; - } - public void setDetails(Map details) { - storageDetails = details; - } - public void setSize(String val) { - storageDetails.put(SIZE, val); - } - public String getSize() { - return (String) storageDetails.get(SIZE); - } - public void setFreeSize(String val) { - storageDetails.put(FREESIZE, val); - } - public String getFreeSize() { - return (String) storageDetails.get(FREESIZE); - } - public void setState(Integer val) { - storageDetails.put(STATE, val); - } - public Integer getState() { - return (Integer) storageDetails.get(STATE); - } - public void setStatus(String val) { - storageDetails.put(STATUS, val); - } - public String getStatus() { - return (String) storageDetails.get(STATUS); - } - /* format depends on storagesource type ? */ - public void setAccessPath(String val) { - storageDetails.put(ACCESSPATH, val); - } - public String getAccessPath() { - return (String) storageDetails.get(ACCESSPATH); - } - public void setName(String val) { - storageDetails.put(NAME, val); - } - public String getName() { - return (String) storageDetails.get(NAME); - } - public void setUuid(String val) throws Ovm3ResourceException { - if (!val.contains("-")) { - throw new Ovm3ResourceException("Storage Details UUID should contain dashes: " + val); - } - storageDetails.put(UUID, val); - } - public String getUuid() { - return (String) storageDetails.get(UUID); - } - public void setDetailsRelationalUuid(String val) throws Ovm3ResourceException { - if (val.contains("-")) { - throw new Ovm3ResourceException("Storage Details UUID that relates to Storage Source should notcontain dashes: " + val); - } - storageDetails.put(SSUUID, val); - } - public String getDetailsRelationalUuid() { - return (String) storageDetails.get(SSUUID); - } - public void setAccessGroupNames(List l) { - storageDetails.put(ACCESSGROUPNAMES, l); - } - public List getAccessGroupNames() { - return (List) storageDetails.get(ACCESSGROUPNAMES); - } - public void setMountOptions(List l) { - storageDetails.put(MOUNTOPTIONS, l); - } - public List getMountOptions() { - return (List) storageDetails.get(MOUNTOPTIONS); - } - } - - /* mind you uuid has NO dashes here */ - public class StorageServer { - private Map storageSource = new HashMap() { - { - put(STATUS, EMPTY_STRING); - put(ADMINUSER, EMPTY_STRING); - put(ADMINHOST, EMPTY_STRING); - put(UUID, EMPTY_STRING); - put(TOTALSIZE, 0); - put(ADMINPASSWORD, EMPTY_STRING); - put(STORAGEDESC, EMPTY_STRING); - put(FREESIZE, 0); - put(ACCESSHOST, EMPTY_STRING); - put(STORAGETYPE, EMPTY_STRING); - put(ALLOCSIZE, 0); - put(ACCESSGROUPS, new ArrayList()); - put(USEDSIZE, 0); - put(NAME, EMPTY_STRING); - } - private static final long serialVersionUID = 4L; - }; - public Map getDetails() { - return storageSource; - } - public void setDetails(Map details) { - storageSource = details; - } - public void setAccessGroups(List l) { - storageSource.put(ACCESSGROUPS, l); - } - public List getAccessGroups() { - return (List) storageSource.get(ACCESSGROUPS); - } - public void setStatus(String val) { - storageSource.put(STATUS, val); - } - public String getStatus() { - return (String) storageSource.get(STATUS); - } - public void setAdminUser(String val) { - storageSource.put(ADMINUSER, val); - } - public String getAdminUser() { - return (String) storageSource.get(ADMINUSER); - } - public void setAdminHost(String val) { - storageSource.put(ADMINHOST, val); - } - public String getAdminHost() { - return (String) storageSource.get(ADMINHOST); - } - public void setUuid(String val) throws Ovm3ResourceException { - if (val.contains("-")) { - throw new Ovm3ResourceException("Storage Source UUID should not contain dashes: " + val); - } - storageSource.put(UUID, val); - } - public String getUuid() { - return (String) storageSource.get(UUID); - } - public String getTotalSize() { - return (String) storageSource.get(TOTALSIZE); - } - public void setTotalSize(Integer val) { - storageSource.put(TOTALSIZE, val); - } - public void setAdminPassword(String val) { - storageSource.put("admin_password", val); - } - public String getAdminPassword() { - return (String) storageSource.get("admin_password"); - } - public void setDescription(String val) { - storageSource.put(STORAGEDESC, val); - } - public String getDescription() { - return (String) storageSource.get(STORAGEDESC); - } - public String getFreeSize() { - return (String) storageSource.get(FREESIZE); - } - public void setFreeSize(Integer val) { - storageSource.put(FREESIZE, val); - } - public void setAccessHost(String val) { - storageSource.put(ACCESSHOST, val); - } - public String getAccessHost() { - return (String) storageSource.get(ACCESSHOST); - } - public void setStorageType(String val) { - storageSource.put(STORAGETYPE, val); - } - public String getStorageType() { - return (String) storageSource.get(STORAGETYPE); - } - public void setAllocationSize(Integer val) { - storageSource.put(ALLOCSIZE, val); - } - public Integer getAllocationSize() { - return (Integer) storageSource.get(ALLOCSIZE); - } - public void setUsedSize(Integer val) { - storageSource.put(USEDSIZE, val); - } - public Integer getUsedSize() { - return (Integer) storageSource.get(USEDSIZE); - } - public void setName(String val) { - storageSource.put(NAME, val); - } - public String getName() { - return (String) storageSource.get(NAME); - } - } - - public class FileProperties { - private Map fileProperties = new HashMap() { - { - put(FRTYPE, EMPTY_STRING); - put(ONDISKSIZE, EMPTY_STRING); - put(FSUUID, EMPTY_STRING); - put(FILEPATH, EMPTY_STRING); - put(FILESIZE, EMPTY_STRING); - } - private static final long serialVersionUID = 1234L; - }; - public Map getProperties() { - return fileProperties; - } - public void setProperties(Map props) { - fileProperties = props; - } - public String getName() { - return (String) fileProperties.get(FILEPATH); - } - public String setName(String f) { - return (String) fileProperties.put(FILEPATH, f); - } - public String setType(String t) { - return (String) fileProperties.put(FRTYPE, t); - } - public String getType() { - return (String) fileProperties.get(FRTYPE); - } - public void setSize(Long t) { - fileProperties.put(FILESIZE, t); - } - public Long getSize() { - return Long.parseLong((String) fileProperties.get(FILESIZE)); - } - public String setOnDiskSize(String t) { - return (String) fileProperties.put(ONDISKSIZE, t); - } - public String getOnDiskSize() { - return (String) fileProperties.get(ONDISKSIZE); - } - public String setUuid(String t) { - return (String) fileProperties.put(FSUUID, t); - } - public String getUuid() { - return (String) fileProperties.get(FSUUID); - } - } - - public String getPluginType() { - return getPluginType; - } - private Boolean setPluginType(String val) throws Ovm3ResourceException { - for(String plugin : discoverStoragePlugins()) { - if (plugin.matches("(?i:.*"+val+".*)")) { - getPluginType = plugin; - return true; - } - } - return false; - } - public Boolean setISCSI() throws Ovm3ResourceException { - return setPluginType("SCSI"); - } - public Boolean setOCFS2() throws Ovm3ResourceException { - return setPluginType("OCFS2"); - } - public Boolean setNFS() throws Ovm3ResourceException { - return setPluginType("NFS"); - } - - /* Actions for the storage plugin */ - /* - * storage_plugin_resizeFileSystem, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getStatus, - * argument: impl_name - default: None meh ? - */ - - /* - * storage_plugin_validate, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_setQoS, - * argument: impl_name - default: None - */ - - /* - * now only for files - * storage_plugin_create, argument: impl_name - default: - * None - calls resize secretly.. after "create" - */ - public FileProperties storagePluginCreate(String poolUuid, String host, - String file, Long size, Boolean dir) throws Ovm3ResourceException{ - /* this is correct ordering stuff and correct naming!!! */ - String uuid = deDash(poolUuid); - StorageServer ss = new StorageServer(); - StorageDetails sd = new StorageDetails(); - FileProperties fp = new FileProperties(); - ss.setUuid(uuid); - ss.setStorageType(FILESYS); - ss.setAccessHost(host); - sd.setUuid(poolUuid); - sd.setDetailsRelationalUuid(uuid); - sd.setState(2); - String type = "File"; - if (dir) { - type = "Directory"; - } - fp.setProperties((HashMap) callWrapper("storage_plugin_create", - getPluginType, ss.getDetails(), - sd.getDetails(), file, type, size)); - return fp; - } - - /* - * storage_plugin_createAccessGroups, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_deviceTeardown, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_startPresent, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_listFileSystems, argument: impl_name - default: - * None - */ - public Boolean storagePluginListFs(String host) throws Ovm3ResourceException { - StorageServer ss = new StorageServer(); - ss.setAccessHost(host); - ss.setStorageType(FILESYS); - ss.setDetails((Map) callWrapper("storage_plugin_listFileSystems", - getPluginType, ss.getDetails())); - return true; - } - - /* - * storage_plugin_getFileSystemCloneLimits, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getQoSList, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_stopPresent, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_isCloneable, argument: impl_name - default: - * None - */ - - /** - * . storage_plugin_mount, - * argument: impl_name - default: None - */ - public final StorageDetails storagePluginMountNFS(String nfsHost, String nfsRemotePath, - String mntUuid, String mountPoint) throws Ovm3ResourceException { - String propUuid = deDash(mntUuid); - StorageServer ss = new StorageServer(); - StorageDetails sd = new StorageDetails(); - ss.setUuid(propUuid); - ss.setName(propUuid); - ss.setAccessHost(nfsHost); - sd.setDetailsRelationalUuid(propUuid); - sd.setUuid(mntUuid); - sd.setAccessPath(nfsHost + ":" + nfsRemotePath); - if (!mountPoint.contains(mntUuid)) { - mountPoint += "/" + mntUuid; - } - sd.setDetails((HashMap) callWrapper( - "storage_plugin_mount", getPluginType, ss.getDetails(), - sd.getDetails(), mountPoint, EMPTY_STRING, ACTIVE, - someList)); - /* this magically means it's already mounted.... - * double check */ - if (sd.getDetails() == null) { - sd = storagePluginGetFileSystemInfo(propUuid, - mntUuid, nfsHost, nfsRemotePath); - } - if (EMPTY_STRING.contains(ss.getUuid())) { - throw new Ovm3ResourceException("Unable to mount NFS FileSystem"); - } - return sd; - } - - /** - * . storage_plugin_unmount, - * argument: impl_name - default: None - * - * @return boolean - * - */ - public final Boolean storagePluginUnmountNFS(String nfsHost, String remotePath, String mntUuid, String localPath) throws Ovm3ResourceException { - StorageServer ss = new StorageServer(); - StorageDetails sd = new StorageDetails(); - sd.setUuid(mntUuid); - sd.setDetailsRelationalUuid(deDash(mntUuid)); - ss.setUuid(deDash(mntUuid)); - ss.setAccessHost(nfsHost); - sd.setAccessPath(nfsHost + ":" + remotePath); - sd.setState(1); - ss.setStorageType(FILESYS); - String mountPoint = localPath + "/" + mntUuid; - callWrapper("storage_plugin_unmount", getPluginType, - ss.getDetails(), sd.getDetails(), mountPoint, ACTIVE); - return true; - } - - /* - * storage_plugin_resize, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_deviceSizeRefresh, argument: impl_name - default: - * None - */ - /* - * storage_plugin_getStorageNames, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_splitClone, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_destroyFileSystem, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_snapRestore, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_updateSERecords, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getSnapLimits, argument: impl_name - default: - * None - */ - - /* - * discover_storage_plugins, - */ - public List discoverStoragePlugins() throws Ovm3ResourceException{ - supportedPlugins = new ArrayList(); - Object result = callWrapper("discover_storage_plugins"); - if (result == null) { - return supportedPlugins; - } - Document xmlDocument = prepParse((String) result); - supportedPlugins.addAll(xmlToList(PLUGINPATH + "/@plugin_impl_name", xmlDocument)); - return supportedPlugins; - } - - private Map checkStoragePluginDetails(String plugin, Boolean ability) throws Ovm3ResourceException { - Object result = callWrapper("discover_storage_plugins"); - Document xmlDocument = prepParse((String) result); - if (discoverStoragePlugins().contains(plugin)) { - String details = PLUGINPATH + "[@plugin_impl_name='" + plugin + "']"; - if (ability) { - return xmlToMap(details + "/abilities", xmlDocument); - } else { - return xmlToMap(details, xmlDocument); - } - } else { - throw new Ovm3ResourceException("StoragePlugin should be one of: " + supportedPlugins); - } - } - - private String checkStoragePluginBoth(String type, String property, Boolean ab) throws Ovm3ResourceException{ - String val = checkStoragePluginDetails(type, ab).get(property); - if (val == null) { - throw new Ovm3ResourceException("StoragePlugin " + type + " has no " + property); - } - return val; - } - - public String checkStoragePluginAbility(String type, String property) throws Ovm3ResourceException { - return checkStoragePluginBoth(type, property, true); - } - public String checkStoragePluginProperties(String type, String property) throws Ovm3ResourceException { - return checkStoragePluginBoth(type, property, false); - } - - /* - * storage_plugin_deviceResize, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getCloneLimits, argument: impl_name - default: - * None - */ - - /* - * INFO: is used for files and dirs..., we only implement files for now... - * storage_plugin_destroy, - * argument: impl_name - default: None - */ - public Boolean storagePluginDestroy(String poolUuid, String file) throws Ovm3ResourceException { - String uuid = deDash(poolUuid); - StorageServer ss = new StorageServer(); - StorageDetails sd = new StorageDetails(); - FileProperties fp = new FileProperties(); - ss.setUuid(uuid); - sd.setDetailsRelationalUuid(uuid); - sd.setUuid(poolUuid); - fp.setType("file"); - fp.setUuid(poolUuid); - fp.setName(file); - return nullIsTrueCallWrapper( - "storage_plugin_destroy", getPluginType, ss.getDetails(), - sd.getDetails(), fp.getProperties()); - } - - /* - * storage_plugin_isSnapable, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getDetailsInfo, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_removeFromAccessGroup, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_renameAccessGroup, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_stop, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_createMultiSnap, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getCurrentSnaps, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getFileInfo, argument: impl_name - default: - * None - */ - public FileProperties storagePluginGetFileInfo(String poolUuid, String host, - String file) throws Ovm3ResourceException { - /* file path is the full path */ - String uuid = deDash(poolUuid); - StorageServer ss = new StorageServer(); - StorageDetails sd = new StorageDetails(); - FileProperties fp = new FileProperties(); - ss.setUuid(uuid); - ss.setAccessHost(host); - sd.setUuid(poolUuid); - sd.setDetailsRelationalUuid(uuid); - sd.setState(1); - fp.setName(file); - fp.setProperties((HashMap) callWrapper( - "storage_plugin_getFileInfo", - getPluginType, - ss.getDetails(), - sd.getDetails(), - fp.getProperties())); - if ("".equals(fp.getName())) { - throw new Ovm3ResourceException("Unable to get file info for " + file); - } - return fp; - } - - /* - * Should do some input checking of ss and base - * storage_plugin_getFileSystemInfo, - * argument: impl_name - - * default: None requires a minumum of uuid, access_host, storage_type - * ss_uuid, access_path, uuid (the ss - */ - public StorageDetails storagePluginGetFileSystemInfo(String propUuid, - String mntUuid, String nfsHost, String nfsRemotePath) throws Ovm3ResourceException{ - /* clean the props */ - StorageServer ss = new StorageServer(); - StorageDetails sd = new StorageDetails(); - new FileProperties(); - ss.setUuid(propUuid); - sd.setDetailsRelationalUuid(propUuid); - sd.setUuid(mntUuid); - ss.setAccessHost(nfsHost); - if (nfsRemotePath.contains(nfsHost + ":")) { - sd.setAccessPath(nfsRemotePath); - } else { - sd.setAccessPath(nfsHost + ":" + nfsRemotePath); - } - ss.setStorageType(FILESYS); - sd.setDetails((HashMap) callWrapper( - "storage_plugin_getFileSystemInfo", getPluginType, - ss.getDetails(), sd.getDetails())); - return sd; - } - public StorageDetails getStorageDetails() { - return storageDetails; - } - public void setStorageDetails(StorageDetails storageDetails) { - this.storageDetails = storageDetails; - } - public StorageServer getStorageServer() { - return storageServer; - } - public void setStorageServer(StorageServer storageServer) { - this.storageServer = storageServer; - } - public FileProperties getFileProperties() { - return fileProperties; - } - public void setFileProperties(FileProperties fileProperties) { - this.fileProperties = fileProperties; - } - - /* - * storage_plugin_clone, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_list, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_getInfo, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_snapRemove, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getCapabilities, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_createSnap, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_getFileSystemSnapLimits, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_remove, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_getCurrentClones, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_online, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_isRestorable, argument: impl_name - default: - * None - */ - - /* - * storage_iSCSI_logoutTarget, argument: target - default: None - * argument: portal - default: None - */ - - /* - * storage_plugin_discover, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_start, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_removeAccessGroups, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_refresh, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_getAccessGroups, argument: impl_name - default: - * None - */ - - /* - * storage_iSCSI_deletePortal, argument: portal - default: None - */ - - /* - * storage_plugin_createFileSystem, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_cloneFromSnap, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_addToAccessGroup, argument: impl_name - default: - * None - */ - - /* - * storage_plugin_offline, - * argument: impl_name - default: None - */ - - /* - * storage_plugin_listMountPoints, argument: impl_name - default: - * None - */ -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Xen.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Xen.java deleted file mode 100644 index 90244a8ff574..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/objects/Xen.java +++ /dev/null @@ -1,996 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -public class Xen extends OvmObject { - private static final String VNCLISTEN = "vnclisten"; - private static final String MEMORY = "memory"; - private static final String MAXVCPUS = "maxvcpus"; - private static final String VCPUS = "vcpus"; - private static final String DOMTYPE = "OVM_domain_type"; - private static final String EXTRA = "extra"; - private Map vmList = null; - private Vm defVm = new Vm(); - - public Xen(Connection c) { - setClient(c); - } - - /* - * a vm class.... Setting up a VM is different than retrieving one from OVM. - * It's either a list retrieval or - * /usr/lib64/python2.4/site-packages/agent/lib/xenvm.py - */ - public class Vm { - /* 'vfb': [ 'type=vnc,vncunused=1,vnclisten=127.0.0.1,keymap=en-us'] */ - private static final long serialVersionUID = 1L; - private final List vmVncElement = new ArrayList(); - private Map vmVnc = new HashMap() { - { - put("type", "vnc"); - put("vncunused", "1"); - put(VNCLISTEN, "127.0.0.1"); - put("keymap", "en-us"); - } - private static final long serialVersionUID = 1L; - }; - - /* - * 'disk': [ - * 'file:/OVS/Repositories/0004fb0000030000aeaca859e4a8f8c0/VirtualDisks/0004fb0000120000c444117fd87ea251.img,xvda,w'] - */ - private final List vmDisks = new ArrayList(); - private Map vmDisk = new HashMap() { - { - put("id", ""); - put("uuid", ""); - put("dev", ""); - put("bootable", "1"); - put("mode", "w"); - put("VDI", ""); - put("backend", "0"); - put("protocol", "x86_32-abi"); - put("uname", ""); - } - private static final long serialVersionUID = 1L; - }; - - /* 'vif': [ 'mac=00:21:f6:00:00:00,bridge=c0a80100'] */ - private final ArrayList vmVifs = new ArrayList(); - private final Integer maxVifs = 7; - private final String[] xvmVifs = new String[maxVifs -1]; - private final String vmSimpleName = ""; - private final String vmName = ""; - private final String vmUuid = ""; - /* - * the pool the vm.cfg will live on, this is the same as the primary - * storage pool (should be unified with disk pool ?) - */ - private String vmPrimaryPoolUuid = ""; - private final String vmOnReboot = "restart"; - /* weight is relative for all VMs compared to each other */ - private final int vmCpuWeight = 27500; - /* minimum memory allowed */ - private final int vmMemory = 256; - private final int vmCpuCap = 0; - /* dynam scaling for cpus */ - private final int vmMaxVcpus = 0; - /* default to 1, can't be higher than maxvCpus */ - private final int vmVcpus = 1; - /* high available */ - private final Boolean vmHa = false; - private final String vmDescription = ""; - private final String vmOnPoweroff = "destroy"; - private final String vmOnCrash = "restart"; - private final String vmBootloader = "/usr/bin/pygrub"; - private final String vmBootArgs = ""; - private final String vmExtra = ""; - /* default to linux */ - private final String vmOs = "Other Linux"; - private final String vmCpuCompatGroup = ""; - /* pv is default */ - private final String vmDomainType = "xen_pvm"; - /* start counting disks at A -> 0 */ - private final int diskZero = 97; - private int diskCount = diskZero; - - private Map vmParams = new HashMap() { - { - put("vif", vmVifs); - put("OVM_simple_name", vmSimpleName); - put("disk", vmDisks); - put("bootargs", vmBootArgs); - put("uuid", vmUuid); - put("on_reboot", vmOnReboot); - put("cpu_weight", vmCpuWeight); - put(MEMORY, vmMemory); - put("cpu_cap", vmCpuCap); - put(MAXVCPUS, vmMaxVcpus); - put("OVM_high_availability", vmHa); - put("OVM_description", vmDescription); - put("on_poweroff", vmOnPoweroff); - put("on_crash", vmOnCrash); - put("bootloader", vmBootloader); - put("name", vmName); - put("guest_os_type", vmOs); - put("vfb", vmVncElement); - put(VCPUS, vmVcpus); - put("OVM_cpu_compat_group", vmCpuCompatGroup); - put(DOMTYPE, vmDomainType); - put(EXTRA, vmExtra); - } - private static final long serialVersionUID = 1L; - }; - - public boolean isControlDomain() { - if ("Domain-0".equals(getVmName())) { - return true; - } - return false; - } - - public boolean setPrimaryPoolUuid(String poolId) { - vmPrimaryPoolUuid = poolId; - return true; - } - - public String getPrimaryPoolUuid() throws Ovm3ResourceException { - if ("".equals(vmPrimaryPoolUuid)) { - return getVmRootDiskPoolId(); - } else { - return vmPrimaryPoolUuid; - } - } - - public Map getVmParams() { - return vmParams; - } - - public void setVmParams(Map params) { - vmParams = params; - } - - public boolean setVmExtra(final String args) { - vmParams.put(EXTRA, args); - return true; - } - - public String getVmExtra() { - return (String) vmParams.get(EXTRA); - } - - public String getVmBootArgs() { - return (String) vmParams.get("bootloader_args"); - } - - public void setVmMaxCpus(Integer val) { - vmParams.put(MAXVCPUS, val); - } - - public Integer getVmMaxCpus() { - return (Integer) vmParams.get(MAXVCPUS); - } - - public void setVmCpus(Integer val) { - if (getVmMaxCpus() == 0 || getVmMaxCpus() >= val) { - vmParams.put(VCPUS, val); - } else if (getVmMaxCpus() < val) { - setVmCpus(getVmMaxCpus()); - } - } - - public Integer getVmCpus() { - return (Integer) vmParams.get(VCPUS); - } - - public Boolean setVmMemory(long memory) { - vmParams.put(MEMORY, Long.toString(memory)); - return true; - } - - public long getVmMemory() { - return Integer.parseInt((String) vmParams.get(MEMORY)); - } - - public Boolean setVmDomainType(String domtype) { - vmParams.put(DOMTYPE, domtype); - return true; - } - - /* iiiis this a good idea ? */ - public String getVmDomainType() { - String domType = (String) vmParams.get(DOMTYPE); - if (domType.equals(vmDomainType)) { - String builder = (String) vmParams.get("builder"); - if (builder == null || builder.contains("linux")) { - domType = "xen_pvm"; - } else { - domType = "hvm"; - } - } - return domType; - } - - public String getVmState() { - return (String) vmParams.get("state"); - } - - public Boolean setVmName(String name) { - vmParams.put("name", name); - vmParams.put("OVM_simple_name", name); - return true; - } - - public String getVmName() { - return (String) vmParams.get("name"); - } - - public Boolean setVmUuid(String uuid) { - vmParams.put("uuid", uuid); - return true; - } - - public String getVmUuid() { - return (String) vmParams.get("uuid"); - } - - public void setVmVncs(List vncs) { - vmVncElement.addAll(vncs); - } - - public List getVmVncs() { - return vmVncElement; - } - - public void setVmDisks(List disks) { - vmDisks.addAll(disks); - } - - public List getVmDisks() { - return vmDisks; - } - - public void setVmVifs(List vifs) { - vmVifs.addAll(vifs); - } - - public List getVmVifs() { - return vmVifs; - } - - public Integer getVifIdByMac(String mac) { - Integer c = 0; - for (final String entry : vmVifs) { - final String[] parts = entry.split(","); - final String[] macpart = parts[0].split("="); - assert macpart.length == 2 : "Invalid entry: " + entry; - if ("mac".equals(macpart[0]) && macpart[1].equals(mac)) { - return c; - } - c += 1; - } - logger.debug("No vif matched mac: " + mac + " in " + vmVifs); - return -1; - } - public Integer getVifIdByIp(String ip) { - Integer c = 0; - for (final String entry : vmVifs) { - final String[] parts = entry.split(","); - final String[] ippart = parts[1].split("="); - assert ippart.length == 2 : "Invalid entry: " + entry; - if ("mac".equals(ippart[0]) && ippart[1].equals(ip)) { - return c; - } - c += 1; - } - logger.debug("No vif matched IP: " + ip + " in " + vmVifs); - return -1; - } - - public Boolean addVif(Integer id, String bridge, String mac) { - if (getVifIdByMac(mac) > 0) { - logger.debug("Already nic with mac present: " + mac); - return false; - } - String vif = "mac=" + mac + ",bridge=" + bridge; - xvmVifs[id] = vif; - return true; - } - - public boolean setupVifs() { - for (String vif : xvmVifs) { - if (vif != null && !vmVifs.contains(vif)) { - vmVifs.add(vif); - } - } - vmParams.put("vif", vmVifs); - return true; - } - - public Boolean removeVif(String bridge, String mac) { - List newVifs = new ArrayList(); - try { - String remove = "mac=" + mac + ",bridge=" + bridge; - for (String vif : getVmVifs()) { - if (vif.equals(remove)) { - logger.debug("leaving out vif: " + remove); - } else { - logger.debug("keeping vif: " + vif); - newVifs.add(vif); - } - } - vmParams.put("vif", newVifs); - } catch (Exception e) { - logger.debug(e); - } - return true; - } - - /* 'file:/OVS/Repositories/d5f5a4480515467ca1638554f085b278/ISOs/e14c811ebbf84f0b8221e5b7404a554e.iso,hdc:cdrom,r' */ - /* device is coupled with vmtype enumerate and cdboot ? */ - public Boolean addRootDisk(String image) { - Boolean ret = false; - if (diskCount > diskZero) { - Integer oVmDisk = diskCount; - diskCount = diskZero; - ret = addDisk(image, "w"); - diskCount = oVmDisk; - } else { - ret = addDisk(image, "w"); - } - return ret; - } - - public Boolean addDataDisk(String image) { - /* - * w! means we're able to share the disk nice for clustered FS? - */ - return addDisk(image, "w!"); - } - - public Boolean addIso(String image) { - return addDisk(image, "r!"); - } - - private Boolean addDisk(String image, String mode) { - String devName = null; - /* better accounting then diskCount += 1 */ - diskCount = diskZero + vmDisks.size(); - if (getVmDomainType().contains("hvm")) { - diskCount += 2; - devName = Character.toString((char) diskCount); - } else { - devName = "xvd" + Character.toString((char) diskCount); - } - - /* check for iso, force mode and additions */ - if (image.endsWith(".iso")) { - devName = devName + ":cdrom"; - mode = "r"; - } - return addDiskToDisks(image, devName, mode); - } - - /* should be on device id too, or else we get random attaches... */ - private Boolean addDiskToDisks(String image, String devName, String mode) { - for (String disk : vmDisks) { - if (disk.contains(image)) { - logger.debug(vmName + " already has disk " +image+ ":" + devName + ":" + mode); - return true; - } - } - vmDisks.add("file:" + image + "," + devName + "," + mode); - vmParams.put("disk", vmDisks); - return true; - } - - public Boolean removeDisk(String image) { - for (String disk : vmDisks) { - if (disk.contains(image)) { - vmDisks.remove(disk); - vmParams.put("disk", vmDisks); - return true; - } - } - logger.debug("No disk found corresponding to image: " + image); - return false; - } - - /* The conflict between getVm and getVmConfig becomes clear */ - public String getVmRootDiskPoolId() throws Ovm3ResourceException { - String poolId = getVmDiskPoolId(0); - setPrimaryPoolUuid(poolId); - return poolId; - } - - private String getVmDiskPoolId(int disk) throws Ovm3ResourceException { - int fi = 3; - String diskPath = ""; - try { - diskPath = getVmDiskDetailFromMap(disk, "uname"); - } catch (NullPointerException e) { - throw new Ovm3ResourceException("No valid disk found for id: " - + disk); - } - String[] st = diskPath.split("/"); - return st[fi]; - } - - private String getVmDiskDetailFromMap(int disk, String dest) { - Map o = (Map) vmParams - .get("device"); - if (o == null) { - logger.info("No devices found" + vmName); - return null; - } - vmDisk = (Map) o.get("vbd")[disk]; - return vmDisk.get(dest); - } - - private boolean setVnc() { - List vfb = new ArrayList(); - for (final String key : vmVnc.keySet()) { - vfb.add(key + "=" + vmVnc.get(key)); - } - vmVncElement.add(StringUtils.join(vfb, ",")); - return true; - } - - public Boolean setVnc(String address, String password) { - setVncAddress(address); - setVncPassword(password); - return setVnc(); - } - - public void setVncUsed(String used) { - vmVnc.put("vncused", used); - } - - public String getVncUsed() { - return vmVnc.get("vncused"); - } - - public void setVncPassword(String pass) { - vmVnc.put("vncpasswd", pass); - } - - public String getVncPassword() { - return vmVnc.get("vncpasswd"); - } - - public void setVncAddress(String address) { - vmVnc.put(VNCLISTEN, address); - } - - public String getVncAddress() throws Ovm3ResourceException { - Integer port = getVncPort(); - if (port == null) { - return null; - } - return vmVnc.get(VNCLISTEN); - } - - public Integer getVncPort() throws Ovm3ResourceException { - if (getFromVncMap("port") != null) { - return Integer.parseInt(getFromVncMap("port")); - } - String vnc = getVncLocation(); - if (vnc != null && vnc.contains(":")) { - final String[] res = vnc.split(":"); - vmVnc.put(VNCLISTEN, res[0]); - vmVnc.put("port", res[1]); - return Integer.parseInt(res[1]); - } - throw new Ovm3ResourceException("No VNC port found"); - } - - public String getVncLocation() { - return getFromVncMap("location"); - } - - private String getFromVncMap(String el) { - Map o = (Map) vmParams - .get("device"); - if (o == null) { - return null; - } - vmVnc = (Map) o.get("vfb")[0]; - if (vmVnc.containsKey(el)) { - return vmVnc.get(el); - } else { - return null; - } - } - - private Object get(String key) { - return vmParams.get(key); - } - } - - /* - * delete_assembly, argument: self - * - default: None argument: repo_id - default: None argument: assembly_id - - * default: None - */ - - /* - * unconfigure_template, argument: - * self - default: None argument: repo_id - default: None argument: - * template_id - default: None argument: params - default: None - */ - - /* - * sysrq_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: letter - default: None - */ - - /* - * list_vms, argument: self - - * default: None - */ - public Map listVms() throws Ovm3ResourceException { - Object[] result = (Object[]) callWrapper("list_vms"); - if (result == null) { - logger.debug("no vm results on list_vms"); - return null; - } - - try { - vmList = new HashMap(); - for (Object x : result) { - /* put the vmparams in, as x is a hashmap */ - Vm vm = new Vm(); - vm.setVmParams((Map) x); - vmList.put((String) vm.get("name"), vm); - } - } catch (Exception e) { - String msg = "Unable to list VMs: " + e.getMessage(); - throw new Ovm3ResourceException(msg, e); - } - return vmList; - } - - /* - * this should become getVmConfig later... getVmConfig returns the - * configuration file, while getVm returns the "live" configuration. It - * makes perfect sense if you think about it..... ....long enough - */ - public Vm getRunningVmConfig(String name) throws Ovm3ResourceException { - return getRunningVmConfigs().get(name); - } - - public Map getRunningVmConfigs() throws Ovm3ResourceException { - return listVms(); - } - - /* - * delete_vm_core, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: core_date - default: None - */ - - /* - * delete_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ - public Boolean deleteVm(String repoId, String vmId) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("delete_vm", repoId, vmId); - } - - /* - * save_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: checkpoint - default: None - *//* add checkpoint */ - - /* - * configure_template, argument: - * self - default: None argument: repo_id - default: None argument: - * template_id - default: None argument: params - default: None - */ - - /* - * create_template, argument: self - * - default: None argument: repo_id - default: None argument: template_id - - * default: None argument: params - default: None - */ - - /* - * list_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ - - public Boolean listVm(String repoId, String vmId) - throws Ovm3ResourceException { - defVm.setVmParams((Map) callWrapper("list_vm", repoId, - vmId)); - if (defVm.getVmParams() == null) { - logger.debug("no vm results on list_vm"); - return false; - } - return true; - } - - /* - * dump_vm_core, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: live - default: None argument: crash - default: - * None argument: reset - default: None - */ - - /* - * assembly_del_file, argument: - * self - default: None argument: repo_id - default: None argument: - * assembly_id - default: None argument: filename - default: None - */ - - /* - * get_template_config, argument: - * self - default: None argument: repo_id - default: None argument: - * template_id - default: None - */ - - /* - * set_assembly_config_xml, - * argument: self - default: None argument: repo_id - default: None - * argument: assembly_id - default: None argument: cfg - default: None - */ - - /* - * assembly_add_file, argument: - * self - default: None argument: repo_id - default: None argument: - * assembly_id - default: None argument: url - default: None argument: - * filename - default: None argument: option - default: None - */ - - /* - * send_to_guest, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: params - default: None - */ - - /* - * set_assembly_config, argument: - * self - default: None argument: repo_id - default: None argument: - * assembly_id - default: None argument: cfg - default: None - */ - - /* - * configure_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: params - default: None - */ - private Boolean configureVm(String repoId, String vmId, - Map params) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("configure_vm", repoId, vmId, params); - } - - public Boolean configureVm(String repoId, String vmId) - throws Ovm3ResourceException { - return configureVm(repoId, vmId, defVm.getVmParams()); - } - - /* - * cleanup_migration_target, - * argument: self - default: None argument: repo_id - default: None - * argument: vm_id - default: None - */ - - /* - * pause_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ - public Boolean pauseVm(String repoId, String vmId) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("pause_vm", repoId, vmId); - } - - /* - * setup_migration_target, - * argument: self - default: None argument: repo_id - default: None - * argument: vm_id - default: None - */ - - /* - * deploy_assembly, argument: self - * - default: None argument: repo_id - default: None argument: assembly_id - - * default: None argument: to_deploy - default: None argument: - * target_repo_id - default: None argument: option - default: None - */ - - /* - * stop_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: force - default: None - */ - public Boolean stopVm(String repoId, String vmId) - throws Ovm3ResourceException { - Object x = callWrapper("stop_vm", repoId, vmId, false); - if (x == null) { - return true; - } - return false; - } - - public Boolean stopVm(String repoId, String vmId, Boolean force) - throws Ovm3ResourceException { - Object x = callWrapper("stop_vm", repoId, vmId, force); - if (x == null) { - return true; - } - return false; - } - - /* - * set_template_config, argument: - * self - default: None argument: repo_id - default: None argument: - * template_id - default: None argument: params - default: None - */ - - /* - * assembly_rename_file, argument: - * self - default: None argument: repo_id - default: None argument: - * assembly_id - default: None argument: filename - default: None argument: - * new_filename - default: None - */ - - /* - * migrate_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: dest - default: None argument: live - default: - * None argument: ssl - default: None - */ - public Boolean migrateVm(String repoId, String vmId, String dest) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("migrate_vm", repoId, vmId, dest); - } - - public Boolean migrateVm(String repoId, String vmId, String dest, - boolean live, boolean ssl) throws Ovm3ResourceException { - Object x = callWrapper("migrate_vm", repoId, vmId, dest, live, ssl); - if (x == null) { - return true; - } - return false; - } - - /* - * configure_vm_ha, argument: self - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: enable_ha - default: None - */ - public Boolean configureVmHa(String repoId, String vmId, Boolean ha) - throws Ovm3ResourceException { - Object x = callWrapper("configure_vm_ha", repoId, vmId, ha); - if (x == null) { - return true; - } - return false; - } - - /* - * create_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: params - default: None - */ - public Boolean createVm(String repoId, String vmId) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("create_vm", repoId, vmId, - defVm.getVmParams()); - } - - public Boolean createVm(String repoId, String vmId, - Map vmParams) throws Ovm3ResourceException { - return nullIsTrueCallWrapper("create_vm", repoId, vmId, vmParams); - } - - /* - * pack_assembly, argument: self - - * default: None argument: repo_id - default: None argument: assembly_id - - * default: None - */ - - /* - * restore_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: paused - default: None - */ - - /* - * start_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ - public Boolean startVm(String repoId, String vmId) - throws Ovm3ResourceException { - return nullIsTrueCallWrapper("start_vm", repoId, vmId); - } - - /* - * unpause_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ - - /* - * trigger_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: name - default: None argument: vcpu - default: - * None - */ - - /* - * set_vm_config, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: params - default: None - */ - - /* - * delete_template, argument: self - * - default: None argument: repo_id - default: None argument: template_id - - * default: None - */ - - /* - * reboot_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: wait - default: None - */ - public Boolean rebootVm(String repoId, String vmId, int wait) - throws Ovm3ResourceException { - Object x = callWrapper("reboot_vm", repoId, vmId, wait); - if (x == null) { - return true; - } - return false; - } - - public Boolean rebootVm(String repoId, String vmId) - throws Ovm3ResourceException { - Object x = callWrapper("reboot_vm", repoId, vmId, 3); - if (x == null) { - return true; - } - return false; - } - - /* - * unpack_assembly, argument: self - * - default: None argument: repo_id - default: None argument: assembly_id - - * default: None - */ - - /* - * get_vm_config, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ - public Vm getVmConfig(String vmName) throws Ovm3ResourceException { - defVm = getRunningVmConfig(vmName); - if (defVm == null) { - logger.debug("Unable to retrieve running config for " + vmName); - return defVm; - } - return getVmConfig(defVm.getVmRootDiskPoolId(), defVm.getVmUuid()); - } - - public Vm getVmConfig() { - return defVm; - } - - /* - * returns the configuration file contents, so we parse it for configuration - * alterations we might want to do (/$repo/VirtualMachines/$uuid/vm.cfg) - */ - public Vm getVmConfig(String repoId, String vmId) - throws Ovm3ResourceException { - try { - Xen.Vm nVm = new Xen.Vm(); - Map x = (Map) callWrapper( - "get_vm_config", repoId, vmId); - if (x == null) { - logger.debug("Unable to find vm with id:" + vmId + " on repoId:" + repoId); - return nVm; - } - nVm.setVmVifs(Arrays.asList(Arrays.copyOf(x.get("vif"), - x.get("vif").length, String[].class))); - x.remove("vif"); - nVm.setVmDisks(Arrays.asList(Arrays.copyOf(x.get("disk"), - x.get("disk").length, String[].class))); - x.remove("disk"); - nVm.setVmVncs(Arrays.asList(Arrays.copyOf(x.get("vfb"), - x.get("vfb").length, String[].class))); - x.remove("vfb"); - Map remains = new HashMap(); - for (final Map.Entry not : x.entrySet()) { - remains.put(not.getKey(), not.getValue()); - } - nVm.setVmParams(remains); - nVm.setPrimaryPoolUuid(repoId); - /* to make sure stuff doesn't blow up in our face... */ - defVm = nVm; - return nVm; - } catch (Ovm3ResourceException e) { - throw e; - } - } - - /* - * get_assembly_config_xml, - * argument: self - default: None argument: repo_id - default: None - * argument: assembly_id - default: None - */ - - /* - * import_assembly, argument: self - * - default: None argument: repo_id - default: None argument: assembly_id - - * default: None argument: url - default: None argument: option - default: - * None - */ - - /* - * create_assembly, argument: self - * - default: None argument: repo_id - default: None argument: assembly_id - - * default: None argument: templates - default: None - */ - - /* - * get_assembly_config, argument: - * self - default: None argument: repo_id - default: None argument: - * assembly_id - default: None - */ - - /* - * unconfigure_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: params - default: None - */ - - /* - * import_template, argument: self - * - default: None argument: repo_id - default: None argument: template_id - - * default: None argument: url_list - default: None argument: option - - * default: None - */ - - /* - * import_vm, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None argument: url_list - default: None argument: option - - * default: None - */ - - /* - * list_vm_core, argument: self - - * default: None argument: repo_id - default: None argument: vm_id - - * default: None - */ -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3Discoverer.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3Discoverer.java deleted file mode 100755 index 52cc419ad2e4..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3Discoverer.java +++ /dev/null @@ -1,414 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - - -import com.cloud.agent.AgentManager; -import com.cloud.agent.Listener; -import com.cloud.agent.api.AgentControlAnswer; -import com.cloud.agent.api.AgentControlCommand; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.configuration.Config; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.exception.DiscoveryException; -import com.cloud.host.Host; -import com.cloud.host.HostInfo; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Linux; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.resource.Discoverer; -import com.cloud.resource.DiscovererBase; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.utils.UuidUtils; -import com.cloud.utils.db.QueryBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.ssh.SSHCmdHelper; - -public class Ovm3Discoverer extends DiscovererBase implements Discoverer, - Listener, ResourceStateAdapter { - protected String publicNetworkDevice; - protected String privateNetworkDevice; - protected String guestNetworkDevice; - protected String storageNetworkDevice; - - @Inject - ClusterDao clusterDao; - @Inject - ClusterDetailsDao clusterDetailsDao; - @Inject - ResourceManager resourceMgr; - @Inject - AgentManager agentMgr; - @Inject - HostDao hostDao = null; - - protected Ovm3Discoverer() { - } - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - boolean success = super.configure(name, params); - if (!success) { - return false; - } - - /* these are in Config.java */ - publicNetworkDevice = _params.get(Config.Ovm3PublicNetwork.key()); - privateNetworkDevice = _params.get(Config.Ovm3PrivateNetwork.key()); - guestNetworkDevice = _params.get(Config.Ovm3GuestNetwork.key()); - storageNetworkDevice = _params.get(Config.Ovm3StorageNetwork.key()); - resourceMgr.registerResourceStateAdapter(this.getClass() - .getSimpleName(), this); - return true; - } - - @Override - public boolean stop() { - resourceMgr.unregisterResourceStateAdapter(this.getClass() - .getSimpleName()); - return super.stop(); - } - - private boolean checkIfExisted(String guid) { - QueryBuilder sc = QueryBuilder.create(HostVO.class); - sc.and(sc.entity().getGuid(), SearchCriteria.Op.EQ, guid); - sc.and(sc.entity().getHypervisorType(), SearchCriteria.Op.EQ, - HypervisorType.Ovm3); - List hosts = sc.list(); - return !hosts.isEmpty(); - } - - private boolean CheckUrl(URI url) throws DiscoveryException { - if ("http".equals(url.getScheme()) || "https".equals(url.getScheme())) { - String msg = "Discovering " + url + ": " + _params; - logger.debug(msg); - } else { - String msg = "urlString is not http(s) so we're not taking care of the discovery for this: " - + url; - logger.info(msg); - throw new DiscoveryException(msg); - } - return true; - } - - @Override - public Map> find(long dcId, - Long podId, Long clusterId, URI url, String username, - String password, List hostTags) throws DiscoveryException { - Connection c = null; - - CheckUrl(url); - if (clusterId == null) { - String msg = "must specify cluster Id when add host"; - logger.info(msg); - throw new DiscoveryException(msg); - } - - if (podId == null) { - String msg = "must specify pod Id when add host"; - logger.info(msg); - throw new DiscoveryException(msg); - } - - ClusterVO cluster = clusterDao.findById(clusterId); - if (cluster == null - || (cluster.getHypervisorType() != HypervisorType.Ovm3)) { - String msg = "invalid cluster id or cluster is not for Ovm3 hypervisors"; - logger.info(msg); - throw new DiscoveryException(msg); - } else { - logger.debug("cluster: " + cluster); - } - - String agentUsername = _params.get("agentusername"); - if (agentUsername == null) { - String msg = "Agent user name must be specified"; - logger.info(msg); - throw new DiscoveryException(msg); - } - - String agentPassword = _params.get("agentpassword"); - if (agentPassword == null) { - String msg = "Agent password must be specified"; - logger.info(msg); - throw new DiscoveryException(msg); - } - - String agentPort = _params.get("agentport"); - if (agentPort == null) { - String msg = "Agent port must be specified"; - logger.info(msg); - throw new DiscoveryException(msg); - } - - try { - String hostname = url.getHost(); - - InetAddress ia = InetAddress.getByName(hostname); - String hostIp = ia.getHostAddress(); - String guid = UuidUtils.nameUUIDFromBytes(hostIp.getBytes("UTF8")) - .toString(); - - if (checkIfExisted(guid)) { - String msg = "The host " + hostIp + " has been added before"; - logger.info(msg); - throw new DiscoveryException(msg); - } - - logger.debug("Ovm3 discover is going to disover host having guid " - + guid); - - ClusterVO clu = clusterDao.findById(clusterId); - if (clu.getGuid() == null) { - clu.setGuid(UUID.randomUUID().toString()); - } - clusterDao.update(clusterId, clu); - Map clusterDetails = clusterDetailsDao - .findDetails(clusterId); - String ovm3vip = (clusterDetails.get("ovm3vip") == null) ? "" - : clusterDetails.get("ovm3vip"); - String ovm3pool = (clusterDetails.get("ovm3pool") == null) ? "false" - : clusterDetails.get("ovm3pool"); - String ovm3cluster = (clusterDetails.get("ovm3cluster") == null) ? "false" - : clusterDetails.get("ovm3cluster"); - - /* should perhaps only make this connect to the agent port ? */ - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection( - hostIp, 22); - sshConnection.connect(null, 60000, 60000); - sshConnection = SSHCmdHelper.acquireAuthorizedConnection(hostIp, - username, password); - if (sshConnection == null) { - String msg = "Cannot Ssh to Ovm3 host(IP=" + hostIp - + ", username=" + username - + ", password=*******), discovery failed"; - logger.warn(msg); - throw new DiscoveryException(msg); - } - - Map details = new HashMap(); - Ovm3HypervisorResource ovmResource = new Ovm3HypervisorResource(); - details.put("ip", hostIp); - details.put("host", hostname); - details.put("username", username); - details.put("password", password); - details.put("zone", Long.toString(dcId)); - details.put("guid", guid); - details.put("pod", Long.toString(podId)); - details.put("cluster", Long.toString(clusterId)); - details.put("agentusername", agentUsername); - details.put("agentpassword", agentPassword); - details.put("agentport", agentPort.toString()); - details.put("ovm3vip", ovm3vip); - details.put("ovm3pool", ovm3pool); - details.put("ovm3cluster", ovm3cluster); - - if (publicNetworkDevice != null) { - details.put("public.network.device", publicNetworkDevice); - } - if (privateNetworkDevice != null) { - details.put("private.network.device", privateNetworkDevice); - } - if (guestNetworkDevice != null) { - details.put("guest.network.device", guestNetworkDevice); - } - if (storageNetworkDevice != null) { - details.put("storage.network.device", storageNetworkDevice); - } - - Map params = new HashMap(); - params.putAll(details); - - ovmResource.configure(hostname, params); - ovmResource.start(); - - c = new Connection(hostIp, Integer.parseInt(agentPort), - agentUsername, agentPassword); - - /* After resource start, we are able to execute our agent api */ - Linux host = new Linux(c); - details.put("agentVersion", host.getAgentVersion()); - details.put(HostInfo.HOST_OS_KERNEL_VERSION, - host.getHostKernelRelease()); - details.put(HostInfo.HOST_OS, host.getHostOs()); - details.put(HostInfo.HOST_OS_VERSION, host.getHostOsVersion()); - details.put(HostInfo.HYPERVISOR_VERSION, - host.getHypervisorVersion()); - - Map> resources = new HashMap>(); - resources.put(ovmResource, details); - return resources; - } catch (UnknownHostException e) { - logger.error( - "Host name resolve failed exception, Unable to discover Ovm3 host: " - + url.getHost(), e); - return null; - } catch (ConfigurationException e) { - logger.error( - "Configure resource failed, Unable to discover Ovm3 host: " - + url.getHost(), e); - return null; - } catch (IOException | Ovm3ResourceException e) { - logger.error("Unable to discover Ovm3 host: " + url.getHost(), e); - return null; - } - } - - @Override - public void postDiscovery(List hosts, long msId) - throws CloudRuntimeException { - logger.debug("postDiscovery: " + hosts); - } - - @Override - public boolean matchHypervisor(String hypervisor) { - return HypervisorType.Ovm3.toString().equalsIgnoreCase(hypervisor); - } - - @Override - public HypervisorType getHypervisorType() { - return HypervisorType.Ovm3; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, - StartupCommand[] cmd) { - logger.debug("createHostVOForConnectedAgent: " + host); - return null; - } - - @Override - public boolean processAnswers(long agentId, long seq, Answer[] answers) { - logger.debug("processAnswers: " + agentId); - return false; - } - - @Override - public boolean processCommands(long agentId, long seq, Command[] commands) { - logger.debug("processCommands: " + agentId); - return false; - } - - @Override - public AgentControlAnswer processControlCommand(long agentId, - AgentControlCommand cmd) { - logger.debug("processControlCommand: " + agentId); - return null; - } - - @Override - public void processHostAdded(long hostId) { - } - - /* for reconnecting */ - @Override - public void processConnect(Host host, StartupCommand cmd, - boolean forRebalance) { - logger.debug("processConnect"); - } - - @Override - public boolean processDisconnect(long agentId, Status state) { - logger.debug("processDisconnect"); - return false; - } - - @Override - public void processHostAboutToBeRemoved(long hostId) { - } - - @Override - public void processHostRemoved(long hostId, long clusterId) { - } - - @Override - public boolean isRecurring() { - return false; - } - - @Override - public int getTimeout() { - logger.debug("getTimeout"); - return 0; - } - - @Override - public boolean processTimeout(long agentId, long seq) { - logger.debug("processTimeout: " + agentId); - return false; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, - StartupCommand[] startup, ServerResource resource, - Map details, List hostTags) { - logger.debug("createHostVOForDirectConnectAgent: " + host); - StartupCommand firstCmd = startup[0]; - if (!(firstCmd instanceof StartupRoutingCommand)) { - return null; - } - - StartupRoutingCommand ssCmd = (StartupRoutingCommand) firstCmd; - if (ssCmd.getHypervisorType() != HypervisorType.Ovm3) { - return null; - } - - return resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.Ovm3, - details, hostTags); - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, - boolean isForceDeleteStorage) throws UnableDeleteHostException { - logger.debug("deleteHost: " + host); - if (host.getType() != com.cloud.host.Host.Type.Routing - || host.getHypervisorType() != HypervisorType.Ovm3) { - return null; - } - - resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage); - return new DeleteHostAnswer(true); - } - -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3FenceBuilder.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3FenceBuilder.java deleted file mode 100755 index eb83572fc2b8..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3FenceBuilder.java +++ /dev/null @@ -1,115 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.FenceAnswer; -import com.cloud.agent.api.FenceCommand; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.ha.FenceBuilder; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceManager; -import com.cloud.utils.component.AdapterBase; -import com.cloud.vm.VirtualMachine; - -public class Ovm3FenceBuilder extends AdapterBase implements FenceBuilder { - Map fenceParams; - @Inject - AgentManager agentMgr; - @Inject - ResourceManager resourceMgr; - - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - fenceParams = params; - return true; - } - - @Override - public boolean start() { - /* start the agent here ? */ - return true; - } - - @Override - public boolean stop() { - /* stop the agent here ? */ - return true; - } - - public Ovm3FenceBuilder() { - super(); - } - - @Override - public Boolean fenceOff(VirtualMachine vm, Host host) { - if (host.getHypervisorType() != HypervisorType.Ovm3) { - logger.debug("Don't know how to fence non Ovm3 hosts " - + host.getHypervisorType()); - return null; - } else { - logger.debug("Fencing " + vm + " on host " + host - + " with params: "+ fenceParams ); - } - - List hosts = resourceMgr.listAllHostsInCluster(host - .getClusterId()); - FenceCommand fence = new FenceCommand(vm, host); - - for (HostVO h : hosts) { - if (h.getHypervisorType() == HypervisorType.Ovm3 && - h.getStatus() == Status.Up && - h.getId() != host.getId()) { - FenceAnswer answer; - try { - answer = (FenceAnswer) agentMgr.send(h.getId(), fence); - } catch (AgentUnavailableException | OperationTimedoutException e) { - if (logger.isDebugEnabled()) { - logger.debug("Moving on to the next host because " - + h.toString() + " is unavailable", e); - } - continue; - } - if (answer != null && answer.getResult()) { - return true; - } - } - } - - if (logger.isDebugEnabled()) { - logger.debug("Unable to fence off " + vm.toString() + " on " - + host.toString()); - } - - return false; - } - -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorGuru.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorGuru.java deleted file mode 100755 index 77663d9bf045..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorGuru.java +++ /dev/null @@ -1,69 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import javax.inject.Inject; - -import org.apache.cloudstack.storage.command.StorageSubSystemCommand; - -import com.cloud.agent.api.Command; -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.HypervisorGuru; -import com.cloud.hypervisor.HypervisorGuruBase; -import com.cloud.storage.GuestOSVO; -import com.cloud.storage.dao.GuestOSDao; -import com.cloud.utils.Pair; -import com.cloud.vm.VirtualMachineProfile; - -public class Ovm3HypervisorGuru extends HypervisorGuruBase implements HypervisorGuru { - @Inject - private GuestOSDao guestOsDao; - - @Override - public HypervisorType getHypervisorType() { - return HypervisorType.Ovm3; - } - - @Override - public VirtualMachineTO implement(VirtualMachineProfile vm) { - VirtualMachineTO to = toVirtualMachineTO(vm); - to.setBootloader(vm.getBootLoaderType()); - - GuestOSVO guestOS = guestOsDao.findById(vm.getVirtualMachine() - .getGuestOSId()); - to.setOs(guestOS.getDisplayName()); - - return to; - } - - @Override - public boolean trackVmHostChange() { - return true; - } - - @Override - public Pair getCommandHostDelegation(long hostId, Command cmd) { - logger.debug("getCommandHostDelegation: " + cmd.getClass()); - if (cmd instanceof StorageSubSystemCommand) { - StorageSubSystemCommand c = (StorageSubSystemCommand)cmd; - c.setExecuteInSequence(true); - } - return new Pair(Boolean.FALSE, Long.valueOf(hostId)); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResource.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResource.java deleted file mode 100644 index d01738ea0863..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResource.java +++ /dev/null @@ -1,536 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import java.nio.charset.Charset; -import java.util.Map; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.storage.command.AttachCommand; -import org.apache.cloudstack.storage.command.CopyCommand; -import org.apache.cloudstack.storage.command.CreateObjectCommand; -import org.apache.cloudstack.storage.command.StorageSubSystemCommand; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AttachIsoCommand; -import com.cloud.agent.api.CheckHealthCommand; -import com.cloud.agent.api.CheckNetworkCommand; -import com.cloud.agent.api.CheckOnHostCommand; -import com.cloud.agent.api.CheckVirtualMachineCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; -import com.cloud.agent.api.CreateStoragePoolCommand; -import com.cloud.agent.api.DeleteStoragePoolCommand; -import com.cloud.agent.api.FenceCommand; -import com.cloud.agent.api.GetHostStatsCommand; -import com.cloud.agent.api.GetStorageStatsCommand; -import com.cloud.agent.api.GetVmStatsCommand; -import com.cloud.agent.api.GetVncPortCommand; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.MigrateCommand; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.agent.api.NetworkRulesSystemVmCommand; -import com.cloud.agent.api.NetworkUsageCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.PingRoutingCommand; -import com.cloud.agent.api.PingTestCommand; -import com.cloud.agent.api.PlugNicCommand; -import com.cloud.agent.api.PrepareForMigrationCommand; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.RebootAnswer; -import com.cloud.agent.api.RebootCommand; -import com.cloud.agent.api.StartAnswer; -import com.cloud.agent.api.StartCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.agent.api.StartupStorageCommand; -import com.cloud.agent.api.StopAnswer; -import com.cloud.agent.api.StopCommand; -import com.cloud.agent.api.UnPlugNicCommand; -import com.cloud.agent.api.check.CheckSshCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.DestroyCommand; -import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; -import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; -import com.cloud.host.Host.Type; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Common; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.Xen; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3Configuration; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3HypervisorNetwork; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3HypervisorSupport; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3StoragePool; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3VirtualRoutingSupport; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3VmGuestTypes; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3VmSupport; -import com.cloud.network.Networks.TrafficType; -import com.cloud.resource.ServerResourceBase; -import com.cloud.resource.hypervisor.HypervisorResource; -import com.cloud.storage.resource.StorageSubsystemCommandHandler; -import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; -import com.cloud.template.VirtualMachineTemplate.BootloaderType; -import com.cloud.utils.UuidUtils; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; - -public class Ovm3HypervisorResource extends ServerResourceBase implements HypervisorResource { - @Inject - private VirtualRoutingResource vrResource; - private StorageSubsystemCommandHandler storageHandler; - private Connection c; - private Ovm3StoragePool storagepool; - private Ovm3StorageProcessor storageprocessor; - private Ovm3HypervisorSupport hypervisorsupport; - private Ovm3VmSupport vmsupport; - private Ovm3HypervisorNetwork hypervisornetwork; - private Ovm3VirtualRoutingResource virtualroutingresource; - private Ovm3VirtualRoutingSupport virtualroutingsupport; - private Ovm3Configuration configuration; - private Ovm3VmGuestTypes guesttypes; - private final OvmObject ovmObject = new OvmObject(); - - @Override - public Type getType() { - return Type.Routing; - } - - /* - * configure is called before this, does setup of the connection and - * gets the params. - * - * @see com.cloud.resource.ServerResource#initialize() - */ - @Override - public StartupCommand[] initialize() { - logger.debug("Ovm3 resource intializing"); - try { - StartupRoutingCommand srCmd = new StartupRoutingCommand(); - StartupStorageCommand ssCmd = new StartupStorageCommand(); - - /* here stuff gets completed, but where should state live ? */ - hypervisorsupport.fillHostInfo(srCmd); - hypervisorsupport.vmStateMapClear(); - logger.debug("Ovm3 pool " + ssCmd + " " + srCmd); - return new StartupCommand[] {srCmd, ssCmd}; - } catch (Exception e) { - logger.debug("Ovm3 resource initializes failed", e); - return new StartupCommand[] {}; - } - } - - @Override - public PingCommand getCurrentStatus(long id) { - try { - /* feels useless somehow */ - Common test = new Common(c); - String ping = "put"; - String pong = test.echo(ping); - if (pong.contains(ping)) { - hypervisorsupport.syncState(); - CloudstackPlugin cSp = new CloudstackPlugin(c); - if (!cSp.dom0CheckStorageHealthCheck(configuration.getAgentScriptsDir(), configuration.getAgentCheckStorageScript(), configuration.getCsHostGuid(), - configuration.getAgentStorageCheckTimeout(), configuration.getAgentStorageCheckInterval()) && !cSp.dom0CheckStorageHealthCheck()) { - logger.error("Storage health check not running on " + configuration.getAgentHostname()); - } else if (cSp.dom0CheckStorageHealthCheck()) { - logger.error("Storage health check started on " + configuration.getAgentHostname()); - } else { - logger.debug("Storage health check running on " + configuration.getAgentHostname()); - } - return new PingRoutingCommand(getType(), id, hypervisorsupport.hostVmStateReport()); - } else { - logger.debug("Agent did not respond correctly: " + ping + " but got " + pong); - } - - } catch (Ovm3ResourceException | NullPointerException e) { - logger.debug("Check agent status failed", e); - return null; - } - return null; - } - - @Override - public Answer executeRequest(Command cmd) { - Class clazz = cmd.getClass(); - logger.debug("executeRequest called: " + cmd.getClass()); - if (cmd instanceof NetworkElementCommand) { - return vrResource.executeRequest((NetworkElementCommand)cmd); - } else if (clazz == NetworkRulesSystemVmCommand.class) { - return virtualroutingsupport.execute((NetworkRulesSystemVmCommand)cmd); - } else if (clazz == CheckSshCommand.class) { - return virtualroutingsupport.execute((CheckSshCommand)cmd); - } else if (clazz == NetworkUsageCommand.class) { - return virtualroutingsupport.execute((NetworkUsageCommand)cmd); - /* double check order! */ - } else if (clazz == CopyCommand.class) { - return storageprocessor.execute((CopyCommand)cmd); - } else if (cmd instanceof StorageSubSystemCommand) { - return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd); - } else if (clazz == CreateCommand.class) { - return storageprocessor.execute((CreateCommand)cmd); - } else if (clazz == CreateObjectCommand.class) { - return storageprocessor.execute((CreateObjectCommand)cmd); - } else if (clazz == AttachIsoCommand.class) { - return storageprocessor.attachIso((AttachCommand)cmd); - } else if (clazz == CreatePrivateTemplateFromVolumeCommand.class) { - return storageprocessor.execute((CreatePrivateTemplateFromVolumeCommand)cmd); - } else if (clazz == DestroyCommand.class) { - return storageprocessor.execute((DestroyCommand)cmd); - } else if (clazz == CopyVolumeCommand.class) { - return storageprocessor.execute((CopyVolumeCommand)cmd); - } else if (clazz == CreateStoragePoolCommand.class) { - return storagepool.execute((CreateStoragePoolCommand)cmd); - } else if (clazz == ModifyStoragePoolCommand.class) { - return storagepool.execute((ModifyStoragePoolCommand)cmd); - } else if (clazz == PrimaryStorageDownloadCommand.class) { - return storagepool.execute((PrimaryStorageDownloadCommand)cmd); - } else if (clazz == DeleteStoragePoolCommand.class) { - return storagepool.execute((DeleteStoragePoolCommand)cmd); - } else if (clazz == GetStorageStatsCommand.class) { - return storagepool.execute((GetStorageStatsCommand)cmd); - } else if (clazz == GetHostStatsCommand.class) { - return hypervisorsupport.execute((GetHostStatsCommand)cmd); - } else if (clazz == CheckVirtualMachineCommand.class) { - return hypervisorsupport.execute((CheckVirtualMachineCommand)cmd); - } else if (clazz == MaintainCommand.class) { - return hypervisorsupport.execute((MaintainCommand)cmd); - } else if (clazz == CheckHealthCommand.class) { - return hypervisorsupport.execute((CheckHealthCommand)cmd); - } else if (clazz == ReadyCommand.class) { - return hypervisorsupport.execute((ReadyCommand)cmd); - } else if (clazz == FenceCommand.class) { - return hypervisorsupport.execute((FenceCommand)cmd); - } else if (clazz == CheckOnHostCommand.class) { - return hypervisorsupport.execute((CheckOnHostCommand)cmd); - } else if (clazz == PingTestCommand.class) { - return hypervisornetwork.execute((PingTestCommand)cmd); - } else if (clazz == CheckNetworkCommand.class) { - return hypervisornetwork.execute((CheckNetworkCommand)cmd); - } else if (clazz == GetVmStatsCommand.class) { - return vmsupport.execute((GetVmStatsCommand)cmd); - } else if (clazz == PrepareForMigrationCommand.class) { - return vmsupport.execute((PrepareForMigrationCommand)cmd); - } else if (clazz == MigrateCommand.class) { - return vmsupport.execute((MigrateCommand)cmd); - } else if (clazz == GetVncPortCommand.class) { - return vmsupport.execute((GetVncPortCommand)cmd); - } else if (clazz == PlugNicCommand.class) { - return vmsupport.execute((PlugNicCommand)cmd); - } else if (clazz == UnPlugNicCommand.class) { - return vmsupport.execute((UnPlugNicCommand)cmd); - } else if (clazz == StartCommand.class) { - return execute((StartCommand)cmd); - } else if (clazz == StopCommand.class) { - return execute((StopCommand)cmd); - } else if (clazz == RebootCommand.class) { - return execute((RebootCommand)cmd); - } - logger.debug("Can't find class for executeRequest " + cmd.getClass() + ", is your direct call missing?"); - return Answer.createUnsupportedCommandAnswer(cmd); - } - - @Override - public void disconnected() { - logger.debug("disconnected seems unused everywhere else"); - } - - @Override - public IAgentControl getAgentControl() { - logger.debug("we don't use IAgentControl"); - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - logger.debug("No use in setting IAgentControl"); - } - - @Override - public String getName() { - return configuration.getAgentName(); - } - - @Override - public void setName(String name) { - configuration.setAgentName(name); - } - - @Override - public void setConfigParams(Map params) { - configuration.setRawParams(params); - } - - @Override - public Map getConfigParams() { - return configuration.getRawParams(); - } - - @Override - public int getRunLevel() { - return 0; - } - - @Override - public void setRunLevel(int level) { - logger.debug("runlevel seems unused in other hypervisors"); - } - - /** - * Base configuration of the plugins components. - */ - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - logger.debug("configure " + name + " with params: " + params); - /* check if we're primary or not and if we can connect */ - try { - configuration = new Ovm3Configuration(params); - if (!configuration.getIsTest()) { - c = new Connection(configuration.getAgentIp(), configuration.getAgentOvsAgentPort(), configuration.getAgentOvsAgentUser(), - configuration.getAgentOvsAgentPassword()); - c.setHostName(configuration.getAgentHostname()); - } - hypervisorsupport = new Ovm3HypervisorSupport(c, configuration); - if (!configuration.getIsTest()) { - hypervisorsupport.setupServer(configuration.getAgentSshKeyFileName()); - } - hypervisorsupport.primaryCheck(); - } catch (Exception e) { - throw new CloudRuntimeException("Base checks failed for " + configuration.getAgentHostname(), e); - } - hypervisornetwork = new Ovm3HypervisorNetwork(c, configuration); - hypervisornetwork.configureNetworking(); - virtualroutingresource = new Ovm3VirtualRoutingResource(c); - storagepool = new Ovm3StoragePool(c, configuration); - storagepool.prepareForPool(); - storageprocessor = new Ovm3StorageProcessor(c, configuration, storagepool); - vmsupport = new Ovm3VmSupport(c, configuration, hypervisorsupport, storageprocessor, storagepool, hypervisornetwork); - vrResource = new VirtualRoutingResource(virtualroutingresource); - if (!vrResource.configure(name, params)) { - throw new ConfigurationException("Unable to configure VirtualRoutingResource"); - } - guesttypes = new Ovm3VmGuestTypes(); - storageHandler = new StorageSubsystemCommandHandlerBase(storageprocessor); - virtualroutingsupport = new Ovm3VirtualRoutingSupport(c, configuration, virtualroutingresource); - setConfigParams(params); - return true; - } - - public void setConnection(Connection con) { - logger.debug("override connection: " + con.getIp()); - c = con; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public synchronized StartAnswer execute(StartCommand cmd) { - VirtualMachineTO vmSpec = cmd.getVirtualMachine(); - String vmName = vmSpec.getName(); - State state = State.Stopped; - Xen xen = new Xen(c); - - try { - hypervisorsupport.setVmStateStarting(vmName); - Xen.Vm vm = xen.getVmConfig(); - /* max and min ? */ - vm.setVmCpus(vmSpec.getCpus()); - /* in mb not in bytes */ - vm.setVmMemory(vmSpec.getMinRam() / 1024 / 1024); - vm.setVmUuid(UuidUtils.nameUUIDFromBytes(vmSpec.getName().getBytes(Charset.defaultCharset())).toString()); - vm.setVmName(vmName); - - String domType = guesttypes.getOvm3GuestType(vmSpec.getOs()); - if (domType == null || domType.isEmpty()) { - domType = "default"; - logger.debug("VM Virt type missing setting to: " + domType); - } else { - logger.debug("VM Virt type set to " + domType + " for " + vmSpec.getOs()); - } - vm.setVmDomainType(domType); - - if (vmSpec.getBootloader() == BootloaderType.CD) { - logger.warn("CD booting is not supported"); - } - /* - * officially CD boot is only supported on HVM, although there is a - * simple way around it.. - */ - vmsupport.createVbds(vm, vmSpec); - - if (vmSpec.getType() != VirtualMachine.Type.User) { - // double check control network if we run a non user VM - hypervisornetwork.configureNetworking(); - vm.setVmExtra(vmSpec.getBootArgs().replace(" ", "%")); - String svmPath = configuration.getAgentOvmRepoPath() + "/" + ovmObject.deDash(vm.getPrimaryPoolUuid()) + "/ISOs"; - String svmIso = svmPath + "/" + storagepool.getSystemVMPatchIsoFile().getName(); - vm.addIso(svmIso); - } - /* OVS/Network stuff should go here! */ - vmsupport.createVifs(vm, vmSpec); - vm.setupVifs(); - - vm.setVnc("0.0.0.0", vmSpec.getVncPassword()); - xen.createVm(ovmObject.deDash(vm.getPrimaryPoolUuid()), vm.getVmUuid()); - xen.startVm(ovmObject.deDash(vm.getPrimaryPoolUuid()), vm.getVmUuid()); - state = State.Running; - - if (vmSpec.getType() != VirtualMachine.Type.User) { - String controlIp = null; - for (NicTO nic : vmSpec.getNics()) { - if (nic.getType() == TrafficType.Control) { - controlIp = nic.getIp(); - } - } - /* fix is in cloudstack.py for xend restart timer */ - for (int count = 0; count < 60; count++) { - CloudstackPlugin cSp = new CloudstackPlugin(c); - /* skip a beat to make sure we didn't miss start */ - if (hypervisorsupport.getVmState(vmName) == null && count > 1) { - String msg = "VM " + vmName + " went missing on " + configuration.getAgentHostname() + ", returning stopped"; - logger.debug(msg); - state = State.Stopped; - return new StartAnswer(cmd, msg); - } - /* creative fix? */ - try { - Boolean res = cSp.domrCheckSsh(controlIp); - logger.debug("connected to " + controlIp + " on attempt " + count + " result: " + res); - if (res) { - break; - } - } catch (Exception x) { - logger.trace("unable to connect to " + controlIp + " on attempt " + count + " " + x.getMessage(), x); - } - Thread.sleep(5000); - } - } - /* - * Can't remember if HA worked if we were only a pool ? - */ - if (configuration.getAgentInOvm3Pool() && configuration.getAgentInOvm3Cluster()) { - xen.configureVmHa(ovmObject.deDash(vm.getPrimaryPoolUuid()), vm.getVmUuid(), true); - } - /* should be starting no ? */ - state = State.Running; - return new StartAnswer(cmd); - } catch (Exception e) { - logger.debug("Start vm " + vmName + " failed", e); - state = State.Stopped; - return new StartAnswer(cmd, e.getMessage()); - } finally { - hypervisorsupport.setVmState(vmName, state); - } - } - - /** - * Removes the vm and its configuration from the hypervisor. - */ - @Override - public StopAnswer execute(StopCommand cmd) { - String vmName = cmd.getVmName(); - State state = State.Error; - hypervisorsupport.setVmState(vmName, State.Stopping); - - try { - Xen vms = new Xen(c); - Xen.Vm vm = null; - vm = vms.getRunningVmConfig(vmName); - - if (vm == null) { - state = State.Stopping; - logger.debug("Unable to get details of vm: " + vmName + ", treating it as Stopping"); - return new StopAnswer(cmd, "success", true); - } - String repoId = ovmObject.deDash(vm.getVmRootDiskPoolId()); - String vmId = vm.getVmUuid(); - /* can we do without the poolId ? */ - vms.stopVm(repoId, vmId); - int tries = 30; - while (vms.getRunningVmConfig(vmName) != null && tries > 0) { - String msg = "Waiting for " + vmName + " to stop"; - logger.debug(msg); - tries--; - Thread.sleep(10 * 1000); - } - vms.deleteVm(repoId, vmId); - vmsupport.cleanup(vm); - - if (vms.getRunningVmConfig(vmName) != null) { - String msg = "Stop " + vmName + " failed "; - logger.debug(msg); - return new StopAnswer(cmd, msg, false); - } - state = State.Stopped; - return new StopAnswer(cmd, "success", true); - } catch (Exception e) { - logger.debug("Stop " + vmName + " failed ", e); - return new StopAnswer(cmd, e.getMessage(), false); - } finally { - if (state != null) { - hypervisorsupport.setVmState(vmName, state); - } else { - hypervisorsupport.revmoveVmState(vmName); - } - } - } - - @Override - public RebootAnswer execute(RebootCommand cmd) { - String vmName = cmd.getVmName(); - hypervisorsupport.setVmStateStarting(vmName); - try { - Xen xen = new Xen(c); - Xen.Vm vm = xen.getRunningVmConfig(vmName); - if (vm == null) { - return new RebootAnswer(cmd, vmName + " not present", false); - } - xen.rebootVm(ovmObject.deDash(vm.getVmRootDiskPoolId()), vm.getVmUuid()); - vm = xen.getRunningVmConfig(vmName); - Integer vncPort = vm.getVncPort(); - return new RebootAnswer(cmd, null, vncPort); - } catch (Exception e) { - logger.debug("Reboot " + vmName + " failed", e); - return new RebootAnswer(cmd, e.getMessage(), false); - } finally { - hypervisorsupport.setVmState(vmName, State.Running); - } - } - - @Override - protected String getDefaultScriptsDir() { - return null; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessor.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessor.java deleted file mode 100644 index 800df1db91fe..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessor.java +++ /dev/null @@ -1,872 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.UUID; - -import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand; -import org.apache.cloudstack.storage.command.AttachAnswer; -import org.apache.cloudstack.storage.command.AttachCommand; -import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplianceCommand; -import org.apache.cloudstack.storage.command.CopyCmdAnswer; -import org.apache.cloudstack.storage.command.CopyCommand; -import org.apache.cloudstack.storage.command.CreateObjectAnswer; -import org.apache.cloudstack.storage.command.CreateObjectCommand; -import org.apache.cloudstack.storage.command.DeleteCommand; -import org.apache.cloudstack.storage.command.DettachCommand; -import org.apache.cloudstack.storage.command.ForgetObjectCmd; -import org.apache.cloudstack.storage.command.IntroduceObjectCmd; -import org.apache.cloudstack.storage.command.ResignatureAnswer; -import org.apache.cloudstack.storage.command.ResignatureCommand; -import org.apache.cloudstack.storage.command.SnapshotAndCopyCommand; -import org.apache.cloudstack.storage.command.SnapshotAndCopyAnswer; -import org.apache.cloudstack.storage.command.SyncVolumePathCommand; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.cloudstack.storage.to.TemplateObjectTO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; -import com.cloud.agent.api.storage.CopyVolumeAnswer; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.storage.CreateAnswer; -import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; -import com.cloud.agent.api.storage.DestroyCommand; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.NfsTO; -import com.cloud.agent.api.to.StorageFilerTO; -import com.cloud.agent.api.to.VolumeTO; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Linux; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.StoragePlugin; -import com.cloud.hypervisor.ovm3.objects.StoragePlugin.FileProperties; -import com.cloud.hypervisor.ovm3.objects.Xen; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3Configuration; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3StoragePool; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.Volume; -import com.cloud.storage.resource.StorageProcessor; -import com.cloud.vm.DiskProfile; - -/** - * Storage related bits - */ -public class Ovm3StorageProcessor implements StorageProcessor { - protected Logger logger = LogManager.getLogger(getClass()); - private Connection c; - private OvmObject ovmObject = new OvmObject(); - private Ovm3StoragePool pool; - private Ovm3Configuration config; - - public Ovm3StorageProcessor(Connection conn, Ovm3Configuration ovm3config, - Ovm3StoragePool ovm3pool) { - c = conn; - config = ovm3config; - pool = ovm3pool; - } - - public final Answer execute(final CopyCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - DataTO srcData = cmd.getSrcTO(); - DataStoreTO srcStore = srcData.getDataStore(); - DataTO destData = cmd.getDestTO(); - DataStoreTO destStore = destData.getDataStore(); - String msg = "Not implemented yet"; - try { - /* target and source are NFS and TEMPLATE */ - if ((srcStore instanceof NfsTO) - && (srcData.getObjectType() == DataObjectType.TEMPLATE) - && (destData.getObjectType() == DataObjectType.TEMPLATE)) { - return copyTemplateToPrimaryStorage(cmd); - /* we assume the cache for templates is local */ - } else if ((srcData.getObjectType() == DataObjectType.TEMPLATE) - && (destData.getObjectType() == DataObjectType.VOLUME)) { - if (srcStore.getUrl().equals(destStore.getUrl())) { - return cloneVolumeFromBaseTemplate(cmd); - } else { - msg = "Primary to Primary doesn't match"; - logger.debug(msg); - } - } else if ((srcData.getObjectType() == DataObjectType.SNAPSHOT) - && (destData.getObjectType() == DataObjectType.SNAPSHOT)) { - return backupSnapshot(cmd); - } else if ((srcData.getObjectType() == DataObjectType.SNAPSHOT) - && (destData.getObjectType() == DataObjectType.TEMPLATE)) { - return createTemplateFromSnapshot(cmd); - } else if ((srcData.getObjectType() == DataObjectType.SNAPSHOT) - && (destData.getObjectType() == DataObjectType.VOLUME)) { - return createVolumeFromSnapshot(cmd); - } else { - msg = "Unable to do stuff for " + srcStore.getClass() + ":" - + srcData.getObjectType() + " to " - + destStore.getClass() + ":" + destData.getObjectType(); - logger.debug(msg); - } - } catch (Exception e) { - msg = "Catch Exception " + e.getClass().getName() - + " for template due to " + e.toString(); - logger.warn(msg, e); - return new CopyCmdAnswer(msg); - } - logger.warn(msg + " " + cmd.getClass()); - return new CopyCmdAnswer(msg); - } - - public Answer execute(DeleteCommand cmd) { - DataTO data = cmd.getData(); - String msg; - logger.debug("Deleting object: " + data.getObjectType()); - if (data.getObjectType() == DataObjectType.VOLUME) { - return deleteVolume(cmd); - } else if (data.getObjectType() == DataObjectType.SNAPSHOT) { - return deleteSnapshot(cmd); - } else if (data.getObjectType() == DataObjectType.TEMPLATE) { - msg = "Template deletion is not implemented yet."; - logger.info(msg); - } else { - msg = data.getObjectType() + " deletion is not implemented yet."; - logger.info(msg); - } - return new Answer(cmd, false, msg); - } - - public CreateAnswer execute(CreateCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - StorageFilerTO primaryStorage = cmd.getPool(); - DiskProfile disk = cmd.getDiskCharacteristics(); - /* disk should have a uuid */ - // should also be replaced with getVirtualDiskPath ? - String fileName = UUID.randomUUID().toString() + ".raw"; - String dst = primaryStorage.getPath() + "/" - + primaryStorage.getUuid() + "/" + fileName; - try { - StoragePlugin store = new StoragePlugin(c); - if (cmd.getTemplateUrl() != null) { - logger.debug("CreateCommand " + cmd.getTemplateUrl() + " " - + dst); - Linux host = new Linux(c); - host.copyFile(cmd.getTemplateUrl(), dst); - } else { - /* this is a dup with the createVolume ? */ - logger.debug("CreateCommand " + dst); - store.storagePluginCreate(primaryStorage.getUuid(), - primaryStorage.getHost(), dst, disk.getSize(), false); - } - FileProperties fp = store.storagePluginGetFileInfo( - primaryStorage.getUuid(), primaryStorage.getHost(), dst); - VolumeTO volume = new VolumeTO(cmd.getVolumeId(), disk.getType(), - primaryStorage.getType(), primaryStorage.getUuid(), - primaryStorage.getPath(), fileName, fp.getName(), - fp.getSize(), null); - return new CreateAnswer(cmd, volume); - } catch (Exception e) { - logger.debug("CreateCommand failed", e); - return new CreateAnswer(cmd, e.getMessage()); - } - } - - /** - * src is Nfs and Template from secondary storage to primary - */ - @Override - public CopyCmdAnswer copyTemplateToPrimaryStorage(CopyCommand cmd) { - logger.debug("execute copyTemplateToPrimaryStorage: "+ cmd.getClass()); - DataTO srcData = cmd.getSrcTO(); - DataStoreTO srcStore = srcData.getDataStore(); - DataTO destData = cmd.getDestTO(); - NfsTO srcImageStore = (NfsTO) srcStore; - TemplateObjectTO destTemplate = (TemplateObjectTO) destData; - try { - String secPoolUuid = pool.setupSecondaryStorage(srcImageStore.getUrl()); - String primaryPoolUuid = destData.getDataStore().getUuid(); - String destPath = config.getAgentOvmRepoPath() + "/" - + ovmObject.deDash(primaryPoolUuid) + "/" - + config.getTemplateDir(); - String sourcePath = config.getAgentSecStoragePath() - + "/" + secPoolUuid; - Linux host = new Linux(c); - String destUuid = destTemplate.getUuid(); - /* - * Would love to add dynamic formats (tolower), to also support - * VHD and QCOW2, although Ovm3.2 does not have tapdisk2 anymore - * so we can forget about that. - */ - /* TODO: add checksumming */ - String srcFile = sourcePath + "/" - + srcData.getPath(); - if (srcData.getPath().endsWith("/")) { - srcFile = sourcePath + "/" + srcData.getPath() - + "/" + destUuid + ".raw"; - } - String destFile = destPath + "/" + destUuid + ".raw"; - logger.debug("CopyFrom: " + srcData.getObjectType() + "," - + srcFile + " to " + destData.getObjectType() + "," - + destFile); - host.copyFile(srcFile, destFile); - TemplateObjectTO newVol = new TemplateObjectTO(); - newVol.setUuid(destUuid); - // was destfile - newVol.setPath(destUuid); - newVol.setFormat(ImageFormat.RAW); - return new CopyCmdAnswer(newVol); - } catch (Ovm3ResourceException e) { - String msg = "Error while copying template to primary storage: " + e.getMessage(); - logger.info(msg); - return new CopyCmdAnswer(msg); - } - } - /** - * Only copies in case of dest is NfsTO, xenserver also unmounts secstorage - */ - @Override - public Answer copyVolumeFromPrimaryToSecondary(CopyCommand cmd) { - logger.debug("execute copyVolumeFromPrimaryToSecondary: "+ cmd.getClass()); - return new Answer(cmd); - } - /** - * dest is VolumeObject, src is a template - */ - @Override - public CopyCmdAnswer cloneVolumeFromBaseTemplate(CopyCommand cmd) { - logger.debug("execute cloneVolumeFromBaseTemplate: "+ cmd.getClass()); - try { - // src - DataTO srcData = cmd.getSrcTO(); - TemplateObjectTO src = (TemplateObjectTO) srcData; - String srcFile = getVirtualDiskPath(src.getUuid(), src.getDataStore().getUuid()); - srcFile = srcFile.replace(config.getVirtualDiskDir(), config.getTemplateDir()); - - DataTO destData = cmd.getDestTO(); - VolumeObjectTO dest = (VolumeObjectTO) destData; - String destFile = getVirtualDiskPath(dest.getUuid(), dest.getDataStore().getUuid()); - Linux host = new Linux(c); - logger.debug("CopyFrom: " + srcData.getObjectType() + "," - + srcFile + " to " + destData.getObjectType() + "," - + destFile); - host.copyFile(srcFile, destFile); - VolumeObjectTO newVol = new VolumeObjectTO(); - newVol.setUuid(dest.getUuid()); - // was destfile - newVol.setPath(dest.getUuid()); - newVol.setFormat(ImageFormat.RAW); - return new CopyCmdAnswer(newVol); - } catch (Ovm3ResourceException e) { - String msg = "Error cloneVolumeFromBaseTemplate: " + e.getMessage(); - logger.info(msg); - return new CopyCmdAnswer(msg); - } - } - /** - * createprivatetemplate, also needs template.properties - */ - @Override - public Answer createTemplateFromVolume(CopyCommand cmd) { - logger.debug("execute createTemplateFromVolume: "+ cmd.getClass()); - return new Answer(cmd); - } - /** - * Volume to Volume from NfsTO - */ - @Override - public Answer copyVolumeFromImageCacheToPrimary(CopyCommand cmd) { - logger.debug("execute copyVolumeFromImageCacheToPrimary: "+ cmd.getClass()); - return new Answer(cmd); - } - /** - * Copies from secondary to secondary - */ - @Override - public Answer createTemplateFromSnapshot(CopyCommand cmd) { - logger.debug("execute createTemplateFromSnapshot: "+ cmd.getClass()); - try { - // src.getPath contains the uuid of the snapshot. - DataTO srcData = cmd.getSrcTO(); - SnapshotObjectTO srcSnap = (SnapshotObjectTO) srcData; - String secPoolUuid = pool.setupSecondaryStorage(srcData.getDataStore().getUrl()); - String srcFile = config.getAgentSecStoragePath() - + "/" + secPoolUuid + "/" - + srcSnap.getPath(); - // dest - DataTO destData = cmd.getDestTO(); - TemplateObjectTO destTemplate = (TemplateObjectTO) destData; - String secPoolUuidTemplate = pool.setupSecondaryStorage(destData.getDataStore().getUrl()); - String destDir = config.getAgentSecStoragePath() - + "/" + secPoolUuidTemplate + "/" - + destTemplate.getPath(); - String destFile = destDir + "/" - + destTemplate.getUuid() + ".raw"; - CloudstackPlugin csp = new CloudstackPlugin(c); - csp.ovsMkdirs(destDir); - - Linux host = new Linux(c); - host.copyFile(srcFile, destFile); - TemplateObjectTO newVol = new TemplateObjectTO(); - newVol.setUuid(destTemplate.getUuid()); - newVol.setPath(destTemplate.getUuid()); - newVol.setFormat(ImageFormat.RAW); - return new CopyCmdAnswer(newVol); - } catch (Ovm3ResourceException e) { - String msg = "Error backupSnapshot: " + e.getMessage(); - logger.info(msg); - return new CopyCmdAnswer(msg); - } - } - - /** - * use the cache, or the normal nfs, also delete the leftovers for us - * also contains object store storage in xenserver. - */ - @Override - public CopyCmdAnswer backupSnapshot(CopyCommand cmd) { - logger.debug("execute backupSnapshot: "+ cmd.getClass()); - try { - DataTO srcData = cmd.getSrcTO(); - DataTO destData = cmd.getDestTO(); - SnapshotObjectTO src = (SnapshotObjectTO) srcData; - SnapshotObjectTO dest = (SnapshotObjectTO) destData; - - // src.getPath contains the uuid of the snapshot. - String srcFile = getVirtualDiskPath(src.getPath(), src.getDataStore().getUuid()); - - // destination - String storeUrl = dest.getDataStore().getUrl(); - String secPoolUuid = pool.setupSecondaryStorage(storeUrl); - String destDir = config.getAgentSecStoragePath() - + "/" + secPoolUuid + "/" - + dest.getPath(); - String destFile = destDir + "/" + src.getPath(); - destFile = destFile.concat(".raw"); - // copy - Linux host = new Linux(c); - CloudstackPlugin csp = new CloudstackPlugin(c); - csp.ovsMkdirs(destDir); - logger.debug("CopyFrom: " + srcData.getObjectType() + "," - + srcFile + " to " + destData.getObjectType() + "," - + destFile); - host.copyFile(srcFile, destFile); - StoragePlugin sp = new StoragePlugin(c); - sp.storagePluginDestroy(secPoolUuid, srcFile); - - SnapshotObjectTO newSnap = new SnapshotObjectTO(); - // newSnap.setPath(destFile); - // damnit frickin crap, no reference whatsoever... could use parent ? - newSnap.setPath(dest.getPath() + "/" + src.getPath() + ".raw"); - newSnap.setParentSnapshotPath(null); - return new CopyCmdAnswer(newSnap); - } catch (Ovm3ResourceException e) { - String msg = "Error backupSnapshot: " + e.getMessage(); - logger.info(msg); - return new CopyCmdAnswer(msg); - } - } - - public Answer execute(CreateObjectCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - DataTO data = cmd.getData(); - if (data.getObjectType() == DataObjectType.VOLUME) { - return createVolume(cmd); - } else if (data.getObjectType() == DataObjectType.SNAPSHOT) { - return createSnapshot(cmd); - } else if (data.getObjectType() == DataObjectType.TEMPLATE) { - logger.debug("Template object creation not supported."); - } - return new CreateObjectAnswer(data.getObjectType() - + " object creation not supported"); - } - /** - * Attach an iso - */ - @Override - public AttachAnswer attachIso(AttachCommand cmd) { - logger.debug("execute attachIso: "+ cmd.getClass()); - String vmName = cmd.getVmName(); - DiskTO disk = cmd.getDisk(); - return attachDetach(cmd, vmName, disk, true); - } - /** - * Detach an iso - */ - @Override - public AttachAnswer dettachIso(DettachCommand cmd) { - logger.debug("execute dettachIso: "+ cmd.getClass()); - String vmName = cmd.getVmName(); - DiskTO disk = cmd.getDisk(); - return attachDetach(cmd, vmName, disk, false); - } - - /** - * Iso specific path return. - * @param disk - * @return - * @throws Ovm3ResourceException - */ - private String getIsoPath(DiskTO disk) throws Ovm3ResourceException { - TemplateObjectTO isoTO = (TemplateObjectTO) disk.getData(); - DataStoreTO store = isoTO.getDataStore(); - NfsTO nfsStore = (NfsTO) store; - String secPoolUuid = pool.setupSecondaryStorage(nfsStore.getUrl()); - return config.getAgentSecStoragePath() + "/" - + secPoolUuid + "/" + isoTO.getPath(); - } - - /** - * Returns the disk path - * @param diskUuid - * @return - * @throws Ovm3ResourceException - */ - public String getVirtualDiskPath(String diskUuid, String storeUuid) throws Ovm3ResourceException { - String d = config.getAgentOvmRepoPath() + - "/" + - ovmObject.deDash(storeUuid) + - "/" + - config.getVirtualDiskDir() + - "/" + - diskUuid; - if (!d.endsWith(".raw")) { - d = d.concat(".raw"); - } - return d; - } - public String getVirtualDiskPath(DiskTO disk, String storeUuid) throws Ovm3ResourceException { - return getVirtualDiskPath(disk.getPath(), storeUuid); - } - - /** - * Generic disk attach/detach. - * @param cmd - * @param vmName - * @param disk - * @param isAttach - * @return - */ - private AttachAnswer attachDetach(Command cmd, String vmName, DiskTO disk, - boolean isAttach) { - Xen xen = new Xen(c); - String doThis = (isAttach) ? "Attach" : "Dettach"; - logger.debug(doThis + " volume type " + disk.getType() + " " + vmName); - String msg = ""; - String path = ""; - try { - Xen.Vm vm = xen.getVmConfig(vmName); - /* check running */ - if (vm == null) { - msg = doThis + " can't find VM " + vmName; - logger.debug(msg); - return new AttachAnswer(msg); - } - if (disk.getType() == Volume.Type.ISO) { - path = getIsoPath(disk); - } else if (disk.getType() == Volume.Type.DATADISK) { - path = getVirtualDiskPath(disk, vm.getPrimaryPoolUuid()); - } - if ("".equals(path)) { - msg = doThis + " can't do anything with an empty path."; - logger.debug(msg); - return new AttachAnswer(msg); - } - if (isAttach) { - if (disk.getType() == Volume.Type.ISO) { - vm.addIso(path); - } else { - vm.addDataDisk(path); - } - } else { - if (!vm.removeDisk(path)) { - msg = doThis + " failed for " + vmName + disk.getType() - + " was not attached " + path; - logger.debug(msg); - return new AttachAnswer(msg); - } - } - xen.configureVm(ovmObject.deDash(vm.getPrimaryPoolUuid()), - vm.getVmUuid()); - return new AttachAnswer(disk); - } catch (Ovm3ResourceException e) { - msg = doThis + " failed for " + vmName + " " + e.getMessage(); - logger.warn(msg, e); - return new AttachAnswer(msg); - } - } - /** - * Attach a volume - */ - @Override - public AttachAnswer attachVolume(AttachCommand cmd) { - logger.debug("execute attachVolume: "+ cmd.getClass()); - String vmName = cmd.getVmName(); - DiskTO disk = cmd.getDisk(); - return attachDetach(cmd, vmName, disk, true); - } - /** - * Detach a volume - */ - @Override - public AttachAnswer dettachVolume(DettachCommand cmd) { - logger.debug("execute dettachVolume: "+ cmd.getClass()); - String vmName = cmd.getVmName(); - DiskTO disk = cmd.getDisk(); - return attachDetach(cmd, vmName, disk, false); - } - - /** - * Creates a volume, just a normal empty volume. - */ - @Override - public Answer createVolume(CreateObjectCommand cmd) { - logger.debug("execute createVolume: "+ cmd.getClass()); - DataTO data = cmd.getData(); - VolumeObjectTO volume = (VolumeObjectTO) data; - try { - /* - * public Boolean storagePluginCreate(String uuid, String ssuuid, - * String host, String file, Integer size) - */ - String poolUuid = data.getDataStore().getUuid(); - String storeUrl = data.getDataStore().getUrl(); - URI uri = new URI(storeUrl); - String host = uri.getHost(); - String file = getVirtualDiskPath(volume.getUuid(), poolUuid); - Long size = volume.getSize(); - StoragePlugin sp = new StoragePlugin(c); - FileProperties fp = sp.storagePluginCreate(poolUuid, host, file, - size, false); - if (!fp.getName().equals(file)) { - return new CreateObjectAnswer("Filename mismatch: " - + fp.getName() + " != " + file); - } - VolumeObjectTO newVol = new VolumeObjectTO(); - newVol.setName(volume.getName()); - newVol.setSize(fp.getSize()); - newVol.setPath(volume.getUuid()); - return new CreateObjectAnswer(newVol); - } catch (Ovm3ResourceException | URISyntaxException e) { - logger.info("Volume creation failed: " + e.toString(), e); - return new CreateObjectAnswer(e.toString()); - } - } - - /** - * Creates a snapshot from a volume, but only if the VM is stopped. - * This due qemu not being able to snap raw volumes. - * - * if stopped yes, if running ... no, unless we have ocfs2 when - * using raw partitions (file:) if using tap:aio we cloud... - * The "ancient" way: - * We do however follow the "two stage" approach, of "snap" - * on primary first, with the create object... and then - * backup the snapshot with the copycmd.... - * (should transfer to createSnapshot, backupSnapshot) - */ - @Override - public Answer createSnapshot(CreateObjectCommand cmd) { - logger.debug("execute createSnapshot: "+ cmd.getClass()); - DataTO data = cmd.getData(); - Xen xen = new Xen(c); - SnapshotObjectTO snap = (SnapshotObjectTO) data; - VolumeObjectTO vol = snap.getVolume(); - try { - Xen.Vm vm = xen.getVmConfig(snap.getVmName()); - if (vm != null) { - return new CreateObjectAnswer( - "Snapshot object creation not supported for running VMs." - + snap.getVmName()); - } - Linux host = new Linux(c); - String uuid = host.newUuid(); - /* for root volumes this works... */ - String src = vol.getPath() + "/" + vol.getUuid() - + ".raw"; - String dest = vol.getPath() + "/" + uuid + ".raw"; - /* seems that sometimes the path is already contains a file - * in case, we just replace it.... (Seems to happen if not ROOT) - */ - if (vol.getPath().contains(vol.getUuid())) { - src = getVirtualDiskPath(vol.getUuid(),data.getDataStore().getUuid()); - dest = src.replace(vol.getUuid(), uuid); - } - logger.debug("Snapshot " + src + " to " + dest); - host.copyFile(src, dest); - SnapshotObjectTO nsnap = new SnapshotObjectTO(); - // nsnap.setPath(dest); - // move to something that looks the same as xenserver. - nsnap.setPath(uuid); - return new CreateObjectAnswer(nsnap); - } catch (Ovm3ResourceException e) { - return new CreateObjectAnswer( - "Snapshot object creation failed. " + e.getMessage()); - } - } - - @Override - public Answer deleteVolume(DeleteCommand cmd) { - logger.debug("execute deleteVolume: "+ cmd.getClass()); - DataTO data = cmd.getData(); - VolumeObjectTO volume = (VolumeObjectTO) data; - try { - String poolUuid = data.getDataStore().getUuid(); - String uuid = volume.getUuid(); - String path = getVirtualDiskPath(uuid, poolUuid); - StoragePlugin sp = new StoragePlugin(c); - sp.storagePluginDestroy(poolUuid, path); - logger.debug("Volume deletion success: " + path); - } catch (Ovm3ResourceException e) { - logger.info("Volume deletion failed: " + e.toString(), e); - return new CreateObjectAnswer(e.toString()); - } - return new Answer(cmd); - } - - /* - * CopyVolumeCommand gets the storage_pool should use that for - * bumper bowling. - */ - public CopyVolumeAnswer execute(CopyVolumeCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - String volumePath = cmd.getVolumePath(); - /* is a repository */ - String secondaryStorageURL = cmd.getSecondaryStorageURL(); - int wait = cmd.getWait(); - if (wait == 0) { - wait = 7200; - } - - try { - Linux host = new Linux(c); - - /* to secondary storage */ - if (cmd.toSecondaryStorage()) { - logger.debug("Copy to secondary storage " + volumePath - + " to " + secondaryStorageURL); - host.copyFile(volumePath, secondaryStorageURL); - /* from secondary storage */ - } else { - logger.debug("Copy from secondary storage " - + secondaryStorageURL + " to " + volumePath); - host.copyFile(secondaryStorageURL, volumePath); - } - /* check the truth of this */ - return new CopyVolumeAnswer(cmd, true, null, null, null); - } catch (Ovm3ResourceException e) { - logger.debug("Copy volume failed", e); - return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null); - } - } - - /* Destroy a volume (image) */ - public Answer execute(DestroyCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - VolumeTO vol = cmd.getVolume(); - String vmName = cmd.getVmName(); - try { - StoragePlugin store = new StoragePlugin(c); - store.storagePluginDestroy(vol.getPoolUuid(), vol.getPath()); - return new Answer(cmd, true, "Success"); - } catch (Ovm3ResourceException e) { - logger.debug("Destroy volume " + vol.getName() + " failed for " - + vmName + " ", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - /* check if a VM is running should be added */ - public CreatePrivateTemplateAnswer execute( - final CreatePrivateTemplateFromVolumeCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - String volumePath = cmd.getVolumePath(); - Long accountId = cmd.getAccountId(); - Long templateId = cmd.getTemplateId(); - int wait = cmd.getWait(); - if (wait == 0) { - /* Defaut timeout 2 hours */ - wait = 7200; - } - - try { - /* missing uuid */ - String installPath = config.getAgentOvmRepoPath() + "/" - + config.getTemplateDir() + "/" - + accountId + "/" + templateId; - Linux host = new Linux(c); - host.copyFile(volumePath, installPath); - return new CreatePrivateTemplateAnswer(cmd, true, installPath); - } catch (Exception e) { - logger.debug("Create template failed", e); - return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage()); - } - } - - /** - * SnapshotObjectTO secondary to VolumeObjectTO primary in xenserver, - */ - @Override - public Answer createVolumeFromSnapshot(CopyCommand cmd) { - logger.debug("execute createVolumeFromSnapshot: "+ cmd.getClass()); - try { - DataTO srcData = cmd.getSrcTO(); - DataStoreTO srcStore = srcData.getDataStore(); - NfsTO srcImageStore = (NfsTO) srcStore; - - // source, should contain snap dir/filename - SnapshotObjectTO srcSnap = (SnapshotObjectTO) srcData; - String secPoolUuid = pool.setupSecondaryStorage(srcImageStore.getUrl()); - String srcFile = config.getAgentSecStoragePath() - + "/" + secPoolUuid + "/" - + srcSnap.getPath(); - - // dest - DataTO destData = cmd.getDestTO(); - VolumeObjectTO destVol = (VolumeObjectTO) destData; - String primaryPoolUuid = destData.getDataStore().getUuid(); - String destFile = getVirtualDiskPath(destVol.getUuid(), ovmObject.deDash(primaryPoolUuid)); - - Linux host = new Linux(c); - host.copyFile(srcFile, destFile); - - VolumeObjectTO newVol = new VolumeObjectTO(); - newVol.setUuid(destVol.getUuid()); - // newVol.setPath(destFile); - newVol.setPath(destVol.getUuid()); - newVol.setFormat(ImageFormat.RAW); - return new CopyCmdAnswer(newVol); - /* we assume the cache for templates is local */ - } catch (Ovm3ResourceException e) { - logger.debug("Failed to createVolumeFromSnapshot: ", e); - return new CopyCmdAnswer(e.toString()); - } - } - - /** - * Is not used in normal operation, the SSVM takes care of this. - */ - @Override - public Answer deleteSnapshot(DeleteCommand cmd) { - logger.debug("execute deleteSnapshot: "+ cmd.getClass()); - DataTO data = cmd.getData(); - SnapshotObjectTO snap = (SnapshotObjectTO) data; - String storeUrl = data.getDataStore().getUrl(); - String snapUuid = snap.getPath(); - try { - // snapshots/accountid/volumeid - String secPoolUuid = pool.setupSecondaryStorage(storeUrl); - String filePath = config.getAgentSecStoragePath() - + "/" + secPoolUuid + "/" - + snapUuid + ".raw"; - StoragePlugin sp = new StoragePlugin(c); - sp.storagePluginDestroy(secPoolUuid, filePath); - logger.debug("Snapshot deletion success: " + filePath); - return new Answer(cmd, true, "Deleted Snapshot " + filePath); - } catch (Ovm3ResourceException e) { - logger.info("Snapshot deletion failed: " + e.toString(), e); - return new CreateObjectAnswer(e.toString()); - } - } - /** - * SR scan in xenserver - */ - @Override - public Answer introduceObject(IntroduceObjectCmd cmd) { - logger.debug("execute introduceObject: "+ cmd.getClass()); - return new Answer(cmd, false, "not implemented yet"); - } - /** - * used as unmount for VDIs in xenserver - */ - @Override - public Answer forgetObject(ForgetObjectCmd cmd) { - logger.debug("execute forgetObject: "+ cmd.getClass()); - return new Answer(cmd, false, "not implemented yet"); - } - - /** - * make sure both mounts are there, snapshot source image - * copy snap to dest image, remove source snap and unmount - * iSCSI? - */ - @Override - public SnapshotAndCopyAnswer snapshotAndCopy(SnapshotAndCopyCommand cmd) { - logger.info("'SnapshotAndCopyAnswer snapshotAndCopy(SnapshotAndCopyCommand)' not currently used for Ovm3StorageProcessor"); - - return new SnapshotAndCopyAnswer("Not implemented"); - } - - @Override - public ResignatureAnswer resignature(final ResignatureCommand cmd) { - logger.info("'ResignatureAnswer resignature(ResignatureCommand)' not currently used for Ovm3StorageProcessor"); - - return new ResignatureAnswer("Not implemented"); - } - - @Override - public Answer handleDownloadTemplateToPrimaryStorage(DirectDownloadCommand cmd) { - return null; - } - - @Override - public Answer checkDataStoreStoragePolicyCompliance(CheckDataStoreStoragePolicyComplianceCommand cmd) { - logger.info("'CheckDataStoreStoragePolicyComplianceCommand' not applicable used for Ovm3StorageProcessor"); - return new Answer(cmd,false,"Not applicable used for Ovm3StorageProcessor"); - } - - @Override - public Answer syncVolumePath(SyncVolumePathCommand cmd) { - logger.info("SyncVolumePathCommand not currently applicable for Ovm3StorageProcessor"); - return new Answer(cmd, false, "Not currently applicable for Ovm3StorageProcessor"); - } - - @Override - public Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd) { - return null; - } - - /** - * Attach disks - * @param cmd - * @return - */ - public Answer execute(AttachCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - String vmName = cmd.getVmName(); - DiskTO disk = cmd.getDisk(); - return attachDetach(cmd, vmName, disk, true); - } - - /** - * Detach disks, calls a middle man which calls attachDetach for volumes. - * @param cmd - * @return - */ - public Answer execute(DettachCommand cmd) { - logger.debug("execute: "+ cmd.getClass()); - String vmName = cmd.getVmName(); - DiskTO disk = cmd.getDisk(); - return attachDetach(cmd, vmName, disk, false); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResource.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResource.java deleted file mode 100644 index a3c4e926d085..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResource.java +++ /dev/null @@ -1,180 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.joda.time.Duration; - -import com.cloud.agent.api.SetupGuestNetworkCommand; -import com.cloud.agent.api.routing.IpAssocCommand; -import com.cloud.agent.api.routing.IpAssocVpcCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.to.IpAddressTO; -import com.cloud.agent.resource.virtualnetwork.VRScripts; -import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Xen; -import com.cloud.utils.ExecutionResult; - -public class Ovm3VirtualRoutingResource implements VirtualRouterDeployer { - protected Logger logger = LogManager.getLogger(getClass()); - private String domRCloudPath = "/opt/cloud/bin/"; - private Connection c; - private String agentName; - public Ovm3VirtualRoutingResource() { - } - public Ovm3VirtualRoutingResource(Connection conn) { - c = conn; - agentName=c.getIp(); - } - public void setConnection(Connection conn) { - c = conn; - } - @Override - public ExecutionResult executeInVR(String routerIp, String script, - String args) { - return executeInVR(routerIp, script, args, VRScripts.VR_SCRIPT_EXEC_TIMEOUT); - } - - @Override - public ExecutionResult executeInVR(String routerIp, String script, - String args, Duration timeout) { - if (!script.contains(domRCloudPath)) { - script = domRCloudPath + "/" + script; - } - String cmd = script + " " + args; - logger.debug("executeInVR via " + agentName + " on " + routerIp + ": " - + cmd); - try { - CloudstackPlugin cSp = new CloudstackPlugin(c); - CloudstackPlugin.ReturnCode result; - result = cSp.domrExec(routerIp, cmd); - return new ExecutionResult(result.getRc(), result.getStdOut()); - } catch (Exception e) { - logger.error("executeInVR FAILED via " + agentName + " on " - + routerIp + ":" + cmd + ", " + e.getMessage(), e); - } - return new ExecutionResult(false, ""); - } - - @Override - public ExecutionResult createFileInVR(String routerIp, String path, - String filename, String content) { - String error = null; - logger.debug("createFileInVR via " + agentName + " on " + routerIp - + ": " + path + "/" + filename + ", content: " + content); - try { - CloudstackPlugin cSp = new CloudstackPlugin(c); - boolean result = cSp.ovsDomrUploadFile(routerIp, path, filename, - content); - return new ExecutionResult(result, ""); - } catch (Exception e) { - error = e.getMessage(); - logger.warn( - "createFileInVR failed for " + path + "/" + filename - + " in VR " + routerIp + " via " + agentName + ": " - + error, e); - } - return new ExecutionResult(error == null, error); - } - - @Override - public ExecutionResult prepareCommand(NetworkElementCommand cmd) { - // Update IP used to access router - cmd.setRouterAccessIp(cmd - .getAccessDetail(NetworkElementCommand.ROUTER_IP)); - assert cmd.getRouterAccessIp() != null; - - if (cmd instanceof IpAssocVpcCommand) { - return prepareNetworkElementCommand((IpAssocVpcCommand) cmd); - } else if (cmd instanceof IpAssocCommand) { - return prepareNetworkElementCommand((IpAssocCommand) cmd); - } else if (cmd instanceof SetupGuestNetworkCommand) { - return prepareNetworkElementCommand((SetupGuestNetworkCommand) cmd); - } else if (cmd instanceof SetSourceNatCommand) { - return prepareNetworkElementCommand((SetSourceNatCommand) cmd); - } - return new ExecutionResult(true, null); - } - - @Override - public ExecutionResult cleanupCommand(NetworkElementCommand cmd) { - if (cmd instanceof IpAssocCommand - && !(cmd instanceof IpAssocVpcCommand)) { - return cleanupNetworkElementCommand((IpAssocCommand) cmd); - } - return new ExecutionResult(true, null); - } - - private ExecutionResult cleanupNetworkElementCommand(IpAssocCommand cmd) { - return new ExecutionResult(true, null); - } - - private ExecutionResult prepareNetworkElementCommand( - SetupGuestNetworkCommand cmd) { - return new ExecutionResult(true, null); - } - - private ExecutionResult prepareNetworkElementCommand(IpAssocVpcCommand cmd) { - return prepNetBoth(cmd - .getAccessDetail(NetworkElementCommand.ROUTER_NAME), - cmd.getIpAddresses(), "IpAssocVpcCommand"); - } - - private ExecutionResult prepareNetworkElementCommand(SetSourceNatCommand cmd) { - return new ExecutionResult(true, null); - } - - private ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) { - return prepNetBoth(cmd - .getAccessDetail(NetworkElementCommand.ROUTER_NAME), - cmd.getIpAddresses(), "IpAssocCommand"); - } - - private ExecutionResult prepNetBoth(String routerName, IpAddressTO[] ips, String type) { - Xen xen = new Xen(c); - try { - Xen.Vm vm = xen.getVmConfig(routerName); - for (IpAddressTO ip : ips) { - Integer devId = vm.getVifIdByMac(ip.getVifMacAddress()); - if (devId < 0 && "IpAssocVpcCommand".equals(type)) { - String msg = "No valid Nic devId found for " + vm.getVmName() - + " with " + ip.getVifMacAddress(); - logger.error(msg); - return new ExecutionResult(false, msg); - } else if (devId < 0 && "IpAssocCommand".equals(type)) { - // vm.get - String msg = "No valid Nic devId found for " + vm.getVmName() - + " with " + ip.getVifMacAddress() + " " - + " Ignoring for now (routervm)"; - logger.debug(msg); - devId=2; - } - ip.setNicDevId(devId); - } - } catch (Exception e) { - String msg = type + " failure on applying one ip due to exception: " + e; - logger.error(msg); - return new ExecutionResult(false, msg); - } - return new ExecutionResult(true, null); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3Configuration.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3Configuration.java deleted file mode 100644 index ff6583be3ce0..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3Configuration.java +++ /dev/null @@ -1,465 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.commons.lang.BooleanUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.hypervisor.ovm3.objects.Network; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.net.NetUtils; - -/* holds config data for the Ovm3 Hypervisor */ -public class Ovm3Configuration { - protected Logger logger = LogManager.getLogger(getClass()); - private String agentIp; - private Long agentZoneId; - private Long agentPodId; - private String agentPoolId; - private Long agentClusterId; - private String agentHostname; - private String csHostGuid; - private String agentSshUserName = "root"; - private String agentSshPassword; - private String agentOvsAgentUser = "oracle"; - private String agentOvsAgentPassword; - private Integer agentOvsAgentPort = 8899; - private Boolean agentOvsAgentSsl = false; - private String agentSshKeyFile = "id_rsa.cloud"; - private String agentOwnedByUuid = "d1a749d4295041fb99854f52ea4dea97"; - private Boolean agentIsPrimary = false; - private Boolean agentHasPrimary = false; - private Boolean agentInOvm3Pool = false; - private Boolean agentInOvm3Cluster = false; - private String ovm3PoolVip = ""; - private String agentPrivateNetworkName; - private String agentPublicNetworkName; - private String agentGuestNetworkName; - private String agentStorageNetworkName; - private String agentControlNetworkName = "control0"; - private String agentOvmRepoPath = "/OVS/Repositories"; - private String agentSecStoragePath = "/nfsmnt"; - private String agentScript = "cloudstack.py"; - private String agentCheckStorageScript = "storagehealth.py"; - private Integer agentStorageCheckTimeout = 120; - private Integer agentStorageCheckInterval = 1; - private List agentScripts = Arrays.asList(agentCheckStorageScript, agentScript); - private String agentScriptsDir = "/opt/cloudstack/bin"; - private int domRSshPort = 3922; - private String domRCloudPath = "/opt/cloud/bin/"; - private String virtualdiskdir = "VirtualDisks"; - private String templatedir = "Templates"; - private Map agentInterfaces = null; - private Boolean istest = false; - private Map rawParams = new HashMap(); - - public Ovm3Configuration(Map params) - throws ConfigurationException { - setAgentZoneId(Long.parseLong((String) params.get("zone"))); - setAgentPodId(Long.parseLong(validateParam("PodId", - (String) params.get("pod")))); - setAgentClusterId(Long.parseLong((String) params.get("cluster"))); - setOvm3PoolVip(String.valueOf(params.get("ovm3vip"))); - setAgentInOvm3Pool(BooleanUtils.toBoolean((String) params - .get("ovm3pool"))); - setAgentInOvm3Cluster(BooleanUtils.toBoolean((String) params - .get("ovm3cluster"))); - setAgentHostname(validateParam("Hostname", (String) params.get("host"))); - setAgentIp((String) params.get("ip")); - if (params.get("agentport") != null) { - setAgentOvsAgentPort(Integer.parseInt((String) params - .get("agentport"))); - } - setAgentSshUserName(validateParam("Username", - (String) params.get("username"))); - setAgentSshPassword(validateParam("Password", - (String) params.get("password"))); - setCsHostGuid(validateParam("Cloudstack Host GUID", (String) params.get("guid"))); - setAgentOvsAgentUser(validateParam("OVS Username", - (String) params.get("agentusername"))); - setAgentOvsAgentPassword(validateParam("OVS Password", - (String) params.get("agentpassword"))); - setAgentPrivateNetworkName((String) params - .get("private.network.device")); - setAgentPublicNetworkName((String) params.get("public.network.device")); - setAgentGuestNetworkName((String) params.get("guest.network.device")); - setAgentStorageNetworkName((String) params - .get("storage.network.device1")); - this.setAgentStorageCheckTimeout(NumbersUtil.parseInt( - (String) params.get("ovm3.heartbeat.timeout"), - agentStorageCheckTimeout)); - this.setAgentStorageCheckInterval(NumbersUtil.parseInt( - (String) params.get("ovm3.heartbeat.interval"), - agentStorageCheckInterval)); - validatePoolAndCluster(); - if (params.containsKey("istest")) { - setIsTest((Boolean) params.get("istest")); - } - } - - /** - * validatePoolAndCluster: - * A cluster is impossible with a pool. - * A pool is impossible without a vip. - */ - private void validatePoolAndCluster() { - if (agentInOvm3Cluster) { - logger.debug("Clustering requires a pool, setting pool to true"); - agentInOvm3Pool = true; - } - if (!NetUtils.isValidIp4(ovm3PoolVip)) { - logger.debug("No VIP, Setting ovm3pool and ovm3cluster to false"); - agentInOvm3Pool = false; - agentInOvm3Cluster = false; - ovm3PoolVip = ""; - } - } - - public String getAgentName() { - return agentHostname; - } - - public void setAgentName(String agentName) { - this.agentHostname = agentName; - } - - public String getAgentIp() { - return agentIp; - } - - public void setAgentIp(String agentIp) { - this.agentIp = agentIp; - } - - public Long getAgentZoneId() { - return agentZoneId; - } - - public void setAgentZoneId(Long agentZoneId) { - this.agentZoneId = agentZoneId; - } - - public Long getAgentPodId() { - return agentPodId; - } - - public void setAgentPodId(Long agentPodId) { - this.agentPodId = agentPodId; - } - - public String getAgentPoolId() { - return agentPoolId; - } - - public void setAgentPoolId(String agentPoolId) { - this.agentPoolId = agentPoolId; - } - - public Long getAgentClusterId() { - return agentClusterId; - } - - public void setAgentClusterId(Long agentClusterId) { - this.agentClusterId = agentClusterId; - } - - public String getAgentHostname() { - return agentHostname; - } - - public void setAgentHostname(String agentHostname) { - this.agentHostname = agentHostname; - } - - public String getCsHostGuid() { - return csHostGuid; - } - - public void setCsHostGuid(String csHostGuid) { - this.csHostGuid = csHostGuid; - } - - public String getAgentSshUserName() { - return agentSshUserName; - } - - public void setAgentSshUserName(String agentSshUserName) { - this.agentSshUserName = agentSshUserName; - } - - public String getAgentSshPassword() { - return agentSshPassword; - } - - public void setAgentSshPassword(String agentSshPassword) { - this.agentSshPassword = agentSshPassword; - } - - public String getAgentOvsAgentUser() { - return agentOvsAgentUser; - } - - public void setAgentOvsAgentUser(String agentOvsAgentUser) { - this.agentOvsAgentUser = agentOvsAgentUser; - } - - public String getAgentOvsAgentPassword() { - return agentOvsAgentPassword; - } - - public void setAgentOvsAgentPassword(String agentOvsAgentPassword) { - this.agentOvsAgentPassword = agentOvsAgentPassword; - } - - public Integer getAgentOvsAgentPort() { - return agentOvsAgentPort; - } - - public void setAgentOvsAgentPort(Integer agentOvsAgentPort) { - this.agentOvsAgentPort = agentOvsAgentPort; - } - - public Boolean getAgentOvsAgentSsl() { - return agentOvsAgentSsl; - } - - public void setAgentOvsAgentSsl(Boolean agentOvsAgentSsl) { - this.agentOvsAgentSsl = agentOvsAgentSsl; - } - - public String getAgentSshKeyFileName() { - return agentSshKeyFile; - } - - public void setAgentSshKeyFileName(String agentSshFile) { - this.agentSshKeyFile = agentSshFile; - } - - public String getAgentOwnedByUuid() { - return agentOwnedByUuid; - } - - public void setAgentOwnedByUuid(String agentOwnedByUuid) { - this.agentOwnedByUuid = agentOwnedByUuid; - } - - public Boolean getAgentIsPrimary() { - return agentIsPrimary; - } - - public void setAgentIsPrimary(Boolean agentIsPrimary) { - this.agentIsPrimary = agentIsPrimary; - } - - public Boolean getAgentHasPrimary() { - return agentHasPrimary; - } - - public void setAgentHasPrimary(Boolean agentHasPrimary) { - this.agentHasPrimary = agentHasPrimary; - } - - public Boolean getAgentInOvm3Pool() { - return agentInOvm3Pool; - } - - public void setAgentInOvm3Pool(Boolean agentInOvm3Pool) { - this.agentInOvm3Pool = agentInOvm3Pool; - } - - public Boolean getAgentInOvm3Cluster() { - return agentInOvm3Cluster; - } - - public void setAgentInOvm3Cluster(Boolean agentInOvm3Cluster) { - this.agentInOvm3Cluster = agentInOvm3Cluster; - } - - public String getOvm3PoolVip() { - return ovm3PoolVip; - } - - public void setOvm3PoolVip(String ovm3PoolVip) { - this.ovm3PoolVip = ovm3PoolVip; - } - - public String getAgentPrivateNetworkName() { - return agentPrivateNetworkName; - } - - public void setAgentPrivateNetworkName(String agentPrivateNetworkName) { - this.agentPrivateNetworkName = agentPrivateNetworkName; - } - - public String getAgentPublicNetworkName() { - return agentPublicNetworkName; - } - - public void setAgentPublicNetworkName(String agentPublicNetworkName) { - this.agentPublicNetworkName = agentPublicNetworkName; - } - - public String getAgentGuestNetworkName() { - return agentGuestNetworkName; - } - - public void setAgentGuestNetworkName(String agentGuestNetworkName) { - this.agentGuestNetworkName = agentGuestNetworkName; - } - - public String getAgentStorageNetworkName() { - return agentStorageNetworkName; - } - - public void setAgentStorageNetworkName(String agentStorageNetworkName) { - this.agentStorageNetworkName = agentStorageNetworkName; - } - - public String getAgentControlNetworkName() { - return agentControlNetworkName; - } - - public void setAgentControlNetworkName(String agentControlNetworkName) { - this.agentControlNetworkName = agentControlNetworkName; - } - - public String getAgentOvmRepoPath() { - return agentOvmRepoPath; - } - - public void setAgentOvmRepoPath(String agentOvmRepoPath) { - this.agentOvmRepoPath = agentOvmRepoPath; - } - - public String getAgentSecStoragePath() { - return agentSecStoragePath; - } - - public void setAgentSecStoragePath(String agentSecStoragePath) { - this.agentSecStoragePath = agentSecStoragePath; - } - - public int getDomRSshPort() { - return domRSshPort; - } - - public void setDomRSshPort(int domRSshPort) { - this.domRSshPort = domRSshPort; - } - - public String getDomRCloudPath() { - return domRCloudPath; - } - - public void setDomRCloudPath(String domRCloudPath) { - this.domRCloudPath = domRCloudPath; - } - public Boolean getIsTest() { - return istest; - } - public void setIsTest(Boolean t) { - istest = t; - } - public String getAgentScript() { - return agentScript; - } - - public void setAgentScript(String agentScript) { - this.agentScript = agentScript; - } - - public String getAgentScriptsDir() { - return agentScriptsDir; - } - - public void setAgentScriptsDir(String agentScriptsDir) { - this.agentScriptsDir = agentScriptsDir; - } - - public Map getAgentInterfaces() { - return agentInterfaces; - } - - public void setAgentInterfaces(Map agentInterfaces) { - this.agentInterfaces = agentInterfaces; - } - public List getAgentScripts() { - return agentScripts; - } - - public void setAgentScripts(List agentScripts) { - this.agentScripts = agentScripts; - } - public String getAgentCheckStorageScript() { - return agentCheckStorageScript; - } - - public void setAgentCheckStorageScript(String agentCheckStorageScript) { - this.agentCheckStorageScript = agentCheckStorageScript; - } - public Integer getAgentStorageCheckTimeout() { - return agentStorageCheckTimeout; - } - public void setAgentStorageCheckTimeout(Integer agentStorageCheckTimeout) { - this.agentStorageCheckTimeout = agentStorageCheckTimeout; - } - - public Integer getAgentStorageCheckInterval() { - return agentStorageCheckInterval; - } - - public void setAgentStorageCheckInterval(Integer agentStorageCheckInterval) { - this.agentStorageCheckInterval = agentStorageCheckInterval; - } - public String getVirtualDiskDir() { - return this.virtualdiskdir; - } - public String getTemplateDir() { - return this.templatedir; - } - /** - * ValidateParam: Validate the input for configure - * @param name - * @param param - * @return param - * @throws ConfigurationException - */ - private String validateParam(String name, String param) throws ConfigurationException { - if (param == null) { - String msg = "Unable to get " + name + " params are null"; - logger.debug(msg); - throw new ConfigurationException(msg); - } - return param; - } - - public Map getRawParams() { - return rawParams; - } - public void setRawParams(Map params) { - rawParams.putAll(params); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetwork.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetwork.java deleted file mode 100644 index 6c2f48dbf8de..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetwork.java +++ /dev/null @@ -1,250 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.util.List; - -import javax.naming.ConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckNetworkAnswer; -import com.cloud.agent.api.CheckNetworkCommand; -import com.cloud.agent.api.PingTestCommand; -import com.cloud.agent.api.to.NicTO; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Network; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.network.PhysicalNetworkSetupInfo; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; - -public class Ovm3HypervisorNetwork { - protected Logger logger = LogManager.getLogger(getClass()); - private Connection c; - private Ovm3Configuration config; - public Ovm3HypervisorNetwork(Connection conn, Ovm3Configuration ovm3config) { - c = conn; - config = ovm3config; - } - - public void configureNetworking() throws ConfigurationException { - /* TODO: setup meta tags for the management interface (probably - * required with multiple interfaces)? - */ - try { - Network net = new Network(c); - String controlIface = config.getAgentControlNetworkName(); - if (controlIface != null - && net.getInterfaceByName(controlIface) == null) { - logger.debug("starting " + controlIface); - net.startOvsLocalConfig(controlIface); - /* ovs replies too "fast" so the bridge can be "busy" */ - int contCount = 0; - while (net.getInterfaceByName(controlIface) == null) { - logger.debug("waiting for " + controlIface); - Thread.sleep(1 * 1000); - if (contCount > 9) { - throw new ConfigurationException("Unable to configure " - + controlIface + " on host " - + config.getAgentHostname()); - } - contCount++; - } - } else { - logger.debug("already have " + controlIface); - } - /* - * The bridge is remembered upon reboot, but not the IP or the - * config. Zeroconf also adds the route again by default. - */ - net.ovsIpConfig(controlIface, "static", - NetUtils.getLinkLocalGateway(), - NetUtils.getLinkLocalNetMask()); - CloudstackPlugin cSp = new CloudstackPlugin(c); - cSp.ovsControlInterface(controlIface, - NetUtils.getLinkLocalCIDR()); - } catch (InterruptedException e) { - logger.error("interrupted?", e); - } catch (Ovm3ResourceException e) { - String msg = "Basic configuration failed on " + config.getAgentHostname(); - logger.error(msg, e); - throw new ConfigurationException(msg + ", " + e.getMessage()); - } - } - - /**/ - private boolean isNetworkSetupByName(String nameTag) { - if (nameTag != null) { - logger.debug("Looking for network setup by name " + nameTag); - - try { - Network net = new Network(c); - net.getInterfaceList(); - if (net.getBridgeByName(nameTag) != null) { - logger.debug("Found bridge with name: " + nameTag); - return true; - } - } catch (Ovm3ResourceException e) { - logger.debug("Unxpected error looking for name: " + nameTag, e); - return false; - } - } - logger.debug("No bridge with name: " + nameTag); - return false; - } - - /* this might have to change in the future, works for now... */ - public CheckNetworkAnswer execute(CheckNetworkCommand cmd) { - logger.debug("Checking if network name setup is done on " - + config.getAgentHostname()); - - List infoList = cmd - .getPhysicalNetworkInfoList(); - /* here we assume all networks are set */ - for (PhysicalNetworkSetupInfo info : infoList) { - if (info.getGuestNetworkName() == null) { - info.setGuestNetworkName(config.getAgentGuestNetworkName()); - } - if (info.getPublicNetworkName() == null) { - info.setPublicNetworkName(config.getAgentPublicNetworkName()); - } - if (info.getPrivateNetworkName() == null) { - info.setPrivateNetworkName(config.getAgentPrivateNetworkName()); - } - if (info.getStorageNetworkName() == null) { - info.setStorageNetworkName(config.getAgentStorageNetworkName()); - } - - if (!isNetworkSetupByName(info.getGuestNetworkName())) { - String msg = "Guest Physical Network id:" - + info.getPhysicalNetworkId() - + ", Guest Network is not configured on the backend by name " - + info.getGuestNetworkName(); - logger.error(msg); - return new CheckNetworkAnswer(cmd, false, msg); - } - if (!isNetworkSetupByName(info.getPrivateNetworkName())) { - String msg = "Private Physical Network id:" - + info.getPhysicalNetworkId() - + ", Private Network is not configured on the backend by name " - + info.getPrivateNetworkName(); - logger.error(msg); - return new CheckNetworkAnswer(cmd, false, msg); - } - if (!isNetworkSetupByName(info.getPublicNetworkName())) { - String msg = "Public Physical Network id:" - + info.getPhysicalNetworkId() - + ", Public Network is not configured on the backend by name " - + info.getPublicNetworkName(); - logger.error(msg); - return new CheckNetworkAnswer(cmd, false, msg); - } - /* Storage network is optional, will revert to private otherwise */ - } - - return new CheckNetworkAnswer(cmd, true, - "Network Setup check by names is done"); - - } - - public Answer execute(PingTestCommand cmd) { - try { - if (cmd.getComputingHostIp() != null) { - CloudstackPlugin cSp = new CloudstackPlugin(c); - if (!cSp.ping(cmd.getComputingHostIp())) { - return new Answer(cmd, false, "ping failed"); - } - } else { - return new Answer(cmd, false, "why asks me to ping a router???"); - } - return new Answer(cmd, true, "success"); - } catch (Ovm3ResourceException e) { - logger.debug("Ping " + cmd.getComputingHostIp() + " failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - private String createVlanBridge(String networkName, Integer vlanId) - throws Ovm3ResourceException { - if (vlanId < 1 || vlanId > 4094) { - String msg = "Incorrect vlan " + vlanId - + ", needs to be between 1 and 4094"; - logger.error(msg); - throw new CloudRuntimeException(msg); - } - Network net = new Network(c); - /* figure out if our bridged vlan exists, if not then create */ - String brName = networkName + "." + vlanId.toString(); - try { - String physInterface = net.getPhysicalByBridgeName(networkName); - if (net.getInterfaceByName(brName) == null) { - net.startOvsVlanBridge(brName, physInterface, vlanId); - } else { - logger.debug("Interface " + brName + " already exists"); - } - } catch (Ovm3ResourceException e) { - String msg = "Unable to create vlan " + vlanId.toString() - + " bridge for " + networkName; - logger.warn(msg + ": " + e); - throw new CloudRuntimeException(msg + ":" + e.getMessage()); - } - return brName; - } - /* getNetwork needs to be split in pure retrieval versus creation */ - public String getNetwork(NicTO nic) throws Ovm3ResourceException { - String vlanId = null; - String bridgeName = null; - if (nic.getBroadcastType() == BroadcastDomainType.Vlan) { - vlanId = BroadcastDomainType.getValue(nic.getBroadcastUri()); - } - - if (nic.getType() == TrafficType.Guest) { - if (nic.getBroadcastType() == BroadcastDomainType.Vlan - && !"untagged".equalsIgnoreCase(vlanId)) { - /* This is completely the wrong place for this, we should NEVER - * create a network when we're just trying to figure out if it's there - * The name of this is misleading and wrong. - */ - bridgeName = createVlanBridge(config.getAgentGuestNetworkName(), - Integer.valueOf(vlanId)); - } else { - bridgeName = config.getAgentGuestNetworkName(); - } - - /* VLANs for other mgmt traffic ? */ - } else if (nic.getType() == TrafficType.Control) { - bridgeName = config.getAgentControlNetworkName(); - } else if (nic.getType() == TrafficType.Public) { - bridgeName = config.getAgentPublicNetworkName(); - } else if (nic.getType() == TrafficType.Management) { - bridgeName = config.getAgentPrivateNetworkName(); - } else if (nic.getType() == TrafficType.Storage) { - bridgeName = config.getAgentStorageNetworkName(); - } else { - throw new CloudRuntimeException("Unknown network traffic type:" - + nic.getType()); - } - return bridgeName; - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupport.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupport.java deleted file mode 100644 index 3deaea06db94..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupport.java +++ /dev/null @@ -1,752 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.io.File; -import java.io.IOException; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckHealthAnswer; -import com.cloud.agent.api.CheckHealthCommand; -import com.cloud.agent.api.CheckOnHostAnswer; -import com.cloud.agent.api.CheckOnHostCommand; -import com.cloud.agent.api.CheckVirtualMachineAnswer; -import com.cloud.agent.api.CheckVirtualMachineCommand; -import com.cloud.agent.api.FenceAnswer; -import com.cloud.agent.api.FenceCommand; -import com.cloud.agent.api.GetHostStatsAnswer; -import com.cloud.agent.api.GetHostStatsCommand; -import com.cloud.agent.api.HostStatsEntry; -import com.cloud.agent.api.HostVmStateReportEntry; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Common; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Linux; -import com.cloud.hypervisor.ovm3.objects.Network; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.Pool; -import com.cloud.hypervisor.ovm3.objects.Xen; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.script.Script; -import com.cloud.utils.ssh.SSHCmdHelper; -import com.cloud.vm.VirtualMachine.PowerState; -import com.cloud.vm.VirtualMachine.State; -import com.trilead.ssh2.SCPClient; - -public class Ovm3HypervisorSupport { - protected Logger logger = LogManager.getLogger(getClass()); - private Connection c; - private Ovm3Configuration config; - - public Ovm3HypervisorSupport(Connection conn, Ovm3Configuration ovm3config) { - c = conn; - config = ovm3config; - } - - /* statemap bounces */ - private Map powerStateMaps; - { - powerStateMaps = new HashMap(); - powerStateMaps.put("Stopping", PowerState.PowerOn); - powerStateMaps.put("Running", PowerState.PowerOn); - powerStateMaps.put("Stopped", PowerState.PowerOff); - powerStateMaps.put("Error", PowerState.PowerUnknown); - powerStateMaps.put("Suspended", PowerState.PowerOn); - powerStateMaps.put("Paused", PowerState.PowerOn); - /* unknown ? */ - powerStateMaps.put("Migrating", PowerState.PowerOn); - } - private Map vmStateMap = new HashMap(); - private Map stateMaps; - { - stateMaps = new HashMap(); - stateMaps.put("Stopping", State.Stopping); - stateMaps.put("Running", State.Running); - stateMaps.put("Stopped", State.Stopped); - stateMaps.put("Error", State.Error); - stateMaps.put("Suspended", State.Running); - stateMaps.put("Paused", State.Running); - stateMaps.put("Migrating", State.Migrating); - } - - /** - * removeVmState: get rid of the state of a VM - * - * @param vmName - */ - public void revmoveVmState(String vmName) { - vmStateMap.remove(vmName); - } - - /** - * vmStateMapClear: clear out the statemap and repopulate it. - * - * @throws Ovm3ResourceException - */ - public void vmStateMapClear() throws Ovm3ResourceException { - synchronized (vmStateMap) { - vmStateMap.clear(); - syncState(this.vmStateMap); - } - } - - /** - * vmStateStarting: set the state of a vm to starting - * - * @param vmName - */ - public void setVmStateStarting(String vmName) { - setVmState(vmName, State.Starting); - } - - /** - * getVmState: get the state for a vm - * - * @param vmName - * @return - */ - public State getVmState(String vmName) { - return vmStateMap.get(vmName); - } - - /** - * vmStateChange: set the state of a vm to state - * - * @param vmName - * @param state - */ - public void setVmState(String vmName, State state) { - synchronized (vmStateMap) { - vmStateMap.put(vmName, state); - } - } - - /** - * getSystemVMKeyFile: - * Figure out where the cloud keyfile lives for access to the systemvm. - * - * @param filename - * @return keyfileURI - */ - public File getSystemVMKeyFile(String filename) { - String keyPath = Script.findScript("", "scripts/vm/systemvm/" - + filename); - File keyFile = null; - if (keyPath != null) { - logger.debug("found SshKey " + keyPath); - keyFile = new File(keyPath); - } - if (keyFile == null || !keyFile.exists()) { - String key = "client/target/generated-webapp/WEB-INF/classes/scripts/vm/systemvm/" - + filename; - logger.warn("findScript failed, going for generated " + key); - keyFile = new File(key); - } - if (keyFile == null || !keyFile.exists()) { - String key = "/usr/share/cloudstack-common/scripts/vm/systemvm/" - + filename; - logger.warn("generated key retrieval failed " + key); - keyFile = new File(key); - } - return keyFile; - } - - /** - * fillHostInfo: Startup the routing for the host. - * - * @param cmd - */ - public void fillHostInfo(StartupRoutingCommand cmd) { - try { - /* get data we need from parts */ - Linux host = new Linux(c); - if (!host.getOvmVersion().startsWith("3.2.") && !host.getOvmVersion().startsWith("3.3.")) { - logger.error("Hypervisor not supported: " + host.getOvmVersion()); - throw new CloudRuntimeException( - "OVM 3.2. or 3.3. are only supported, not " - + host.getOvmVersion()); - } else { - logger.debug("Hypervisor version: " + host.getOvmVersion()); - } - cmd.setName(host.getHostName()); - cmd.setSpeed(host.getCpuKhz()); - cmd.setCpus(host.getTotalThreads()); - cmd.setCpuSockets(host.getCpuSockets()); - cmd.setMemory(host.getMemory().longValue()); - BigInteger totalmem = BigInteger.valueOf(host.getMemory() - .longValue()); - BigInteger freemem = BigInteger.valueOf(host.getFreeMemory() - .longValue()); - cmd.setDom0MinMemory(totalmem.subtract(freemem).longValue()); - // setPoolSync and setCaps. - cmd.setGuid(config.getCsHostGuid()); - cmd.setDataCenter(config.getAgentZoneId().toString()); - cmd.setPod(config.getAgentPodId().toString()); - /* TODO: cmd.setOwner(host.getManagerUuid()); */ - cmd.setCluster(config.getAgentClusterId().toString()); - cmd.setHypervisorVersion(host.getOvmVersion()); - cmd.setVersion(host.getAgentVersion()); - cmd.setHypervisorType(HypervisorType.Ovm3); - cmd.setCaps(host.getCapabilities()); - cmd.setPrivateIpAddress(c.getIp()); - cmd.setStorageIpAddress(c.getIp()); - Network net = new Network(c); - String defaultBridge = net.getBridgeByIp(c.getIp()).getName(); - if (defaultBridge == null) { - throw new CloudRuntimeException( - "Unable to obtain valid bridge with " + c.getIp()); - } - - if (config.getAgentPublicNetworkName() == null) { - config.setAgentPublicNetworkName(defaultBridge); - } - if (config.getAgentPrivateNetworkName() == null) { - config.setAgentPrivateNetworkName(config - .getAgentPublicNetworkName()); - } - if (config.getAgentGuestNetworkName() == null) { - config.setAgentGuestNetworkName(config - .getAgentPublicNetworkName()); - } - if (config.getAgentStorageNetworkName() == null) { - config.setAgentStorageNetworkName(config - .getAgentPrivateNetworkName()); - } - Map d = cmd.getHostDetails(); - d.put("public.network.device", config.getAgentPublicNetworkName()); - d.put("private.network.device", config.getAgentPrivateNetworkName()); - d.put("guest.network.device", config.getAgentGuestNetworkName()); - d.put("storage.network.device", config.getAgentStorageNetworkName()); - d.put("isprimary", config.getAgentIsPrimary().toString()); - d.put("hasprimary", config.getAgentHasPrimary().toString()); - cmd.setHostDetails(d); - logger.debug("Add an Ovm3 host " + config.getAgentHostname() + ":" - + cmd.getHostDetails()); - } catch (Ovm3ResourceException e) { - throw new CloudRuntimeException("Ovm3ResourceException: " - + e.getMessage(), e); - } - } - - /** - * setupServer: - * Add the cloudstack plugin and setup the agent. - * Add the ssh keys to the host. - * - * @param c - * @throws IOException - */ - public Boolean setupServer(String key) throws IOException { - logger.debug("Setup all bits on agent: " + config.getAgentHostname()); - /* version dependent patching ? */ - try { - com.trilead.ssh2.Connection sshConnection = SSHCmdHelper - .acquireAuthorizedConnection(config.getAgentIp(), - config.getAgentSshUserName(), - config.getAgentSshPassword()); - if (sshConnection == null) { - throw new ConfigurationException(String.format("Unable to " - + "connect to server(IP=%1$s, username=%2$s, " - + "password=%3$s", config.getAgentIp(), - config.getAgentSshUserName(), - config.getAgentSshPassword())); - } - SCPClient scp = new SCPClient(sshConnection); - String userDataScriptDir = "scripts/vm/hypervisor/ovm3/"; - String userDataScriptPath = Script.findScript("", userDataScriptDir); - if (userDataScriptPath == null) { - throw new ConfigurationException("Can not find " - + userDataScriptDir); - } - String mkdir = "mkdir -p " + config.getAgentScriptsDir(); - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, mkdir)) { - throw new ConfigurationException("Failed " + mkdir + " on " - + config.getAgentHostname()); - } - for (String script : config.getAgentScripts()) { - script = userDataScriptPath + "/" + script; - scp.put(script, config.getAgentScriptsDir(), "0755"); - } - String prepareCmd = String.format(config.getAgentScriptsDir() + "/" - + config.getAgentScript() + " --ssl=" + c.getUseSsl() + " " - + "--port=" + c.getPort()); - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, prepareCmd)) { - throw new ConfigurationException("Failed to insert module on " - + config.getAgentHostname()); - } else { - /* because of OVM 3.3.1 (might be 2000) */ - Thread.sleep(5000); - } - CloudstackPlugin cSp = new CloudstackPlugin(c); - cSp.ovsUploadSshKey(config.getAgentSshKeyFileName(), - FileUtils.readFileToString(getSystemVMKeyFile(key))); - cSp.dom0CheckStorageHealthCheck(config.getAgentScriptsDir(), - config.getAgentCheckStorageScript(), - config.getCsHostGuid(), - config.getAgentStorageCheckTimeout(), - config.getAgentStorageCheckInterval()); - } catch (Exception es) { - logger.error("Unexpected exception ", es); - String msg = "Unable to install module in agent"; - throw new CloudRuntimeException(msg); - } - return true; - } - - /** - * Get all the VMs - * - * @return - * @throws Ovm3ResourceException - */ - private Map getAllVms() throws Ovm3ResourceException { - try { - Xen vms = new Xen(c); - return vms.getRunningVmConfigs(); - } catch (Exception e) { - logger.debug("getting VM list from " + config.getAgentHostname() - + " failed", e); - throw new CloudRuntimeException("Exception on getting VMs from " - + config.getAgentHostname() + ":" + e.getMessage(), e); - } - } - - /** - * getAllVmStates: Get the state of all the VMs - * - * @return - * @throws Ovm3ResourceException - */ - private Map getAllVmStates(Map vmStateMap) - throws Ovm3ResourceException { - Map vms = getAllVms(); - final Map states = new HashMap(); - for (final Map.Entry entry : vms.entrySet()) { - Xen.Vm vm = entry.getValue(); - State ns = State.Running; - String as = vm.getVmState(); - if (vm.isControlDomain() || as == null) { - continue; - } - /* The domain is currently running on a CPU */ - /* need a more exact match! */ - if (as.contains("r")) { - ns = State.Running; - /* The domain is blocked, and not running or runnable. */ - } else if (as.contains("b")) { - ns = State.Running; - /* The domain has been paused */ - } else if (as.contains("p")) { - ns = State.Running; - /* The guest has requested to be shutdown, still migrating... */ - } else if (as.contains("s")) { - if (vmStateMap.get(vm.getVmName()) == State.Migrating) { - ns = State.Migrating; - } else { - ns = State.Stopped; - } - /* The domain has crashed */ - } else if (as.contains("c")) { - ns = State.Error; - /* - * The domain is in process of dying (if we see this twice we - * have a problem ?) - */ - } else if (as.contains("d")) { - ns = State.Stopping; - } else { - ns = State.Unknown; - } - logger.trace("state " + ns + " for " + vm.getVmName() - + " based on " + as); - states.put(vm.getVmName(), ns); - } - return states; - } - - /** - * syncState: Sync the state the VMs are in on the hypervisor. - * - * @return - * @throws Ovm3ResourceException - */ - public Map syncState() throws Ovm3ResourceException { - return syncState(this.vmStateMap); - } - - private Map syncState(Map vmStateMap) - throws Ovm3ResourceException { - Map newStates; - Map oldStates = null; - final Map changes = new HashMap(); - try { - newStates = getAllVmStates(vmStateMap); - } catch (Ovm3ResourceException e) { - logger.error("Ovm3 full sync failed: ", e); - throw e; - } - synchronized (vmStateMap) { - oldStates = new HashMap(vmStateMap.size()); - oldStates.putAll(vmStateMap); - - for (final Map.Entry entry : newStates.entrySet()) { - final String vmName = entry.getKey(); - State newState = entry.getValue(); - final State oldState = oldStates.remove(vmName); - logger.trace("state for " + vmName + ", old: " + oldState - + ", new: " + newState); - - /* eurh ? */ - if (newState == State.Stopped && oldState != State.Stopping - && oldState != null && oldState != State.Stopped) { - logger.trace("Getting power state...."); - newState = State.Running; - } - - if (logger.isTraceEnabled()) { - logger.trace("VM " + vmName + ": ovm has state " + newState - + " and we have state " - + (oldState != null ? oldState.toString() : "null")); - } - - if (newState == State.Migrating) { - logger.trace(vmName + " is migrating, skipping state check"); - continue; - } - - if (oldState == null) { - vmStateMap.put(vmName, newState); - logger.debug("New state without old state: " + vmName); - changes.put(vmName, newState); - } else if (oldState == State.Starting) { - if (newState == State.Running) { - vmStateMap.put(vmName, newState); - } else if (newState == State.Stopped) { - logger.debug("Ignoring vm " + vmName - + " because of a lag in starting the vm."); - } - } else if (oldState == State.Migrating) { - if (newState == State.Running) { - logger.debug("Detected that a migrating VM is now running: " - + vmName); - vmStateMap.put(vmName, newState); - } - } else if (oldState == State.Stopping) { - if (newState == State.Stopped) { - vmStateMap.put(vmName, newState); - } else if (newState == State.Running) { - logger.debug("Ignoring vm " + vmName - + " because of a lag in stopping the vm. "); - /* should kill it hard perhaps ? */ - } - } else if (oldState != newState) { - vmStateMap.put(vmName, newState); - if (newState == State.Stopped) { - // For now leave it be. - } - changes.put(vmName, newState); - } - } - - for (final Map.Entry entry : oldStates.entrySet()) { - final String vmName = entry.getKey(); - final State oldState = entry.getValue(); - - if (oldState == State.Stopping) { - logger.debug("Removing VM " + vmName - + " in transition state stopping."); - vmStateMap.remove(vmName); - } else if (oldState == State.Starting) { - logger.debug("Removing VM " + vmName - + " in transition state starting."); - vmStateMap.remove(vmName); - } else if (oldState == State.Stopped) { - logger.debug("Stopped VM " + vmName + " removing."); - vmStateMap.remove(vmName); - } else if (oldState == State.Migrating) { - /* - * do something smarter here.. newstate should say stopping - * already - */ - logger.debug("Ignoring VM " + vmName - + " in migrating state."); - } else { - /* if it's not there name it stopping */ - State state = State.Stopping; - logger.debug("VM " + vmName - + " is now missing from ovm3 server so removing it"); - changes.put(vmName, state); - vmStateMap.remove(vmName); - vmStateMap.put(vmName, state); - } - } - } - return changes; - } - - /** - * convertStateToPower: Convert a state, running, starting, stopped etc to a - * power state. - * - * @param s - * @param powerStateMap - * @return - */ - private PowerState convertStateToPower(State s) { - final PowerState state = powerStateMaps.get(s.toString()); - return state == null ? PowerState.PowerUnknown : state; - } - - /** - * hostVmStateReport: Get all the VM states. - * - * @return - * @throws Ovm3ResourceException - */ - public Map hostVmStateReport() - throws Ovm3ResourceException { - final Map vmStates = new HashMap(); - for (final Map.Entry vm : vmStateMap.entrySet()) { - logger.debug("VM " + vm.getKey() + " state: " + vm.getValue() + ":" - + convertStateToPower(vm.getValue())); - vmStates.put(vm.getKey(), new HostVmStateReportEntry( - convertStateToPower(vm.getValue()), c.getIp())); - } - return vmStates; - } - - /** - * CheckHealthAnwer: Check the health of an agent on the hypervisor. - * TODO: should elaborate here with checks... - * - * @param cmd - * @return - */ - public CheckHealthAnswer execute(CheckHealthCommand cmd) { - Common test = new Common(c); - String ping = "put"; - String pong; - try { - pong = test.echo(ping); - } catch (Ovm3ResourceException e) { - logger.debug("CheckHealth went wrong: " + config.getAgentHostname() - + ", " + e.getMessage(), e); - return new CheckHealthAnswer(cmd, false); - } - if (ping.contentEquals(pong)) { - return new CheckHealthAnswer(cmd, true); - } - logger.debug("CheckHealth did not receive " + ping + " but got " + pong - + " from " + config.getAgentHostname()); - return new CheckHealthAnswer(cmd, false); - } - - /** - * primaryCheck - * - * @return - */ - public boolean primaryCheck() { - if ("".equals(config.getOvm3PoolVip())) { - logger.debug("No cluster vip, not checking for primary"); - return false; - } - - try { - CloudstackPlugin cSp = new CloudstackPlugin(c); - if (cSp.dom0HasIp(config.getOvm3PoolVip())) { - logger.debug(config.getAgentHostname() - + " is a primary, already has vip " - + config.getOvm3PoolVip()); - config.setAgentIsPrimary(true); - } else if (cSp.ping(config.getOvm3PoolVip())) { - logger.debug(config.getAgentHostname() - + " has a primary, someone has vip " - + config.getOvm3PoolVip()); - config.setAgentHasPrimary(true); - } else { - logger.debug(config.getAgentHostname() - + " becomes a primary, no one has vip " - + config.getOvm3PoolVip()); - config.setAgentIsPrimary(true); - } - } catch (Ovm3ResourceException e) { - logger.debug(config.getAgentHostname() - + " can't reach primary: " + e.getMessage()); - config.setAgentHasPrimary(false); - } - return config.getAgentIsPrimary(); - } - - /* Check if the host is in ready state for CS */ - public ReadyAnswer execute(ReadyCommand cmd) { - try { - Linux host = new Linux(c); - Pool pool = new Pool(c); - - /* only interesting when doing cluster */ - if (!host.getIsPrimary() && config.getAgentInOvm3Cluster()) { - if (pool.getPoolPrimaryVip().equalsIgnoreCase(c.getIp())) { - /* check pool state here */ - return new ReadyAnswer(cmd); - } else { - logger.debug("Primary IP changes to " - + pool.getPoolPrimaryVip() + ", it should be " - + c.getIp()); - return new ReadyAnswer(cmd, "I am not the primary server"); - } - } else if (host.getIsPrimary()) { - logger.debug("Primary, not clustered " - + config.getAgentHostname()); - return new ReadyAnswer(cmd); - } else { - logger.debug("No primary, not clustered " - + config.getAgentHostname()); - return new ReadyAnswer(cmd); - } - } catch (CloudRuntimeException | Ovm3ResourceException e) { - logger.debug("XML RPC Exception" + e.getMessage(), e); - throw new CloudRuntimeException("XML RPC Exception" - + e.getMessage(), e); - } - - } - - /* check "the" virtual machine */ - public CheckVirtualMachineAnswer execute( - final CheckVirtualMachineCommand cmd) { - logger.debug("CheckVirtualMachineCommand: " + cmd.getVmName()); - String vmName = cmd.getVmName(); - try { - CloudstackPlugin plug = new CloudstackPlugin(c); - Integer vncPort = Integer.valueOf(plug.getVncPort(vmName)); - if (vncPort == 0) { - logger.warn("No VNC port for " + vmName); - } - /* we already have the state ftw */ - Map states = getAllVmStates(vmStateMap); - State vmState = states.get(vmName); - if (vmState == null) { - logger.warn("Check state of " + vmName - + " return null in CheckVirtualMachineCommand"); - vmState = State.Stopped; - } - synchronized (vmStateMap) { - vmStateMap.put(vmName, State.Running); - } - return new CheckVirtualMachineAnswer(cmd, - convertStateToPower(vmState), vncPort); - } catch (Ovm3ResourceException e) { - logger.debug("Check migration for " + vmName + " failed", e); - return new CheckVirtualMachineAnswer(cmd, - convertStateToPower(State.Stopped), null); - } - } - - /* - * TODO: leave cluster, leave pool, release ownership, cleanout and - * start over ? - * For now leave it as we're not clustering in OVM terms. - */ - public MaintainAnswer execute(MaintainCommand cmd) { - logger.debug("MaintainCommand"); - /* - * try { - * Network net = new Network(c); - * net.stopOvsLocalConfig(config.getAgentControlNetworkName()); - * } catch (Ovm3ResourceException e) { - * logger.debug("unable to disable " + - * config.getAgentControlNetworkName(), e); - * } - */ - return new MaintainAnswer(cmd); - } - - public Answer execute(GetHostStatsCommand cmd) { - try { - CloudstackPlugin cSp = new CloudstackPlugin(c); - Map stats = cSp.ovsDom0Stats(config - .getAgentPublicNetworkName()); - Double cpuUtil = Double.parseDouble(stats.get("cpu")); - Double rxBytes = Double.parseDouble(stats.get("rx")); - Double txBytes = Double.parseDouble(stats.get("tx")); - Double totalMemory = Double.parseDouble(stats.get("total")); - Double freeMemory = Double.parseDouble(stats.get("free")); - HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), - cpuUtil, rxBytes, txBytes, "host", totalMemory, freeMemory, - 0, 0); - return new GetHostStatsAnswer(cmd, hostStats); - } catch (Exception e) { - logger.debug("Unable to get host stats for: " + cmd.getHostName(), - e); - return new Answer(cmd, false, e.getMessage()); - } - } - - /* - * We rely on storage health with CheckOnHostCommand.... - */ - public FenceAnswer execute(FenceCommand cmd) { - logger.debug("FenceCommand"); - try { - Boolean res = false; - return new FenceAnswer(cmd, res, res.toString()); - } catch (Exception e) { - logger.error("Unable to fence" + cmd.getHostIp(), e); - return new FenceAnswer(cmd, false, e.getMessage()); - } - } - - public CheckOnHostAnswer execute(CheckOnHostCommand cmd) { - logger.debug("CheckOnHostCommand"); - CloudstackPlugin csp = new CloudstackPlugin(c); - try { - Boolean alive = csp.dom0CheckStorageHealth(config.getAgentScriptsDir(), - config.getAgentCheckStorageScript(), - cmd.getHost().getGuid(), - config.getAgentStorageCheckTimeout()); - String msg = ""; - if (alive == null) { - msg = "storage check failed for " + cmd.getHost().getGuid(); - } else if (alive) { - msg = "storage check ok for " + cmd.getHost().getGuid(); - } else { - msg = "storage dead for " + cmd.getHost().getGuid(); - } - logger.debug(msg); - return new CheckOnHostAnswer(cmd, alive, msg); - } catch (Ovm3ResourceException e) { - return new CheckOnHostAnswer(cmd, false, "Error while checking storage for " +cmd.getHost().getGuid() +": " + e.getMessage()); - } - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3StoragePool.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3StoragePool.java deleted file mode 100644 index 4b7cc127eaca..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3StoragePool.java +++ /dev/null @@ -1,748 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.io.File; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.apache.xmlrpc.XmlRpcException; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateStoragePoolCommand; -import com.cloud.agent.api.DeleteStoragePoolCommand; -import com.cloud.agent.api.GetStorageStatsAnswer; -import com.cloud.agent.api.GetStorageStatsCommand; -import com.cloud.agent.api.ModifyStoragePoolAnswer; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; -import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; -import com.cloud.agent.api.to.StorageFilerTO; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Linux; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.Pool; -import com.cloud.hypervisor.ovm3.objects.PoolOCFS2; -import com.cloud.hypervisor.ovm3.objects.Repository; -import com.cloud.hypervisor.ovm3.objects.StoragePlugin; -import com.cloud.hypervisor.ovm3.objects.StoragePlugin.FileProperties; -import com.cloud.hypervisor.ovm3.objects.StoragePlugin.StorageDetails; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.template.TemplateProp; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.script.Script; -import com.cloud.utils.ssh.SshHelper; - -public class Ovm3StoragePool { - protected Logger logger = LogManager.getLogger(getClass()); - private Connection c; - private Ovm3Configuration config; - private OvmObject ovmObject = new OvmObject(); - - public Ovm3StoragePool(Connection conn, Ovm3Configuration ovm3config) { - c = conn; - config = ovm3config; - } - - /** - * Setting up the roles on a host, we set all roles on all hosts! - * - * @param pool - * @throws ConfigurationException - */ - private void setRoles(Pool pool) throws ConfigurationException { - try { - pool.setServerRoles(pool.getValidRoles()); - } catch (Ovm3ResourceException e) { - String msg = "Failed to set server role for host " - + config.getAgentHostname() + ": " + e.getMessage(); - logger.error(msg); - throw new ConfigurationException(msg); - } - } - - /** - * If you don't own the host you can't fiddle with it. - * - * @param pool - * @throws ConfigurationException - */ - private void takeOwnership(Pool pool) throws ConfigurationException { - try { - logger.debug("Take ownership of host " + config.getAgentHostname()); - pool.takeOwnership(config.getAgentOwnedByUuid(), ""); - } catch (Ovm3ResourceException e) { - String msg = "Failed to take ownership of host " - + config.getAgentHostname(); - logger.error(msg); - throw new ConfigurationException(msg); - } - } - - /** - * If you don't own the host you can't fiddle with it. - * - * @param pool - * @throws ConfigurationException - */ - /* FIXME: Placeholders for now, implement later!!!! */ - private void takeOwnership33x(Pool pool) throws ConfigurationException { - try { - logger.debug("Take ownership of host " + config.getAgentHostname()); - String event = "http://localhost:10024/event"; - String stats = "http://localhost:10024/stats"; - String mgrCert = "None"; - String signCert = "None"; - pool.takeOwnership33x(config.getAgentOwnedByUuid(), - event, - stats, - mgrCert, - signCert); - } catch (Ovm3ResourceException e) { - String msg = "Failed to take ownership of host " - + config.getAgentHostname(); - logger.error(msg); - throw new ConfigurationException(msg); - } - } - /** - * Prepare a host to become part of a pool, the roles and ownership are - * important here. - * - * @return - * @throws ConfigurationException - */ - public boolean prepareForPool() throws ConfigurationException { - /* need single primary uuid */ - try { - Linux host = new Linux(c); - Pool pool = new Pool(c); - - /* setup pool and role, needs utility to be able to do things */ - if (host.getServerRoles().contentEquals( - pool.getValidRoles().toString())) { - logger.info("Server role for host " + config.getAgentHostname() - + " is ok"); - } else { - setRoles(pool); - } - if (host.getMembershipState().contentEquals("Unowned")) { - if (host.getOvmVersion().startsWith("3.2.")) { - takeOwnership(pool); - } else if (host.getOvmVersion().startsWith("3.3.")) { - takeOwnership33x(pool); - } - } else { - if (host.getManagerUuid().equals(config.getAgentOwnedByUuid())) { - String msg = "Host " + config.getAgentHostname() - + " owned by us"; - logger.debug(msg); - return true; - } else { - String msg = "Host " + config.getAgentHostname() - + " already part of a pool, and not owned by us"; - logger.error(msg); - throw new ConfigurationException(msg); - } - } - } catch (ConfigurationException | Ovm3ResourceException es) { - String msg = "Failed to prepare " + config.getAgentHostname() - + " for pool: " + es.getMessage(); - logger.error(msg); - throw new ConfigurationException(msg); - } - return true; - } - - /** - * Setup a pool in general, this creates a repo if it doesn't exist yet, if - * it does however we mount it. - * - * @param cmd - * @return - * @throws Ovm3ResourceException - */ - private Boolean setupPool(StorageFilerTO cmd) throws Ovm3ResourceException { - String primUuid = cmd.getUuid(); - String ssUuid = ovmObject.deDash(primUuid); - String fsType = "nfs"; - String clusterUuid = config.getAgentOwnedByUuid().substring(0, 15); - String managerId = config.getAgentOwnedByUuid(); - String poolAlias = cmd.getHost() + ":" + cmd.getPath(); - String mountPoint = String.format("%1$s:%2$s", cmd.getHost(), - cmd.getPath()) - + "/VirtualMachines"; - Integer poolSize = 0; - - Pool poolHost = new Pool(c); - PoolOCFS2 poolFs = new PoolOCFS2(c); - if (config.getAgentIsPrimary()) { - try { - logger.debug("Create poolfs on " + config.getAgentHostname() - + " for repo " + primUuid); - /* double check if we're not overwritting anything here!@ */ - poolFs.createPoolFs(fsType, mountPoint, clusterUuid, primUuid, - ssUuid, managerId); - } catch (Ovm3ResourceException e) { - throw e; - } - try { - poolHost.createServerPool(poolAlias, primUuid, - config.getOvm3PoolVip(), poolSize + 1, - config.getAgentHostname(), c.getIp()); - } catch (Ovm3ResourceException e) { - throw e; - } - } else if (config.getAgentHasPrimary()) { - try { - poolHost.joinServerPool(poolAlias, primUuid, - config.getOvm3PoolVip(), poolSize + 1, - config.getAgentHostname(), c.getIp()); - } catch (Ovm3ResourceException e) { - throw e; - } - } - try { - /* should contain check if we're in an OVM pool or not */ - CloudstackPlugin csp = new CloudstackPlugin(c); - Boolean vip = csp.dom0CheckPort(config.getOvm3PoolVip(), 22, 60, 1); - if (!vip) { - throw new Ovm3ResourceException( - "Unable to reach Ovm3 Pool VIP " - + config.getOvm3PoolVip()); - } - /* - * should also throw exception, we need to stop pool creation here, - * or is the manual addition fine? - */ - if (!addMembers()) { - return false; - } - } catch (Ovm3ResourceException e) { - throw new Ovm3ResourceException("Unable to add members to pool" - + e.getMessage()); - } - return true; - } - - /** - * Adding members to a pool, this is separate from cluster configuration in - * OVM. - * - * @return - * @throws Ovm3ResourceException - */ - private Boolean addMembers() throws Ovm3ResourceException { - List members = new ArrayList(); - try { - Connection m = new Connection(config.getOvm3PoolVip(), c.getPort(), - c.getUserName(), c.getPassword()); - Pool poolPrimary = new Pool(m); - if (poolPrimary.isInAPool()) { - members.addAll(poolPrimary.getPoolMemberList()); - if (!poolPrimary.getPoolMemberList().contains(c.getIp()) - && c.getIp().equals(config.getOvm3PoolVip())) { - members.add(c.getIp()); - } - } else { - logger.warn(c.getIp() + " noticed primary " - + config.getOvm3PoolVip() + " is not part of pool"); - return false; - } - /* a cluster shares usernames and passwords */ - for (String member : members) { - Connection x = new Connection(member, c.getPort(), - c.getUserName(), c.getPassword()); - Pool poolM = new Pool(x); - if (poolM.isInAPool()) { - poolM.setPoolMemberList(members); - logger.debug("Added " + members + " to pool " - + poolM.getPoolId() + " on member " + member); - } else { - logger.warn(member - + " unable to be member of a pool it's not in"); - return false; - } - } - } catch (Exception e) { - throw new Ovm3ResourceException("Unable to add members: " - + e.getMessage(), e); - } - return true; - } - - /** - * Get a host out of a pool/cluster, this should unmount all FSs though. - * - * @param cmd - * @return - */ - public Answer execute(DeleteStoragePoolCommand cmd) { - try { - Pool pool = new Pool(c); - pool.leaveServerPool(cmd.getPool().getUuid()); - /* also connect to the primary and update the pool list ? */ - } catch (Ovm3ResourceException e) { - logger.debug( - "Delete storage pool on host " - + config.getAgentHostname() - + " failed, however, we leave to user for cleanup and tell management server it succeeded", - e); - } - - return new Answer(cmd); - } - - /** - * Create primary storage, which is a repository in OVM. Pooling is part of - * this too and clustering should be in the future. - * - * @param cmd - * @return - * @throws XmlRpcException - */ - private boolean createRepo(StorageFilerTO cmd) throws XmlRpcException { - String basePath = config.getAgentOvmRepoPath(); - Repository repo = new Repository(c); - String primUuid = repo.deDash(cmd.getUuid()); - String ovsRepo = basePath + "/" + primUuid; - /* should add port ? */ - String mountPoint = String.format("%1$s:%2$s", cmd.getHost(), - cmd.getPath()); - String msg; - - if (cmd.getType() == StoragePoolType.NetworkFilesystem) { - Boolean repoExists = false; - /* base repo first */ - try { - repo.mountRepoFs(mountPoint, ovsRepo); - } catch (Ovm3ResourceException e) { - logger.debug("Unable to mount NFS repository " + mountPoint - + " on " + ovsRepo + " requested for " - + config.getAgentHostname() + ": " + e.getMessage()); - } - try { - repo.addRepo(mountPoint, ovsRepo); - repoExists = true; - } catch (Ovm3ResourceException e) { - logger.debug("NFS repository " + mountPoint + " on " + ovsRepo - + " not found creating repo: " + e.getMessage()); - } - if (!repoExists) { - try { - /* - * a mount of the NFS fs by the createrepo actually - * generates a null if it is already mounted... -sigh- - */ - repo.createRepo(mountPoint, ovsRepo, primUuid, - "OVS Repository"); - } catch (Ovm3ResourceException e) { - msg = "NFS repository " + mountPoint + " on " + ovsRepo - + " create failed!"; - logger.debug(msg); - throw new CloudRuntimeException(msg + " " + e.getMessage(), - e); - } - } - - /* add base pooling first */ - if (config.getAgentInOvm3Pool()) { - try { - msg = "Configuring " + config.getAgentHostname() + "(" - + config.getAgentIp() + ") for pool"; - logger.debug(msg); - setupPool(cmd); - msg = "Configured host for pool"; - /* add clustering after pooling */ - if (config.getAgentInOvm3Cluster()) { - msg = "Setup " + config.getAgentHostname() + "(" - + config.getAgentIp() + ") for cluster"; - logger.debug(msg); - /* setup cluster */ - /* - * From cluster.java - * configure_server_for_cluster(cluster conf, fs, mount, - * fsuuid, poolfsbaseuuid) - */ - /* create_cluster(poolfsuuid,) */ - } - } catch (Ovm3ResourceException e) { - msg = "Unable to setup pool on " - + config.getAgentHostname() + "(" - + config.getAgentIp() + ") for " + ovsRepo; - throw new CloudRuntimeException(msg + " " + e.getMessage(), - e); - } - } else { - msg = "no way dude I can't stand for this"; - logger.debug(msg); - } - /* - * this is to create the .generic_fs_stamp else we're not allowed to - * create any data\disks on this thing - */ - try { - URI uri = new URI(cmd.getType() + "://" + cmd.getHost() + ":" - + +cmd.getPort() + cmd.getPath() + "/VirtualMachines"); - setupNfsStorage(uri, cmd.getUuid()); - } catch (Exception e) { - msg = "NFS mount " + mountPoint + " on " - + config.getAgentSecStoragePath() + "/" + cmd.getUuid() - + " create failed!"; - throw new CloudRuntimeException(msg + " " + e.getMessage(), e); - } - } else { - msg = "NFS repository " + mountPoint + " on " + ovsRepo - + " create failed, was type " + cmd.getType(); - logger.debug(msg); - return false; - } - - try { - /* systemvm iso is imported here */ - prepareSecondaryStorageStore(ovsRepo, cmd.getUuid(), cmd.getHost()); - } catch (Exception e) { - msg = "systemvm.iso copy failed to " + ovsRepo; - logger.debug(msg, e); - return false; - } - return true; - } - - /** - * Copy the systemvm.iso in if it doesn't exist or the size differs. - * - * @param storageUrl - * @param poolUuid - * @param host - */ - private void prepareSecondaryStorageStore(String storageUrl, - String poolUuid, String host) { - String mountPoint = storageUrl; - - GlobalLock lock = GlobalLock.getInternLock("prepare.systemvm"); - try { - /* double check */ - if (config.getAgentHasPrimary() && config.getAgentInOvm3Pool()) { - logger.debug("Skip systemvm ISO copy, leave it to the primary"); - return; - } - if (lock.lock(3600)) { - try { - /* - * save src iso real name for reuse, so we don't depend on - * other happy little accidents. - */ - File srcIso = getSystemVMPatchIsoFile(); - String destPath = mountPoint + "/ISOs/"; - try { - StoragePlugin sp = new StoragePlugin(c); - FileProperties fp = sp.storagePluginGetFileInfo( - poolUuid, host, destPath + "/" - + srcIso.getName()); - if (fp.getSize() != srcIso.getTotalSpace()) { - logger.info(" System VM patch ISO file already exists: " - + srcIso.getAbsolutePath().toString() - + ", destination: " + destPath); - } - } catch (Exception e) { - logger.info("Copy System VM patch ISO file to secondary storage. source ISO: " - + srcIso.getAbsolutePath() - + ", destination: " - + destPath); - try { - /* Perhaps use a key instead ? */ - SshHelper - .scpTo(c.getIp(), 22, config - .getAgentSshUserName(), null, - config.getAgentSshPassword(), - destPath, srcIso.getAbsolutePath() - .toString(), "0644"); - } catch (Exception es) { - logger.error("Unexpected exception ", es); - String msg = "Unable to copy systemvm ISO on secondary storage. src location: " - + srcIso.toString() - + ", dest location: " - + destPath; - logger.error(msg); - throw new CloudRuntimeException(msg, es); - } - } - } finally { - lock.unlock(); - } - } - } finally { - lock.releaseRef(); - } - } - - /** - * The secondary storage mountpoint is a uuid based on the host combined - * with the path. - * - * @param url - * @return - * @throws Ovm3ResourceException - */ - public String setupSecondaryStorage(String url) - throws Ovm3ResourceException { - URI uri = URI.create(url); - if (uri.getHost() == null) { - throw new Ovm3ResourceException( - "Secondary storage host can not be empty!"); - } - String uuid = ovmObject.newUuid(uri.getHost() + ":" + uri.getPath()); - logger.info("Secondary storage with uuid: " + uuid); - return setupNfsStorage(uri, uuid); - } - - /** - * Sets up NFS Storage - * - * @param uri - * @param uuid - * @return - * @throws Ovm3ResourceException - */ - private String setupNfsStorage(URI uri, String uuid) - throws Ovm3ResourceException { - String fsUri = "nfs"; - String msg = ""; - String mountPoint = config.getAgentSecStoragePath() + "/" + uuid; - Linux host = new Linux(c); - - Map fsList = host.getFileSystemMap(fsUri); - Linux.FileSystem fs = fsList.get(uuid); - if (fs == null || !fs.getRemoteDir().equals(mountPoint)) { - try { - StoragePlugin sp = new StoragePlugin(c); - sp.storagePluginMountNFS(uri.getHost(), uri.getPath(), uuid, - mountPoint); - msg = "Nfs storage " + uri + " mounted on " + mountPoint; - return uuid; - } catch (Ovm3ResourceException ec) { - msg = "Nfs storage " + uri + " mount on " + mountPoint - + " FAILED " + ec.getMessage(); - logger.error(msg); - throw ec; - } - } else { - msg = "NFS storage " + uri + " already mounted on " + mountPoint; - return uuid; - } - } - - /** - * Gets statistics for storage. - * - * @param cmd - * @return - */ - public GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) { - logger.debug("Getting stats for: " + cmd.getStorageId()); - try { - Linux host = new Linux(c); - Linux.FileSystem fs = host.getFileSystemByUuid(cmd.getStorageId(), - "nfs"); - StoragePlugin store = new StoragePlugin(c); - String propUuid = store.deDash(cmd.getStorageId()); - String mntUuid = cmd.getStorageId(); - if (store == null || propUuid == null || mntUuid == null - || fs == null) { - String msg = "Null returned when retrieving stats for " - + cmd.getStorageId(); - logger.error(msg); - return new GetStorageStatsAnswer(cmd, msg); - } - /* or is it mntUuid ish ? */ - StorageDetails sd = store.storagePluginGetFileSystemInfo(propUuid, - mntUuid, fs.getHost(), fs.getDevice()); - /* - * FIXME: cure me or kill me, this needs to trigger a reinit of - * primary storage, actually the problem is more deeprooted, as when - * the hypervisor reboots it looses partial context and needs to be - * reinitiated.... actually a full configure round... how to trigger - * that ? - */ - if ("".equals(sd.getSize())) { - String msg = "No size when retrieving stats for " - + cmd.getStorageId(); - logger.debug(msg); - return new GetStorageStatsAnswer(cmd, msg); - } - long total = Long.parseLong(sd.getSize()); - long used = total - Long.parseLong(sd.getFreeSize()); - return new GetStorageStatsAnswer(cmd, total, used); - } catch (Ovm3ResourceException e) { - logger.debug("GetStorageStatsCommand for " + cmd.getStorageId() - + " failed", e); - return new GetStorageStatsAnswer(cmd, e.getMessage()); - } - } - - /** - * Try to figure out where the systemvm.iso resides on the fs of the - * management server - * - * @return - */ - public File getSystemVMPatchIsoFile() { - String iso = "systemvm.iso"; - String systemVmIsoPath = Script.findScript("", "vms/" + iso); - File isoFile = null; - if (systemVmIsoPath != null) { - logger.debug("found systemvm patch ISO " + systemVmIsoPath); - isoFile = new File(systemVmIsoPath); - } - if (isoFile == null || !isoFile.exists()) { - String svm = "client/target/generated-webapp/WEB-INF/classes/vms/" - + iso; - logger.debug("last resort for systemvm patch ISO " + svm); - isoFile = new File(svm); - } - assert isoFile != null; - if (!isoFile.exists()) { - logger.error("Unable to locate " + iso + " in your setup at " - + isoFile.toString()); - } - return isoFile; - } - - /** - * Create and OCFS2 filesystem (not implemented) - * - * @param pool - * @return - * @throws XmlRpcException - */ - private Boolean createOCFS2Sr(StorageFilerTO pool) throws XmlRpcException { - logger.debug("OCFS2 Not implemented yet"); - return false; - } - - /** - * Gets the details of a storage pool, size etc - * - * @param cmd - * @return - */ - public Answer execute(ModifyStoragePoolCommand cmd) { - StorageFilerTO pool = cmd.getPool(); - logger.debug("modifying pool " + pool); - try { - if (config.getAgentInOvm3Cluster()) { - // no native ovm cluster for now, I got to break it in horrible - // ways - } - if (pool.getType() == StoragePoolType.NetworkFilesystem) { - createRepo(pool); - StoragePlugin store = new StoragePlugin(c); - String propUuid = store.deDash(pool.getUuid()); - String mntUuid = pool.getUuid(); - String nfsHost = pool.getHost(); - String nfsPath = pool.getPath(); - StorageDetails ss = store.storagePluginGetFileSystemInfo( - propUuid, mntUuid, nfsHost, nfsPath); - - Map tInfo = new HashMap(); - return new ModifyStoragePoolAnswer(cmd, Long.parseLong(ss - .getSize()), Long.parseLong(ss.getFreeSize()), tInfo); - } else if (pool.getType() == StoragePoolType.OCFS2) { - createOCFS2Sr(pool); - } - return new Answer(cmd, false, "The pool type: " - + pool.getType().name() + " is not supported."); - } catch (Exception e) { - logger.debug("ModifyStoragePoolCommand failed", e); - return new Answer(cmd, false, e.getMessage()); - } - } - - /** - * Create the primary storage pool, should add iSCSI and OCFS2 - * - * @param cmd - * @return - */ - public Answer execute(CreateStoragePoolCommand cmd) { - StorageFilerTO pool = cmd.getPool(); - logger.debug("creating pool " + pool); - try { - if (pool.getType() == StoragePoolType.NetworkFilesystem) { - createRepo(pool); - } else if (pool.getType() == StoragePoolType.IscsiLUN) { - return new Answer(cmd, false, - "iSCSI is unsupported at the moment"); - /* - * iScsi like so: getIscsiSR(conn, pool.getUuid(), - * pool.getHost(), pool.getPath(), null, null, false); - */ - } else if (pool.getType() == StoragePoolType.OCFS2) { - return new Answer(cmd, false, - "OCFS2 is unsupported at the moment"); - } else if (pool.getType() == StoragePoolType.PreSetup) { - logger.warn("pre setup for pool " + pool); - } else { - return new Answer(cmd, false, "The pool type: " - + pool.getType().name() + " is not supported."); - } - } catch (Exception e) { - String msg = "Catch Exception " + e.getClass().getName() - + ", create StoragePool failed due to " + e.toString() - + " on host:" + config.getAgentHostname() + " pool: " - + pool.getHost() + pool.getPath(); - logger.warn(msg, e); - return new Answer(cmd, false, msg); - } - return new Answer(cmd, true, "success"); - } - - /** - * Download from template url into primary storage ?.. is this relevant ? - * - * @param cmd - * @return - */ - public PrimaryStorageDownloadAnswer execute( - final PrimaryStorageDownloadCommand cmd) { - try { - Repository repo = new Repository(c); - String tmplturl = cmd.getUrl(); - String poolName = cmd.getPoolUuid(); - String image = repo.deDash(repo.newUuid()) + ".raw"; - - /* url to download from, image name, and repo to copy it to */ - repo.importVirtualDisk(tmplturl, image, poolName); - return new PrimaryStorageDownloadAnswer(image); - } catch (Exception e) { - logger.debug("PrimaryStorageDownloadCommand failed", e); - return new PrimaryStorageDownloadAnswer(e.getMessage()); - } - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupport.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupport.java deleted file mode 100644 index b1547e4a20e6..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupport.java +++ /dev/null @@ -1,201 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.NetworkRulesSystemVmCommand; -import com.cloud.agent.api.NetworkUsageAnswer; -import com.cloud.agent.api.NetworkUsageCommand; -import com.cloud.agent.api.check.CheckSshAnswer; -import com.cloud.agent.api.check.CheckSshCommand; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.resources.Ovm3VirtualRoutingResource; -import com.cloud.utils.ExecutionResult; - -public class Ovm3VirtualRoutingSupport { - protected Logger logger = LogManager.getLogger(getClass()); - private static final String CREATE = "create"; - private static final String SUCCESS = "success"; - private final Connection c; - private final Ovm3VirtualRoutingResource vrr; - private final Ovm3Configuration config; - public Ovm3VirtualRoutingSupport(Connection conn, Ovm3Configuration ovm3config, Ovm3VirtualRoutingResource ovm3vrr) { - c = conn; - vrr = ovm3vrr; - config = ovm3config; - } - - /* copy paste, why isn't this just generic in the VirtualRoutingResource ? */ - public Answer execute(NetworkUsageCommand cmd) { - if (cmd.isForVpc()) { - return vpcNetworkUsage(cmd); - } - if (logger.isInfoEnabled()) { - logger.info("Executing resource NetworkUsageCommand " + cmd); - } - if (cmd.getOption() != null && CREATE.equals(cmd.getOption())) { - String result = networkUsage(cmd.getPrivateIP(), CREATE, null); - return new NetworkUsageAnswer(cmd, result, 0L, 0L); - } - long[] stats = getNetworkStats(cmd.getPrivateIP()); - - return new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); - } - - /* copy paste, why isn't this just generic in the VirtualRoutingResource ? */ - private String networkUsage(final String privateIpAddress, - final String option, final String ethName) { - String args = null; - if ("get".equals(option)) { - args = "-g"; - } else if (CREATE.equals(option)) { - args = "-c"; - } else if ("reset".equals(option)) { - args = "-r"; - } else if ("addVif".equals(option)) { - args = "-a"; - args += ethName; - } else if ("deleteVif".equals(option)) { - args = "-d"; - args += ethName; - } - ExecutionResult result = vrr.executeInVR(privateIpAddress, "netusage.sh", - args); - - if (result == null || !result.isSuccess()) { - return null; - } - - return result.getDetails(); - } - - /* copy paste, why isn't this just generic in the VirtualRoutingResource ? */ - private long[] getNetworkStats(String privateIP) { - String result = networkUsage(privateIP, "get", null); - long[] stats = new long[2]; - if (result != null) { - try { - String[] splitResult = result.split(":"); - int i = 0; - while (i < splitResult.length - 1) { - stats[0] += (Long.parseLong(splitResult[i++])); - stats[1] += (Long.parseLong(splitResult[i++])); - } - } catch (Exception e) { - logger.warn( - "Unable to parse return from script return of network usage command: " - + e.toString(), e); - } - } - return stats; - } - - /* copy paste, why isn't this just generic in the VirtualRoutingResource ? */ - private NetworkUsageAnswer vpcNetworkUsage(NetworkUsageCommand cmd) { - String privateIp = cmd.getPrivateIP(); - String option = cmd.getOption(); - String publicIp = cmd.getGatewayIP(); - - String args = "-l " + publicIp + " "; - if ("get".equals(option)) { - args += "-g"; - } else if (CREATE.equals(option)) { - args += "-c"; - String vpcCIDR = cmd.getVpcCIDR(); - args += " -v " + vpcCIDR; - } else if ("reset".equals(option)) { - args += "-r"; - } else if ("vpn".equals(option)) { - args += "-n"; - } else if ("remove".equals(option)) { - args += "-d"; - } else { - return new NetworkUsageAnswer(cmd, SUCCESS, 0L, 0L); - } - - ExecutionResult callResult = vrr.executeInVR(privateIp, "vpc_netusage.sh", - args); - - if (!callResult.isSuccess()) { - logger.error("Unable to execute NetworkUsage command on DomR (" - + privateIp - + "), domR may not be ready yet. failure due to " - + callResult.getDetails()); - } - - if ("get".equals(option) || "vpn".equals(option)) { - String result = callResult.getDetails(); - if (result == null || result.isEmpty()) { - logger.error(" vpc network usage get returns empty "); - } - long[] stats = new long[2]; - if (result != null) { - String[] splitResult = result.split(":"); - int i = 0; - while (i < splitResult.length - 1) { - stats[0] += (Long.parseLong(splitResult[i++])); - stats[1] += (Long.parseLong(splitResult[i++])); - } - return new NetworkUsageAnswer(cmd, SUCCESS, stats[0], - stats[1]); - } - } - return new NetworkUsageAnswer(cmd, SUCCESS, 0L, 0L); - } - - /* - * we don't for now, gave an error on migration though.... - */ - public Answer execute(NetworkRulesSystemVmCommand cmd) { - boolean success = true; - return new Answer(cmd, success, ""); - } - - public CheckSshAnswer execute(CheckSshCommand cmd) { - String vmName = cmd.getName(); - String privateIp = cmd.getIp(); - int cmdPort = cmd.getPort(); - int interval = cmd.getInterval(); - int retries = cmd.getRetries(); - - try { - CloudstackPlugin cSp = new CloudstackPlugin(c); - if (!cSp.dom0CheckPort(privateIp, cmdPort, retries, interval)) { - String msg = "Port " + cmdPort + " not reachable for " + vmName - + ": " + config.getAgentHostname(); - logger.info(msg); - return new CheckSshAnswer(cmd, msg); - } - } catch (Exception e) { - String msg = "Can not reach port " + cmdPort + " on System vm " - + vmName + ": " + config.getAgentHostname() - + " due to exception: " + e; - logger.error(msg); - return new CheckSshAnswer(cmd, msg); - } - if (logger.isDebugEnabled()) { - logger.debug("Ping " + cmdPort + " succeeded for vm " + vmName - + ": " + config.getAgentHostname() + " " + cmd); - } - return new CheckSshAnswer(cmd); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmGuestTypes.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmGuestTypes.java deleted file mode 100755 index 6b627ce11829..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmGuestTypes.java +++ /dev/null @@ -1,81 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.util.HashMap; -import java.util.Map; - -public class Ovm3VmGuestTypes { - /* /usr/lib64/python2.4/site-packages/agent/lib/assembly */ - private static final Map OVMHELPERMAP = new HashMap(); - private static final String HVM = "hvm"; - private static final String PV = "xen_pvm"; - private static final String DOMSOL = "ldoms_pvm"; - { - OVMHELPERMAP.put("Oracle Enterprise Linux 6.0 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 6.0 (64-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.0 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.0 (64-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.1 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.1 (64-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.2 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.2 (64-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.3 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.3 (64-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.4 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.4 (64-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.5 (32-bit)", PV); - OVMHELPERMAP.put("Oracle Enterprise Linux 5.5 (64-bit)", PV); - OVMHELPERMAP.put("Other Linux (32-bit)", PV); - OVMHELPERMAP.put("Other Linux (64-bit)", PV); - OVMHELPERMAP.put("Other PV (32-bit)", PV); - OVMHELPERMAP.put("Other PV (64-bit)", PV); - OVMHELPERMAP.put("Debian GNU/Linux 7(32-bit)", PV); - OVMHELPERMAP.put("Debian GNU/Linux 7(64-bit)", PV); - OVMHELPERMAP.put("Linux HVM (32-bit)", HVM); - OVMHELPERMAP.put("Linux HVM (64-bit)", HVM); - OVMHELPERMAP.put("Dos", HVM); - OVMHELPERMAP.put("Windows 7 (32-bit)", HVM); - OVMHELPERMAP.put("Windows 7 (64-bit)", HVM); - OVMHELPERMAP.put("Windows 8 (64-bit)", HVM); - OVMHELPERMAP.put("Windows Server 2003 (32-bit)", HVM); - OVMHELPERMAP.put("Windows Server 2003 (64-bit)", HVM); - OVMHELPERMAP.put("Windows Server 2008 (32-bit)", HVM); - OVMHELPERMAP.put("Windows Server 2008 (64-bit)", HVM); - OVMHELPERMAP.put("Windows Server 2008 R2 (64-bit)", HVM); - OVMHELPERMAP.put("Windows Server 2012 (64-bit)", HVM); - OVMHELPERMAP.put("Windows 2000 SP4 (32-bit)", HVM); - OVMHELPERMAP.put("Windows Vista (32-bit)", HVM); - OVMHELPERMAP.put("Windows XP SP2 (32-bit)", HVM); - OVMHELPERMAP.put("Windows XP SP3 (32-bit)", HVM); - OVMHELPERMAP.put("Sun Solaris 10(32-bit)", HVM); - OVMHELPERMAP.put("Sun Solaris 10(64-bit)", HVM); - OVMHELPERMAP.put("Sun Solaris 9(Experimental)", HVM); - OVMHELPERMAP.put("Sun Solaris 8(Experimental)", HVM); - OVMHELPERMAP.put("Sun Solaris 11 (32-bit)", HVM); - OVMHELPERMAP.put("Sun Solaris 11 (64-bit)", HVM); - OVMHELPERMAP.put("Sun Solaris PV (32-bit)", PV); - OVMHELPERMAP.put("Sun Solaris PV (64-bit)", PV); - OVMHELPERMAP.put("Sun Solaris Sparc (32-bit)", DOMSOL); - OVMHELPERMAP.put("Sun Solaris Sparc (64-bit)", DOMSOL); - } - - public String getOvm3GuestType(String stdType) { - return OVMHELPERMAP.get(stdType); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupport.java b/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupport.java deleted file mode 100644 index 4dd9f013e40d..000000000000 --- a/plugins/hypervisors/ovm3/src/main/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupport.java +++ /dev/null @@ -1,467 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.cloudstack.storage.to.TemplateObjectTO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.apache.xmlrpc.XmlRpcException; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.GetVmStatsAnswer; -import com.cloud.agent.api.GetVmStatsCommand; -import com.cloud.agent.api.GetVncPortAnswer; -import com.cloud.agent.api.GetVncPortCommand; -import com.cloud.agent.api.MigrateAnswer; -import com.cloud.agent.api.MigrateCommand; -import com.cloud.agent.api.PlugNicAnswer; -import com.cloud.agent.api.PlugNicCommand; -import com.cloud.agent.api.PrepareForMigrationAnswer; -import com.cloud.agent.api.PrepareForMigrationCommand; -import com.cloud.agent.api.UnPlugNicAnswer; -import com.cloud.agent.api.UnPlugNicCommand; -import com.cloud.agent.api.VmStatsEntry; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.NfsTO; -import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin; -import com.cloud.hypervisor.ovm3.objects.Connection; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.Xen; -import com.cloud.hypervisor.ovm3.resources.Ovm3StorageProcessor; -import com.cloud.resource.ResourceManager; -import com.cloud.storage.Volume; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.VirtualMachine.State; - -public class Ovm3VmSupport { - protected Logger logger = LogManager.getLogger(getClass()); - private OvmObject ovmObject = new OvmObject(); - private ResourceManager resourceMgr; - private Connection c; - private Ovm3HypervisorNetwork network; - private Ovm3Configuration config; - private Ovm3HypervisorSupport hypervisor; - private Ovm3StorageProcessor processor; - private Ovm3StoragePool pool; - private final Map> vmStats = new ConcurrentHashMap>(); - public Ovm3VmSupport(Connection conn, - Ovm3Configuration ovm3config, - Ovm3HypervisorSupport ovm3hyper, - Ovm3StorageProcessor ovm3stp, - Ovm3StoragePool ovm3sp, - Ovm3HypervisorNetwork ovm3hvn) { - c = conn; - config = ovm3config; - hypervisor = ovm3hyper; - pool = ovm3sp; - processor = ovm3stp; - network = ovm3hvn; - } - public Boolean createVifs(Xen.Vm vm, VirtualMachineTO spec) - throws Ovm3ResourceException { - if (spec.getNics() != null) { - NicTO[] nics = spec.getNics(); - return createVifs(vm, nics); - } else { - logger.info("No nics for vm " + spec.getName()); - return false; - } - } - - private Boolean createVifs(Xen.Vm vm, NicTO[] nics) - throws Ovm3ResourceException { - for (NicTO nic : nics) { - if (!createVif(vm, nic)) { - return false; - } - } - return true; - } - - /* should add bitrates and latency... */ - private Boolean createVif(Xen.Vm vm, NicTO nic) - throws Ovm3ResourceException { - try { - String net = network.getNetwork(nic); - if (net != null) { - logger.debug("Adding vif " + nic.getDeviceId() + " " - + nic.getMac() + " " + net + " to " + vm.getVmName()); - vm.addVif(nic.getDeviceId(), net, nic.getMac()); - } else { - logger.debug("Unable to add vif " + nic.getDeviceId() - + " no network for " + vm.getVmName()); - return false; - } - } catch (Exception e) { - String msg = "Unable to add vif " + nic.getType() + " for " - + vm.getVmName() + " " + e.getMessage(); - logger.debug(msg); - throw new Ovm3ResourceException(msg); - } - return true; - } - private Boolean deleteVif(Xen.Vm vm, NicTO nic) - throws Ovm3ResourceException { - /* here we should use the housekeeping of VLANs/Networks etc.. - * so we can clean after the last VM is gone - */ - try { - String net = network.getNetwork(nic); - if (net != null) { - logger.debug("Removing vif " + nic.getDeviceId() + " " + " " - + nic.getMac() + " " + net + " from " + vm.getVmName()); - vm.removeVif(net, nic.getMac()); - } else { - logger.debug("Unable to remove vif " + nic.getDeviceId() - + " no network for " + vm.getVmName()); - return false; - } - } catch (Exception e) { - String msg = "Unable to remove vif " + nic.getType() + " for " - + vm.getVmName() + " " + e.getMessage(); - logger.debug(msg); - throw new Ovm3ResourceException(msg); - } - return true; - } - - /* Migration should make sure both HVs are the same ? */ - public PrepareForMigrationAnswer execute(PrepareForMigrationCommand cmd) { - VirtualMachineTO vm = cmd.getVirtualMachine(); - if (logger.isDebugEnabled()) { - logger.debug("Preparing host for migrating " + vm.getName()); - } - NicTO[] nics = vm.getNics(); - try { - for (NicTO nic : nics) { - network.getNetwork(nic); - } - hypervisor.setVmState(vm.getName(), State.Migrating); - logger.debug("VM " + vm.getName() + " is in Migrating state"); - return new PrepareForMigrationAnswer(cmd); - } catch (Ovm3ResourceException e) { - logger.error("Catch Exception " + e.getClass().getName() - + " prepare for migration failed due to: " + e.getMessage()); - return new PrepareForMigrationAnswer(cmd, e); - } - } - - /* do migrations of VMs in a simple way just inside a cluster for now */ - public MigrateAnswer execute(final MigrateCommand cmd) { - final String vmName = cmd.getVmName(); - String destUuid = cmd.getHostGuid(); - String destIp = cmd.getDestinationIp(); - State state = State.Error; - /* - * TODO: figure out non pooled migration, works from CLI but not from - * the agent... perhaps pause the VM and then migrate it ? for now just - * stop the VM. - */ - String msg = "Migrating " + vmName + " to " + destIp; - logger.info(msg); - if (!config.getAgentInOvm3Cluster() && !config.getAgentInOvm3Pool()) { - try { - Xen xen = new Xen(c); - Xen.Vm vm = xen.getRunningVmConfig(vmName); - HostVO destHost = resourceMgr.findHostByGuid(destUuid); - if (destHost == null) { - msg = "Unable to find migration target host in DB " - + destUuid + " with ip " + destIp; - logger.info(msg); - return new MigrateAnswer(cmd, false, msg, null); - } - xen.stopVm(ovmObject.deDash(vm.getVmRootDiskPoolId()), - vm.getVmUuid()); - msg = destHost.toString(); - state = State.Stopping; - return new MigrateAnswer(cmd, false, msg, null); - } catch (Ovm3ResourceException e) { - msg = "Unpooled VM Migrate of " + vmName + " to " + destUuid - + " failed due to: " + e.getMessage(); - logger.debug(msg, e); - return new MigrateAnswer(cmd, false, msg, null); - } finally { - /* shouldn't we just reinitialize completely as a last resort ? */ - hypervisor.setVmState(vmName, state); - } - } else { - try { - Xen xen = new Xen(c); - Xen.Vm vm = xen.getRunningVmConfig(vmName); - if (vm == null) { - state = State.Stopped; - msg = vmName + " is no running on " + config.getAgentHostname(); - return new MigrateAnswer(cmd, false, msg, null); - } - /* not a storage migration!!! */ - xen.migrateVm(ovmObject.deDash(vm.getVmRootDiskPoolId()), - vm.getVmUuid(), destIp); - state = State.Stopping; - msg = "Migration of " + vmName + " successful"; - return new MigrateAnswer(cmd, true, msg, null); - } catch (Ovm3ResourceException e) { - msg = "Pooled VM Migrate" + ": Migration of " + vmName + " to " - + destIp + " failed due to " + e.getMessage(); - logger.debug(msg, e); - return new MigrateAnswer(cmd, false, msg, null); - } finally { - hypervisor.setVmState(vmName, state); - } - } - } - - /* - */ - public GetVncPortAnswer execute(GetVncPortCommand cmd) { - try { - Xen host = new Xen(c); - Xen.Vm vm = host.getRunningVmConfig(cmd.getName()); - Integer vncPort = vm.getVncPort(); - logger.debug("get vnc port for " + cmd.getName() + ": " + vncPort); - return new GetVncPortAnswer(cmd, c.getIp(), vncPort); - } catch (Ovm3ResourceException e) { - logger.debug("get vnc port for " + cmd.getName() + " failed", e); - return new GetVncPortAnswer(cmd, e.getMessage()); - } - } - - private VmStatsEntry getVmStat(String vmName) { - CloudstackPlugin cSp = new CloudstackPlugin(c); - Map oldVmStats = null; - Map newVmStats = null; - VmStatsEntry stats = new VmStatsEntry(); - try { - if (vmStats.containsKey(vmName)) { - oldVmStats = new HashMap(); - oldVmStats.putAll(vmStats.get(vmName)); - } - newVmStats = cSp.ovsDomUStats(vmName); - } catch (Ovm3ResourceException e) { - logger.info("Unable to retrieve stats from " + vmName, e); - return stats; - } - if (oldVmStats == null) { - logger.debug("No old stats retrieved stats from " + vmName); - stats.setNumCPUs(1); - stats.setNetworkReadKBs(0); - stats.setNetworkWriteKBs(0); - stats.setDiskReadKBs(0); - stats.setDiskWriteKBs(0); - stats.setDiskReadIOs(0); - stats.setDiskWriteIOs(0); - stats.setCPUUtilization(0); - stats.setEntityType("vm"); - } else { - logger.debug("Retrieved new stats from " + vmName); - int cpus = Integer.parseInt(newVmStats.get("vcpus")); - stats.setNumCPUs(cpus); - stats.setNetworkReadKBs(doubleMin(newVmStats.get("rx_bytes"), oldVmStats.get("rx_bytes"))); - stats.setNetworkWriteKBs(doubleMin(newVmStats.get("tx_bytes"), oldVmStats.get("tx_bytes"))); - stats.setDiskReadKBs(doubleMin(newVmStats.get("rd_bytes"), oldVmStats.get("rd_bytes"))); - stats.setDiskWriteKBs(doubleMin(newVmStats.get("rw_bytes"), oldVmStats.get("rw_bytes"))); - stats.setDiskReadIOs(doubleMin(newVmStats.get("rd_ops"), oldVmStats.get("rd_ops"))); - stats.setDiskWriteIOs(doubleMin(newVmStats.get("rw_ops"), oldVmStats.get("rw_ops"))); - Double dCpu = doubleMin(newVmStats.get("cputime"), oldVmStats.get("cputime")); - Double dTime = doubleMin(newVmStats.get("uptime"), oldVmStats.get("uptime")); - Double cpupct = dCpu / dTime * 100 * cpus; - stats.setCPUUtilization(cpupct); - stats.setEntityType("vm"); - } - ((ConcurrentHashMap>) vmStats).put( - vmName, newVmStats); - return stats; - } - private Double doubleMin(String x, String y) { - try { - return (Double.parseDouble(x) - Double.parseDouble(y)); - } catch (NullPointerException e) { - return 0D; - } - } - - public GetVmStatsAnswer execute(GetVmStatsCommand cmd) { - List vmNames = cmd.getVmNames(); - Map vmStatsNameMap = new HashMap(); - for (String vmName : vmNames) { - VmStatsEntry e = getVmStat(vmName); - vmStatsNameMap.put(vmName, e); - } - return new GetVmStatsAnswer(cmd, - (HashMap) vmStatsNameMap); - } - - /* This is not create for us, but really start */ -/* - public boolean startVm(String repoId, String vmId) throws XmlRpcException { - Xen host = new Xen(c); - try { - if (host.getRunningVmConfig(vmId) == null) { - logger.error("Create VM " + vmId + " first on " + c.getIp()); - return false; - } else { - logger.info("VM " + vmId + " exists on " + c.getIp()); - } - host.startVm(repoId, vmId); - } catch (Exception e) { - logger.error("Failed to start VM " + vmId + " on " + c.getIp() - + " " + e.getMessage()); - return false; - } - return true; - } -*/ - /* - * TODO: OVM already cleans stuff up, just not the extra bridges which we - * don't want right now, as we'd have to keep a state table of which vlans - * need to stay on the host!? A map with vlanid -> list-o-hosts - */ - private void cleanupNetwork(List vifs) throws XmlRpcException { - /* peel out vif info for vlan stuff */ - } - - public void cleanup(Xen.Vm vm) { - try { - cleanupNetwork(vm.getVmVifs()); - } catch (XmlRpcException e) { - logger.info("Clean up network for " + vm.getVmName() + " failed", e); - } - String vmName = vm.getVmName(); - /* should become a single entity */ - vmStats.remove(vmName); - } - - /* - * Add rootdisk, datadisk and iso's - */ - public Boolean createVbds(Xen.Vm vm, VirtualMachineTO spec) { - if (spec.getDisks() == null) { - logger.info("No disks defined for " + vm.getVmName()); - return false; - } - for (DiskTO disk : spec.getDisks()) { - try { - if (disk.getType() == Volume.Type.ROOT) { - VolumeObjectTO vol = (VolumeObjectTO) disk.getData(); - String diskFile = processor.getVirtualDiskPath(vol.getUuid(), vol.getDataStore().getUuid()); - vm.addRootDisk(diskFile); - vm.setPrimaryPoolUuid(vol.getDataStore().getUuid()); - logger.debug("Adding root disk: " + diskFile); - } else if (disk.getType() == Volume.Type.ISO) { - DataTO isoTO = disk.getData(); - if (isoTO.getPath() != null) { - TemplateObjectTO template = (TemplateObjectTO) isoTO; - DataStoreTO store = template.getDataStore(); - if (!(store instanceof NfsTO)) { - throw new CloudRuntimeException( - "unsupported protocol"); - } - NfsTO nfsStore = (NfsTO) store; - String secPoolUuid = pool.setupSecondaryStorage(nfsStore - .getUrl()); - String isoPath = config.getAgentSecStoragePath() + "/" - + secPoolUuid + "/" - + template.getPath(); - vm.addIso(isoPath); - /* check if secondary storage is mounted */ - logger.debug("Adding ISO: " + isoPath); - } - } else if (disk.getType() == Volume.Type.DATADISK) { - VolumeObjectTO vol = (VolumeObjectTO) disk.getData(); - String diskFile = processor.getVirtualDiskPath(vol.getUuid(), vol.getDataStore().getUuid()); - vm.addDataDisk(diskFile); - logger.debug("Adding data disk: " - + diskFile); - } else { - throw new CloudRuntimeException("Unknown disk type: " - + disk.getType()); - } - } catch (Exception e) { - logger.debug("CreateVbds failed", e); - throw new CloudRuntimeException("Exception" + e.getMessage(), e); - } - } - return true; - } - - /** - * Implements the unplug and plug feature for Nics, the boolan decides - * to either plug (true) or unplug (false) - * - * @param nic - * @param vmName - * @param plug - * @return - */ - private Answer plugNunplugNic(NicTO nic, String vmName, Boolean plug) { - try { - Xen xen = new Xen(c); - Xen.Vm vm = xen.getVmConfig(vmName); - /* check running */ - if (vm == null) { - return new Answer(null, false, - "Unable to execute command due to missing VM"); - } - // setup the NIC in the VM config. - if (plug) { - createVif(vm, nic); - vm.setupVifs(); - } else { - deleteVif(vm, nic); - } - // execute the change - xen.configureVm(ovmObject.deDash(vm.getPrimaryPoolUuid()), - vm.getVmUuid()); - } catch (Ovm3ResourceException e) { - String msg = "Unable to execute command due to " + e.toString(); - logger.debug(msg); - return new Answer(null, false, msg); - } - return new Answer(null, true, "success"); - } - /** - * PlugNicAnswer: plug a network interface into a VM - * @param cmd - * @return - */ - public PlugNicAnswer execute(PlugNicCommand cmd) { - Answer ans = plugNunplugNic(cmd.getNic(), cmd.getVmName(), true); - return new PlugNicAnswer(cmd, ans.getResult(), ans.getDetails()); - } - - /** - * UnPlugNicAnswer: remove a nic from a VM - * @param cmd - * @return - */ - public UnPlugNicAnswer execute(UnPlugNicCommand cmd) { - Answer ans = plugNunplugNic(cmd.getNic(), cmd.getVmName(), false); - return new UnPlugNicAnswer(cmd, ans.getResult(), ans.getDetails()); - } -} diff --git a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/module.properties b/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/module.properties deleted file mode 100644 index 69e64692ef96..000000000000 --- a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=ovm3-compute -parent=compute diff --git a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/spring-ovm3-compute-context.xml b/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/spring-ovm3-compute-context.xml deleted file mode 100644 index 6880b478046b..000000000000 --- a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-compute/spring-ovm3-compute-context.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/module.properties b/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/module.properties deleted file mode 100644 index 025d4cf11c01..000000000000 --- a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=ovm3-discoverer -parent=discoverer diff --git a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/spring-ovm3-discoverer-context.xml b/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/spring-ovm3-discoverer-context.xml deleted file mode 100644 index a8a825311a58..000000000000 --- a/plugins/hypervisors/ovm3/src/main/resources/META-INF/cloudstack/ovm3-discoverer/spring-ovm3-discoverer-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CloudStackPluginTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CloudStackPluginTest.java deleted file mode 100644 index a6af6df669cf..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CloudStackPluginTest.java +++ /dev/null @@ -1,322 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.Map; - -import org.junit.Test; - -import com.cloud.hypervisor.ovm3.objects.CloudstackPlugin.ReturnCode; - -public class CloudStackPluginTest { - private static final String VMNAME = "test"; - String domrIp = "169.254.3.2"; - public String getDomrIp() { - return domrIp; - } - - public String getDom0Ip() { - return dom0Ip; - } - - public Integer getDomrPort() { - return domrPort; - } - - String dom0Ip = "192.168.1.64"; - Integer domrPort = 3922; - String host = "ovm-1"; - String path = "/tmp"; - String dirpath = "/tmp/testing"; - String filename = "test.txt"; - String content = "This is some content"; - String bridge = "xenbr0"; - String vncPort = "5900"; - Integer port = 8899; - Integer retries = 1; - Integer interval = 1; - Integer timeout = 120; - - ConnectionTest con = new ConnectionTest(); - CloudstackPlugin cSp = new CloudstackPlugin(con); - XmlTestResultTest results = new XmlTestResultTest(); - - String domrExecXml = "" - + "" - + "" - + "" - + "" - + "" - + "out" - + "clearUsageRules.sh func.sh hv-kvp-daemon_3.1_amd64.deb monitorServices.py reconfigLB.sh redundant_router" - + "" - + "" - + "err" - + "" - + "" - + "" - + "rc" - + "0" - + "" - + "" - + "" - + "" - + ""; - String dom0StatsXml = "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "rx\n" + - "11631523\n" + - "\n" + - "\n" + - "\n" + - "total\n" + - "4293918720\n" + - "\n" + - "\n" + - "tx\n" + - "16927399\n" + - "\n" + - "\n" + - "\n" + - "cpu\n" + - "1.5\n" + - "\n" + - "\n" + - "free\n" + - "3162505216\n" + - "\n" + - "\n" + - "\n" + - "\n" + - ""; - String domuStatsXml = "" - + "" - + "" - + "" - + "" - + "" - + "uptime" - + "862195495455" - + "" - + "" - + "rx_bytes" - + "52654010" - + "" - + "" - + "wr_ops" - + "521674" - + "" - + "" - + "vcpus" - + "1" - + "" - + "" - + "cputime" - + "295303661496" - + "" - + "" - + "rd_ops" - + "14790" - + "" - + "" - + "rd_bytes" - + "250168320" - + "" - + "" - + "tx_bytes" - + "161389183" - + "" - + "" - + "wr_bytes" - + "1604468736" - + "" - + "" - + "" - + "" - + ""; - private String dom0StorageCheckXml = "" - + "" - + "" - + "" - + "" - + "1" - + "0" - + "" - + "" - + "" - + ""; - public String getDom0StorageCheckXml() { - return dom0StorageCheckXml; - } - public String getDomrExecXml() { - return domrExecXml; - } - - public String getDom0StatsXml() { - return dom0StatsXml; - } - - public String getDomuStatsXml() { - return domuStatsXml; - } - - @Test - public void testDom0CheckStorageHealthCheck() throws Ovm3ResourceException { - con.setResult(dom0StorageCheckXml); - results.basicBooleanTest(cSp.dom0CheckStorageHealthCheck("", "", "", 120, 1)); - results.basicBooleanTest(cSp.dom0CheckStorageHealthCheck(), false); - } - @Test - public void testOvsUploadFile() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ovsUploadFile(path, filename, content)); - } - - @Test - public void testOvsUploadSshKey() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ovsUploadSshKey(path, content)); - } - - @Test - public void testOvsDomrUploadFile() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ovsDomrUploadFile(VMNAME, path, filename, content)); - } - - @Test - public void testGetVncPort() throws Ovm3ResourceException { - con.setResult(results.getString(vncPort)); - results.basicStringTest(cSp.getVncPort(VMNAME), vncPort); - } - - @Test - public void testDom0CheckPort() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.dom0CheckPort(host, port, retries, interval)); - /* test nothing */ - con.setNull(); - results.basicBooleanTest( - cSp.dom0CheckPort(host, port, retries, interval), false); - /* for the last test we need to fake the timeout... */ - } - - @Test - public void testDom0Ip() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.dom0HasIp(dom0Ip)); - con.setResult(results.getBoolean(false)); - results.basicBooleanTest(cSp.dom0HasIp(dom0Ip), false); - } - - @Test - public void testDomrExec() throws Ovm3ResourceException { - con.setResult(domrExecXml); - ReturnCode x = cSp.domrExec(domrIp, "ls"); - assertNotNull(x); - assertEquals(x.getExit(), (Integer) 0); - assertEquals(x.getRc(), true); - assertEquals(x.getExit(), (Integer) 0); - assertNotNull(x.getStdOut()); - - /* failed */ - domrExecXml = domrExecXml.replace("0", "1"); - domrExecXml = domrExecXml.replace("", "Something went wrong!"); - con.setResult(domrExecXml); - ReturnCode y = cSp.domrExec(domrIp, "ls"); - assertNotNull(y); - assertEquals(y.getRc(), false); - assertEquals(y.getExit(), (Integer) 1); - assertNotNull(x.getStdErr()); - } - - @Test - public void testOvsDom0Stats() throws Ovm3ResourceException { - con.setResult(dom0StatsXml); - Map stats = cSp.ovsDom0Stats(bridge); - results.basicStringTest(stats.get("cpu"), "1.5"); - } - - @Test - public void TestOvsDomUStats() throws Ovm3ResourceException { - con.setResult(domuStatsXml); - Map stats = cSp.ovsDomUStats(VMNAME); - results.basicStringTest(stats.get("cputime"), "295303661496"); - } - - @Test - public void TestDomrCheckPort() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.domrCheckPort(domrIp, domrPort)); - } - - @Test - public void TestDomrCheckSsh() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.domrCheckSsh(domrIp)); - } - - @Test - public void TestOvsControlInterface() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ovsControlInterface("control0", "169.254.0.1/16")); - } - - @Test - public void TestPing() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ping(host)); - } - - @Test - public void TestOvsCheckFile() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ovsCheckFile(filename)); - } - - @Test - public void dom0CheckStorageHealth() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.dom0CheckStorageHealth("", "", "", 120)); - con.setResult(results.getBoolean(false)); - results.basicBooleanTest(cSp.dom0CheckStorageHealth("", "", "", 120), false); - } - @Test - public void TestovsMkdirs() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(cSp.ovsMkdirs(dirpath)); - } - @Test - public void TestovsMkdirsDirExists() throws Ovm3ResourceException { - con.setResult(results.getBoolean(true)); - results.basicBooleanTest(cSp.ovsMkdirs(dirpath), false); - } - @Test - public void TestovsMkdirs2() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(cSp.ovsMkdirs(dirpath, 755)); - } - -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CommonTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CommonTest.java deleted file mode 100644 index 114ae262587f..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/CommonTest.java +++ /dev/null @@ -1,53 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import org.junit.Test; - -public class CommonTest { - ConnectionTest con = new ConnectionTest(); - Common cOm = new Common(con); - XmlTestResultTest results = new XmlTestResultTest(); - String echo = "put"; - String remoteUrl = "http://oracle:password@ovm-2:8899"; - - @Test - public void testGetApiVersion() throws Ovm3ResourceException { - con.setResult(results - .simpleResponseWrap("\n3\n")); - results.basicIntTest(cOm.getApiVersion(), 3); - } - - @Test - public void testSleep() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(cOm.sleep(1)); - } - - @Test - public void testDispatch() throws Ovm3ResourceException { - con.setResult(results.getString(echo)); - results.basicStringTest(cOm.dispatch(remoteUrl, "echo", echo), echo); - } - - @Test - public void testEcho() throws Ovm3ResourceException { - con.setResult(results.getString(echo)); - results.basicStringTest(cOm.echo(echo), echo); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/ConnectionTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/ConnectionTest.java deleted file mode 100644 index 52215c3cffa0..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/ConnectionTest.java +++ /dev/null @@ -1,161 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.xmlrpc.XmlRpcException; -import org.apache.xmlrpc.client.XmlRpcClient; -import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl; -import org.apache.xmlrpc.common.XmlRpcStreamConfig; -import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig; -import org.apache.xmlrpc.parser.XmlRpcResponseParser; -import org.apache.xmlrpc.util.SAXParsers; -import org.junit.Test; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -/* - * This is a stub for XML parsing into result sets, it also contains test for - * Connection - */ -public class ConnectionTest extends Connection { - XmlTestResultTest results = new XmlTestResultTest(); - String result; - List multiRes = new ArrayList(); - String hostIp; - private Map methodResponse = new HashMap(); - - public ConnectionTest() { - } - - @Override - public Object callTimeoutInSec(String method, List params, int timeout, - boolean debug) throws XmlRpcException { - XmlRpcStreamConfig config = new XmlRpcHttpRequestConfigImpl(); - XmlRpcClient client = new XmlRpcClient(); - client.setTypeFactory(new RpcTypeFactory(client)); - XmlRpcResponseParser parser = new XmlRpcResponseParser( - (XmlRpcStreamRequestConfig) config, client.getTypeFactory()); - XMLReader xr = SAXParsers.newXMLReader(); - xr.setContentHandler(parser); - try { - String result = null; - if (getMethodResponse(method) != null) { - result = getMethodResponse(method); - logger.debug("methodresponse call: " + method + " - " + params); - logger.trace("methodresponse reply: " + result); - } - if (result == null && multiRes.size() >= 0) { - result = getResult(); - logger.debug("getresult call: " + method + " - " + params); - logger.trace("getresult reply: " + result); - } - xr.parse(new InputSource(new StringReader(result))); - } catch (Exception e) { - throw new XmlRpcException("Exception: " + e.getMessage(), e); - } - if (parser.getErrorCode() != 0) { - throw new XmlRpcException("Fault received[" + parser.getErrorCode() - + "]: " + parser.getErrorMessage()); - } - return parser.getResult(); - } - - public void setMethodResponse(String method, String response) { - methodResponse.put(method, response); - } - - public String getMethodResponse(String method) { - if (methodResponse.containsKey(method)) { - return methodResponse.get(method); - } - return null; - } - - public void removeMethodResponse(String method) { - if (methodResponse.containsKey(method)) { - methodResponse.remove(method); - } - } - - public void setResult(String res) { - multiRes = new ArrayList(); - multiRes.add(0, res); - } - - public void setResult(List l) { - multiRes = new ArrayList(); - multiRes.addAll(l); - } - - public void setNull() { - multiRes = new ArrayList(); - multiRes.add(0, null); - } - - /* result chainsing */ - public void addResult(String e) { - multiRes.add(e); - } - - public void addNull() { - multiRes.add(null); - } - - public String getResult() { - return popResult(); - } - - public String popResult() { - String res = multiRes.get(0); - if (multiRes.size() > 1) - multiRes.remove(0); - return res; - } - - public List resultList() { - return multiRes; - } - - @Test - public void testConnection() { - String host = "ovm-1"; - String user = "admin"; - String pass = "password"; - Integer port = 8899; - List emptyParams = new ArrayList(); - Connection con = new Connection(host, port, user, pass); - results.basicStringTest(con.getIp(), host); - results.basicStringTest(con.getUserName(), user); - results.basicStringTest(con.getPassword(), pass); - results.basicIntTest(con.getPort(), port); - try { - con.callTimeoutInSec("ping", emptyParams, 1); - // con.call("ping", emptyParams, 1, false); - } catch (XmlRpcException e) { - // TODO Auto-generated catch block - System.out.println("Exception: " + e); - } - new Connection(host, user, pass); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/LinuxTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/LinuxTest.java deleted file mode 100644 index bb6a931b4640..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/LinuxTest.java +++ /dev/null @@ -1,642 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import org.junit.Test; - -public class LinuxTest { - public LinuxTest() { - } - ConnectionTest con = new ConnectionTest(); - Linux lin = new Linux(con); - XmlTestResultTest results = new XmlTestResultTest(); - - private final String DISCOVERSERVER = "<?xml version=\"1.0\" ?>" - + "<Discover_Server_Result>" - + "<Server>" - + "<Unique_Id>1d:d5:e8:91:d9:d0:ed:bd:81:c2:a6:9a:b3:d1:b7:ea</Unique_Id>" - + "<Boot_Time>1413834408</Boot_Time>" - + "<Date_Time>" - + "<Time_Zone>Europe/Amsterdam</Time_Zone>" - + "<UTC>True</UTC>" - + "</Date_Time>" - + "<NTP>" - + "<Local_Time_Source>True</Local_Time_Source>" - + "<Is_NTP_Running>True</Is_NTP_Running>" - + "</NTP>" - + "<Agent_Version>3.2.1-183</Agent_Version>" - + "<RPM_Version>3.2.1-183</RPM_Version>" - + "<OVM_Version>3.2.1-517</OVM_Version>" - + "<CPU_Type>x86_64</CPU_Type>" - + "<OS_Type>Linux</OS_Type>" - + "<OS_Name>Oracle VM Server</OS_Name>" - + "<OS_Major_Version>5</OS_Major_Version>" - + "<OS_Minor_Version>7</OS_Minor_Version>" - + "<Hypervisor_Type>xen</Hypervisor_Type>" - + "<Hypervisor_Name>Xen</Hypervisor_Name>" - + "<Host_Kernel_Release>2.6.39-300.22.2.el5uek</Host_Kernel_Release>" - + "<Host_Kernel_Version>#1 SMP Fri Jan 4 12:40:29 PST 2013</Host_Kernel_Version>" - + "<VMM>" - + "<Version>" - + "<Major>4</Major>" - + "<Minor>1</Minor>" - + "<Extra>.3OVM</Extra>" - + "</Version>" - + "<Compile_Information>" - + "<Compiler>gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)</Compiler>" - + "<By>mockbuild</By>" - + "<Domain>us.oracle.com</Domain>" - + "<Date>Wed Dec 5 09:11:29 PST 2012</Date>" - + "</Compile_Information>" - + "<Capabilities>xen-3.0-x86_64 xen-3.0-x86_32p</Capabilities>" - + "</VMM>" - + "<Pool_Unique_Id>f12842eb-f5ed-3fe7-8da1-eb0e17f5ede8</Pool_Unique_Id>" - + "<Manager_Unique_Id>d1a749d4295041fb99854f52ea4dea97</Manager_Unique_Id>" - + "<Hostname>ovm-1</Hostname>" - + "<Registered_IP>192.168.1.64</Registered_IP>" - + "<Node_Number>1</Node_Number>" - + "<Server_Roles>xen,utility</Server_Roles>" - + "<Is_Primary>true</Is_Primary>" - + "<Primary_Virtual_Ip>192.168.1.230</Primary_Virtual_Ip>" - + "<Manager_Core_API_Version>3.2.1.516</Manager_Core_API_Version>" - + "<Membership_State>Pooled</Membership_State>" - + "<Cluster_State>Offline</Cluster_State>" - + "<Statistic>" - + "<Interval>20</Interval>" - + "</Statistic>" - + "<Exports/>" - + "<Capabilities>" - + "<ISCSI>True</ISCSI>" - + "<BOND_MODE_LINK_AGGREGATION>True</BOND_MODE_LINK_AGGREGATION>" - + "<POWER_ON_WOL>True</POWER_ON_WOL>" - + "<ALL_VM_CPU_OVERSUBSCRIBE>True</ALL_VM_CPU_OVERSUBSCRIBE>" - + "<HVM_MAX_VNICS>8</HVM_MAX_VNICS>" - + "<FIBRE_CHANNEL>True</FIBRE_CHANNEL>" - + "<MAX_CONCURRENT_MIGRATION_OUT>1</MAX_CONCURRENT_MIGRATION_OUT>" - + "<LOCAL_STORAGE_ELEMENT>True</LOCAL_STORAGE_ELEMENT>" - + "<CLUSTERS>True</CLUSTERS>" - + "<CONCURRENT_MIGRATION>False</CONCURRENT_MIGRATION>" - + "<VM_MEMORY_ALIGNMENT>1048576</VM_MEMORY_ALIGNMENT>" - + "<MIGRATION_SETUP>False</MIGRATION_SETUP>" - + "<PER_VM_CPU_OVERSUBSCRIBE>True</PER_VM_CPU_OVERSUBSCRIBE>" - + "<BOND_MODE_ACTIVE_BACKUP>True</BOND_MODE_ACTIVE_BACKUP>" - + "<NFS>True</NFS>" - + "<VM_VNC_CONSOLE>True</VM_VNC_CONSOLE>" - + "<MTU_CONFIGURATION>True</MTU_CONFIGURATION>" - + "<HIGH_AVAILABILITY>True</HIGH_AVAILABILITY>" - + "<MAX_CONCURRENT_MIGRATION_IN>1</MAX_CONCURRENT_MIGRATION_IN>" - + "<VM_SERIAL_CONSOLE>True</VM_SERIAL_CONSOLE>" - + "<BOND_MODE_ADAPTIVE_LOAD_BALANCING>True</BOND_MODE_ADAPTIVE_LOAD_BALANCING>" - + "<VM_SUSPEND>True</VM_SUSPEND>" - + "<YUM_PACKAGE_MANAGEMENT>True</YUM_PACKAGE_MANAGEMENT>" - + "</Capabilities>" + "</Server>" - + "</Discover_Server_Result>"; - - public String getDiscoverserver() { - return DISCOVERSERVER; - } - - public String getDiscoverHw() { - return DISCOVERHW; - } - - public String getDiscoverFs() { - return DISCOVERFS; - } - - private final String DISCOVERHW = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - + "<Discover_Hardware_Result>" - + "<NodeInformation>" - + "<VMM>" - + "<PhysicalInfo>" - + "<ThreadsPerCore>1</ThreadsPerCore>" - + "<CoresPerSocket>1</CoresPerSocket>" - + "<SocketsPerNode>2</SocketsPerNode>" - + "<Nodes>1</Nodes>" - + "<CPUKHz>3392400</CPUKHz>" - + "<TotalPages>1048476</TotalPages>" - + "<FreePages>863459</FreePages>" - + "<HW_Caps>" - + "<Item_0>0x0f8bf3ff</Item_0>" - + "<Item_1>0x28100800</Item_1>" - + "<Item_2>0x00000000</Item_2>" - + "<Item_3>0x00000040</Item_3>" - + "<Item_4>0xb19a2223</Item_4>" - + "<Item_5>0x00000000</Item_5>" - + "<Item_6>0x00000001</Item_6>" - + "<Item_7>0x00000281</Item_7>" - + "</HW_Caps>" - + "</PhysicalInfo>" - + "</VMM>" - + "<CPUInfo>" - + "<Proc_Info>" - + "<CPU ID=\"0\">" - + "<vendor_id>GenuineIntel</vendor_id>" - + "<cpu_family>6</cpu_family>" - + "<model>2</model>" - + "<model_name>Intel Core i7 9xx (Nehalem Class Core i7)</model_name>" - + "<stepping>3</stepping>" - + "<cache_size>4096 KB</cache_size>" - + "<flags>fpu de tsc msr pae mce cx8 apic mca cmov clflush mmx fxsr sse sse2 ss syscall nx lm rep_good nopl pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 popcnt f16c hypervisor lahf_lm fsgsbase erms</flags>" - + "</CPU>" - + "<CPU ID=\"1\">" - + "<vendor_id>GenuineIntel</vendor_id>" - + "<cpu_family>6</cpu_family>" - + "<model>2</model>" - + "<model_name>Intel Core i7 9xx (Nehalem Class Core i7)</model_name>" - + "<stepping>3</stepping>" - + "<cache_size>4096 KB</cache_size>" - + "<flags>fpu de tsc msr pae mce cx8 apic mca cmov clflush mmx fxsr sse sse2 ss syscall nx lm rep_good nopl pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 popcnt f16c hypervisor lahf_lm fsgsbase erms</flags>" - + "</CPU>" - + "</Proc_Info>" - + "</CPUInfo>" - + "<IO>" - + "<SCSI>" - + "<SCSI_Host Num=\"0\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Ahci_Host_Cap2>0</Ahci_Host_Cap2>" - + "<Ahci_Host_Caps>40141f05</Ahci_Host_Caps>" - + "<Ahci_Host_Version>10000</Ahci_Host_Version>" - + "<Ahci_Port_Cmd>1000c017</Ahci_Port_Cmd>" - + "<Can_Queue>31</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Em_Message_Supported></Em_Message_Supported>" - + "<Em_Message_Type>0</Em_Message_Type>" - + "<Host_Busy>0</Host_Busy>" - + "<Link_Power_Management_Policy>max_performance</Link_Power_Management_Policy>" - + "<Proc_Name>ahci</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>168</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>1</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010601</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x2922</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>58</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs>58</Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ahci PCI_CLASS=10601 PCI_ID=8086:2922 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:05.0 MODALIAS=pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"1\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Ahci_Host_Cap2>0</Ahci_Host_Cap2>" - + "<Ahci_Host_Caps>40141f05</Ahci_Host_Caps>" - + "<Ahci_Host_Version>10000</Ahci_Host_Version>" - + "<Ahci_Port_Cmd>10004016</Ahci_Port_Cmd>" - + "<Can_Queue>31</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Em_Message_Supported></Em_Message_Supported>" - + "<Em_Message_Type>0</Em_Message_Type>" - + "<Host_Busy>0</Host_Busy>" - + "<Link_Power_Management_Policy>max_performance</Link_Power_Management_Policy>" - + "<Proc_Name>ahci</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>168</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>2</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010601</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x2922</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>58</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs>58</Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ahci PCI_CLASS=10601 PCI_ID=8086:2922 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:05.0 MODALIAS=pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"2\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Ahci_Host_Cap2>0</Ahci_Host_Cap2>" - + "<Ahci_Host_Caps>40141f05</Ahci_Host_Caps>" - + "<Ahci_Host_Version>10000</Ahci_Host_Version>" - + "<Ahci_Port_Cmd>10004016</Ahci_Port_Cmd>" - + "<Can_Queue>31</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Em_Message_Supported></Em_Message_Supported>" - + "<Em_Message_Type>0</Em_Message_Type>" - + "<Host_Busy>0</Host_Busy>" - + "<Link_Power_Management_Policy>max_performance</Link_Power_Management_Policy>" - + "<Proc_Name>ahci</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>168</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>3</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010601</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x2922</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>58</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs>58</Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ahci PCI_CLASS=10601 PCI_ID=8086:2922 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:05.0 MODALIAS=pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"3\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Ahci_Host_Cap2>0</Ahci_Host_Cap2>" - + "<Ahci_Host_Caps>40141f05</Ahci_Host_Caps>" - + "<Ahci_Host_Version>10000</Ahci_Host_Version>" - + "<Ahci_Port_Cmd>10004016</Ahci_Port_Cmd>" - + "<Can_Queue>31</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Em_Message_Supported></Em_Message_Supported>" - + "<Em_Message_Type>0</Em_Message_Type>" - + "<Host_Busy>0</Host_Busy>" - + "<Link_Power_Management_Policy>max_performance</Link_Power_Management_Policy>" - + "<Proc_Name>ahci</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>168</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>4</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010601</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x2922</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>58</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs>58</Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ahci PCI_CLASS=10601 PCI_ID=8086:2922 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:05.0 MODALIAS=pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"4\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Ahci_Host_Cap2>0</Ahci_Host_Cap2>" - + "<Ahci_Host_Caps>40141f05</Ahci_Host_Caps>" - + "<Ahci_Host_Version>10000</Ahci_Host_Version>" - + "<Ahci_Port_Cmd>10004016</Ahci_Port_Cmd>" - + "<Can_Queue>31</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Em_Message_Supported></Em_Message_Supported>" - + "<Em_Message_Type>0</Em_Message_Type>" - + "<Host_Busy>0</Host_Busy>" - + "<Link_Power_Management_Policy>max_performance</Link_Power_Management_Policy>" - + "<Proc_Name>ahci</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>168</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>5</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010601</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x2922</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>58</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs>58</Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ahci PCI_CLASS=10601 PCI_ID=8086:2922 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:05.0 MODALIAS=pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"5\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Ahci_Host_Cap2>0</Ahci_Host_Cap2>" - + "<Ahci_Host_Caps>40141f05</Ahci_Host_Caps>" - + "<Ahci_Host_Version>10000</Ahci_Host_Version>" - + "<Ahci_Port_Cmd>10004016</Ahci_Port_Cmd>" - + "<Can_Queue>31</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Em_Message_Supported></Em_Message_Supported>" - + "<Em_Message_Type>0</Em_Message_Type>" - + "<Host_Busy>0</Host_Busy>" - + "<Link_Power_Management_Policy>max_performance</Link_Power_Management_Policy>" - + "<Proc_Name>ahci</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>168</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>6</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010601</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x2922</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>58</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs>58</Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ahci PCI_CLASS=10601 PCI_ID=8086:2922 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:05.0 MODALIAS=pci:v00008086d00002922sv00001AF4sd00001100bc01sc06i01</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"6\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Can_Queue>1</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Host_Busy>0</Host_Busy>" - + "<Proc_Name>ata_piix</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>128</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>7</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010180</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x7010</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>0</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs></Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ata_piix PCI_CLASS=10180 PCI_ID=8086:7010 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:01.1 MODALIAS=pci:v00008086d00007010sv00001AF4sd00001100bc01sc01i80</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<SCSI_Host Num=\"7\">" - + "<Active_Mode>Initiator</Active_Mode>" - + "<Can_Queue>1</Can_Queue>" - + "<Cmd_Per_Lun>1</Cmd_Per_Lun>" - + "<Host_Busy>0</Host_Busy>" - + "<Proc_Name>ata_piix</Proc_Name>" - + "<Prot_Capabilities>0</Prot_Capabilities>" - + "<Prot_Guard_Type>0</Prot_Guard_Type>" - + "<Sg_Prot_Tablesize>0</Sg_Prot_Tablesize>" - + "<Sg_Tablesize>128</Sg_Tablesize>" - + "<State>running</State>" - + "<Supported_Mode>Initiator</Supported_Mode>" - + "<Uevent></Uevent>" - + "<Unique_Id>8</Unique_Id>" - + "<SysFSDev>" - + "<Broken_Parity_Status>0</Broken_Parity_Status>" - + "<Class>0x010180</Class>" - + "<Consistent_Dma_Mask_Bits>32</Consistent_Dma_Mask_Bits>" - + "<Device>0x7010</Device>" - + "<Dma_Mask_Bits>32</Dma_Mask_Bits>" - + "<Enable>1</Enable>" - + "<Irq>0</Irq>" - + "<Local_Cpulist>0-1</Local_Cpulist>" - + "<Msi_Bus></Msi_Bus>" - + "<Msi_Irqs></Msi_Irqs>" - + "<Numa_Node>-1</Numa_Node>" - + "<Subsystem_Device>0x1100</Subsystem_Device>" - + "<Subsystem_Vendor>0x1af4</Subsystem_Vendor>" - + "<Uevent>DRIVER=ata_piix PCI_CLASS=10180 PCI_ID=8086:7010 PCI_SUBSYS_ID=1AF4:1100 PCI_SLOT_NAME=0000:00:01.1 MODALIAS=pci:v00008086d00007010sv00001AF4sd00001100bc01sc01i80</Uevent>" - + "<Vendor>0x8086</Vendor>" - + "</SysFSDev>" - + "</SCSI_Host>" - + "<ISCSI_Node>" - + "<Initiatorname>iqn.1988-12.com.oracle:3b3f5e2f59cb</Initiatorname>" - + "</ISCSI_Node>" - + "</SCSI>" - + "<IDE>" - + "</IDE>" - + "</IO>" - + "<DMTF>" - + "<SMBIOS Version=\"2.4.0\">" - + "<MaxSize>48</MaxSize>" - + "</SMBIOS>" - + "<DMI Version=\"2.4\">" - + "<TableLength>346</TableLength>" - + "<Items>13</Items>" - + "<Buffer>" - + "ABgAAAECAOgDAAgAAAAAAAAAAAQBAP//Qm9jaHMAQm9jaHMAMDEvMDEvMjAxMQAAARsAAQEC" - + "AAAd1eiR2dDtvYHCppqz0bfqBgAAQm9jaHMAQm9jaHMAAAMUAAMBAQAAAAMDAwIAAAAAAAAA" - + "Qm9jaHMAAAQgAQQBAwECIwYAAP/7iw8AAAAA0AfQB0EB////////Q1BVIDEAQm9jaHMAAAQg" - + "AgQBAwECIwYAAP/7iw8AAAAA0AfQB0EB////////Q1BVIDIAQm9jaHMAABAPABABAwYAAEAA" - + "/v8BAAAAERUAEQAQAwBAAEAAABAJAAEABwAARElNTSAwAAATDwATAAAAAP//NwAAEAEAABMP" - + "ARMAAEAA//9HAAAQAQAAFBMAFAAAAAD//zcAABEAEwEAAAAAFBMBFAAAQAD//0cAABEBEwEA" - + "AAAAIAsAIAAAAAAAAAAAAH8EAH8AAA==" - + "</Buffer>" - + "</DMI>" - + "<BIOS Type=\"0\" Item=\"0\" Handle=\"0x0\">" - + "<Vendor>Bochs</Vendor>" - + "<Version>Bochs</Version>" - + "<ReleaseDate>01/01/2011</ReleaseDate>" - + "</BIOS>" - + "<System Type=\"1\" Item=\"1\" Handle=\"0x100\">" - + "<UUID>1d:d5:e8:91:d9:d0:ed:bd:81:c2:a6:9a:b3:d1:b7:ea</UUID>" - + "<Manufacturer>Bochs</Manufacturer>" - + "<ProductName>Bochs</ProductName>" - + "</System>" - + "<Chassis Type=\"3\" Item=\"2\" Handle=\"0x300\">" - + "<Height>0U</Height>" - + "<Manufacturer>Bochs</Manufacturer>" - + "</Chassis>" - + "</DMTF>" - + "</NodeInformation>" - + "</Discover_Hardware_Result>"; - private final String FSTYPE = "nfs"; - private final String REMOTEHOST = "cs-mgmt"; - private final String REMOTEDIR = "/volumes/cs-data/primary/ovm"; - public String getFsType() { - return FSTYPE; - } - - public String getRemoteHost() { - return REMOTEHOST; - } - - public String getRemoteDir() { - return REMOTEDIR; - } - - public String getRemote() { - return REMOTE; - } - - public String getRepoId() { - return REPOID; - } - - public String getRepoMnt() { - return REPOMNT; - } - public String getVirtualDisksDir() { - return REPOMNT + "/VirtualDisks"; - } - public String getTemplatesDir() { - return REPOMNT + "/Templates"; - } - public String getIsoDir() { - return REPOMNT + "/ISOs"; - } - private final String REMOTE = REMOTEHOST + ":" + REMOTEDIR; - private final String REPOID = "f12842eb-f5ed-3fe7-8da1-eb0e17f5ede8"; - private final String DDREPOID = lin.deDash(REPOID); - private final String REPOMNT = "/OVS/Repositories/" + DDREPOID; - private final String VMMNT = "/nfsmnt/" + REPOID; - private final String DISCOVERFS = "<?xml version=\"1.0\" ?>" - + "<Discover_Mounted_File_Systems_Result>" - + "<Filesystem Type=\"" - + FSTYPE - + "\">" - + "<Mount Dir=\"" - + REPOMNT - + "\">" - + "<Device>" - + REMOTE - + "</Device>" - + "<Mount_Options>rw,relatime,vers=3,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=65535,timeo=600,retrans=2,sec=sys,local_lock=none,addr=192.168.1.61</Mount_Options>" - + "</Mount>" - + "<Mount Dir=\"" - + VMMNT - + "\">" - + "<Device>" - + REMOTE - + "/VirtualMachines</Device>" - + "<Mount_Options>rw,relatime,vers=3,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=65535,timeo=600,retrans=2,sec=sys,local_lock=none,addr=192.168.1.61</Mount_Options>" - + "</Mount>" + "</Filesystem>" - + "</Discover_Mounted_File_Systems_Result>"; - private final String LASTBOOT = "" + "" - + "last_boot_time" - + "1413834408" + "" + "" - + "local_time" + "1414082517" - + "" + ""; - private final String TIMEZONE = "" - + "Europe/Amsterdam" - + "1" + ""; - - @Test - public void testDiscoverServer() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(DISCOVERSERVER)); - results.basicStringTest(lin.getMembershipState(), "Pooled"); - lin.discoverServer(); - results.basicStringTest(lin.getCapabilities(), - "xen-3.0-x86_64 xen-3.0-x86_32p"); - results.basicStringTest(lin.getOvmVersion(), "3.2.1-517"); - results.basicStringTest(lin.getHypervisorVersion(), "4.1.3OVM"); - results.basicStringTest(lin.get("MAX_CONCURRENT_MIGRATION_IN"), "1"); - } - - @Test - public void testGetTimeZone() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(TIMEZONE)); - results.basicBooleanTest(lin.getTimeZone()); - } - - @Test - public void testLastBootTime() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(LASTBOOT)); - results.basicIntTest(lin.getLastBootTime(), 1413834408); - } - - @Test - public void testDiscoverHardware() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(DISCOVERHW)); - lin.discoverHardware(); - results.basicDoubleTest(lin.getMemory(), - Double.valueOf("1048476") * 4096); - results.basicDoubleTest(lin.getFreeMemory(), - Double.valueOf("863459") * 4096); - results.basicStringTest(lin.get("UUID"), - "1d:d5:e8:91:d9:d0:ed:bd:81:c2:a6:9a:b3:d1:b7:ea"); - } - - @Test - public void testDiscoverMountedFileSystems() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(DISCOVERFS)); - lin.discoverMountedFs(FSTYPE); - results.basicBooleanTest( - results.basicListHasString(lin.getFileSystemList(), REPOMNT), - true); - results.basicBooleanTest( - results.basicListHasString(lin.getFileSystemList(), VMMNT), - true); - results.basicBooleanTest( - results.basicListHasString(lin.getFileSystemList(), REMOTE), - false); - results.basicStringTest(lin.getFileSystem(VMMNT, FSTYPE) - .getMountPoint(), VMMNT); - results.basicStringTest(lin.getFileSystem(VMMNT, FSTYPE).getHost(), - REMOTEHOST); - results.basicStringTest(lin.getFileSystem(VMMNT, FSTYPE).getUuid(), - REPOID); - results.basicStringTest(lin.getFileSystem(REPOMNT, FSTYPE).getUuid(), - DDREPOID); - results.basicStringTest(lin.getFileSystem(REPOMNT, FSTYPE) - .getRemoteDir(), REMOTEDIR); - results.basicBooleanTest(lin.getFileSystem(VMMNT, FSTYPE).getDetails() - .containsKey("Uuid"), true); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NetworkTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NetworkTest.java deleted file mode 100644 index effc7c51ab01..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NetworkTest.java +++ /dev/null @@ -1,345 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import org.junit.Test; - -public class NetworkTest { - ConnectionTest con = new ConnectionTest(); - Network net = new Network(con); - XmlTestResultTest results = new XmlTestResultTest(); - - private String IP = "192.168.1.64"; - private String BR = "192.168.1.255"; - private String MAC = "52:54:00:24:47:70"; - private String INT = "xenbr0"; - private String PHY = "bond0"; - private String VLANBR = "bond0"; - public String getBroadcast() { - return BR; - } - - public String getMac() { - return MAC; - } - - public String getInterface() { - return INT; - } - - public String getPhysical() { - return PHY; - } - - public String getVlanBridge() { - return VLANBR; - } - - public String getVlanInterface() { - return VLANINT; - } - - public Integer getVlan() { - return VLAN; - } - - public String getControl() { - return CONTROL; - } - - private String VLANINT = "xenbr0"; - private Integer VLAN = 200; - private String CONTROL = "control0"; - private String CONTROLMAC = "B2:D1:75:69:8C:58"; - private String EMPTY = results.escapeOrNot("" - + "" + ""); - private String DISCOVERNETWORK = results - .escapeOrNot("" - + "" + " " - + " " + " " - + " " - + " 52:54:00:24:47:70" - + " (0x1043) IFF_UP IFF_BROADCAST IFF_RUNNING IFF_MULTICAST" - + " " - + " " - + " Incomplete" - + " 100baseT-FD" - + " " - + " ok" - + " " - + " 00:00:00" - + " 0" - + " 0" - + " " - + " autonegotiation complete " - + " 100baseT-FD 100baseT-HD 10baseT-FD 10baseT-HD" - + " 100baseT-FD 100baseT-HD 10baseT-FD 10baseT-HD" - + " 100baseT-FD 100baseT-HD 10baseT-FD 10baseT-HD" - + " " - + " " - + " disabled" - + " " - + " " - + " INTERFACE=" - + PHY - + "IFINDEX=2" - + " 0" - + " 6" - + " 0x0" - + " " - + " 2" - + " 2" - + " 0x200041a0" - + " 1" - + " 0" - + " 1" - + " 100" - + " full" - + " 0" - + " up" - + " 1500" - + " 0x1103" - + " 1000" - + " 0" - + " " - + " 0x10ec" - + " 0x8139" - + " 0x1af4" - + " 0x1100" - + " 0x020000" - + " " - + " " - + " none" - + " ethernet:c0a80100{192.168.1.0}:MANAGEMENT,CLUSTER_HEARTBEAT,LIVE_MIGRATE,VIRTUAL_MACHINE,STORAGE" - + " " - + " " - + " 52:54:00:26:7F:A0" - + " (0x1843) IFF_UP IFF_BROADCAST IFF_RUNNING IFF_SLAVE IFF_MULTICAST" - + " " - + " " - + " Incomplete" - + " 100baseT-FD" - + " " - + " ok" - + " " - + " 00:00:00" - + " 0" - + " 0" - + " " - + " autonegotiation complete " - + " 100baseT-FD 100baseT-HD 10baseT-FD 10baseT-HD" - + " 100baseT-FD 100baseT-HD 10baseT-FD 10baseT-HD" - + " 100baseT-FD 100baseT-HD 10baseT-FD 10baseT-HD" - + " " - + " " - + " disabled" - + " " - + " " - + " INTERFACE=eth1" - + "IFINDEX=3" - + " 0" - + " 6" - + " 0x0" - + " " - + " 3" - + " 3" - + " 0x200041a0" - + " 1" - + " 0" - + " 1" - + " 100" - + " full" - + " 0" - + " up" - + " 1500" - + " 0x1903" - + " 1000" - + " 0" - + " " - + " 0x10ec" - + " 0x8139" - + " 0x1af4" - + " 0x1100" - + " 0x020000" - + " " - + " " - + " none" - + " " - + " " - + " " - + " " - + " active-backup" - + " eth1 (primary_reselect always)" - + " eth1" - + " up" - + " 250" - + " 500" - + " 500" - + " " - + " up" - + " 100 Mbps" - + " full" - + " 0" - + " 52:54:00:26:7f:a0" - + " " - + " " - + " 52:54:00:26:7F:A0" - + " 1500" - + " " - + " none" - + " " - + " " - + " " - + " " - + " " - + " " - + MAC - + "" - + "
" - + IP - + "
" - + " 255.255.255.0" - + " " - + BR - + "" - + "
" - + " " - + " " - + PHY - + "" - + " " - + " static" - + "
" - + " " - + " " - + " 52:54:00:26:7F:A0" - + " " - + " " - + " bond1" - + " " - + " none" - + " " - + " " - + " \"" - + " " - + CONTROLMAC - + "" - + " " - + " " - + " " - + " none" - + " " - + " " - + " " - + " 52:54:00:26:7F:A0" - + " " - + " " - + " bond1.200" - + " " - + " none" - + " " - + "
" - + " " - + " " - + "
" - + "
" - + "
"); - - public String getDiscoverNetwork() { - return DISCOVERNETWORK; - } - - @Test - public void testDiscoverNetwork() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(net.discoverNetwork(), false); - con.setResult(results.simpleResponseWrapWrapper(DISCOVERNETWORK)); - results.basicBooleanTest(net.discoverNetwork()); - results.basicStringTest(net.getBridgeByIp(IP).getName(), INT); - results.basicStringTest(net.getBridgeByName(INT).getAddress(), IP); - results.basicStringTest(net.getInterfaceByName(CONTROL).getMac(), CONTROLMAC); - net.getBridgeByIp(""); - results.basicBooleanTest(net.getSuccess(), false); - net.getBridgeByName(""); - results.basicBooleanTest(net.getSuccess(), false); - // results.basicStringTest(net.getBridgeByIp("").getName(), INT); - results.basicStringTest(net.getInterfaceByIp(IP).getName(), INT); - results.basicStringTest(net.getInterfaceByName(INT).getAddress(), IP); - results.basicStringTest(net.getInterfaceByName(INT).getBroadcast(), BR); - results.basicStringTest(net.getInterfaceByName(INT).getMac(), MAC); - results.basicStringTest(net.getPhysicalByBridgeName(INT), PHY); - - } - - @Test - public void testInterfacesNotFound() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(net.discoverNetwork(), false); - con.setResult(results.simpleResponseWrapWrapper(DISCOVERNETWORK)); - results.basicBooleanTest(net.discoverNetwork()); - if (net.getInterfaceByName(CONTROL+ "xx") == null) { - System.out.println("yay!"); - }; - } - - @Test(expected = Ovm3ResourceException.class) - public void testLocalBreak() throws Ovm3ResourceException { - con.setResult(results - .errorResponseWrap( - 1, - "exceptions.RuntimeError:Command: ['/etc/xen/scripts/linuxbridge/ovs-local-bridge', 'start', 'bridge=control0'] failed (1): stderr: Start local network: Bridge control0 Is Busy")); - results.basicBooleanTest(net.startOvsLocalConfig(CONTROL), false); - } - - @Test - public void testLocal() throws Ovm3ResourceException { - String resp = "local bridge " + CONTROL; - con.setResult(results.simpleResponseWrap("start " + resp)); - results.basicBooleanTest(net.startOvsLocalConfig(CONTROL)); - con.setResult(results.simpleResponseWrap("stop " + resp)); - results.basicBooleanTest(net.stopOvsLocalConfig(CONTROL)); - } - - @Test(expected = Ovm3ResourceException.class) - public void testVlanBridgeBreak() throws Ovm3ResourceException { - con.setResult(results - .errorResponseWrap( - 1, - "exceptions.RuntimeError:Command: ['/etc/xen/scripts/linuxbridge/ovs-local-bridge', 'start', 'bridge=control0'] failed (1): stderr: Start local network: Bridge control0 Is Busy")); - results.basicBooleanTest(net.startOvsVlanBridge( - VLANINT + "." + VLAN.toString(), VLANBR, VLAN), false); - } - - @Test - public void testVlanBridge() throws Ovm3ResourceException { - String resp = "bridge=" + VLANINT + "." + VLAN.toString() + " netdev=" - + VLANBR + " vlan " + VLAN.toString(); - con.setResult(results.simpleResponseWrap("start " + resp)); - results.basicBooleanTest(net.startOvsVlanBridge( - VLANINT + "." + VLAN.toString(), VLANBR, VLAN)); - con.setResult(results.simpleResponseWrap("stop " + resp)); - results.basicBooleanTest(net.stopOvsVlanBridge( - VLANINT + "." + VLAN.toString(), VLANBR, VLAN)); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NtpTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NtpTest.java deleted file mode 100644 index 3b2629aaa414..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/NtpTest.java +++ /dev/null @@ -1,97 +0,0 @@ -// 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.hypervisor.ovm3.objects; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -public class NtpTest { - ConnectionTest con = new ConnectionTest(); - Ntp nTp = new Ntp(con); - XmlTestResultTest results = new XmlTestResultTest(); - String details = results.simpleResponseWrapWrapper("\n" - + "\n" - + "\n" - + "\n" - + "\n" - + "ovm-1\n" - + "ovm-2\n" - + "\n" - + "\n" - + "\n" - + "1\n" - + "1\n" - + "\n" - + "\n"); - - public void testGetNtp() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(nTp.getDetails()); - } - - @Test - public void testEnableNtp() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(nTp.enableNtp()); - } - @Test - public void testDisableNtp() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(nTp.disableNtp()); - } - - @Test - public void testGetDetails() throws Ovm3ResourceException { - con.setResult(details); - results.basicBooleanTest(nTp.getDetails()); - results.basicBooleanTest(nTp.isRunning()); - results.basicBooleanTest(nTp.isServer()); - } - - @Test - public void testSetNTP() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(nTp.setNtp("ovm-1", true)); - con.setResult(details); - results.basicBooleanTest(nTp.getDetails()); - List ntpHosts = new ArrayList(); - nTp.setServers(ntpHosts); - results.basicBooleanTest(nTp.setNtp(true), false); - } - - @Test - public void testServerAdditionRemoval() throws Ovm3ResourceException { - List ntpHosts = new ArrayList(); - con.setResult(details); - nTp.getDetails(); - ntpHosts = nTp.getServers(); - assertEquals(ntpHosts.size(), 2); - nTp.removeServer("ovm-2"); - ntpHosts = nTp.getServers(); - assertEquals(ntpHosts.size(), 1); - nTp.removeServer("ovm-2"); - ntpHosts = nTp.getServers(); - assertEquals(ntpHosts.size(), 1); - nTp.addServer("ovm-1"); - ntpHosts = nTp.getServers(); - assertEquals(ntpHosts.size(), 1); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2Test.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2Test.java deleted file mode 100644 index 8b48af32801f..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolOCFS2Test.java +++ /dev/null @@ -1,110 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import org.junit.Test; - -public class PoolOCFS2Test { - ConnectionTest con = new ConnectionTest(); - PoolOCFS2 poolfs = new PoolOCFS2(con); - XmlTestResultTest results = new XmlTestResultTest(); - - private String TYPE = "nfs"; - private String UUID = "f12842eb-f5ed-3fe7-8da1-eb0e17f5ede8"; - private String BOGUSUUID = "deadbeef-dead-beef-dead-beef0000002d"; - private String TARGET = "cs-mgmt:/volumes/cs-data/primary/ovm/VirtualMachines"; - private String BASE = "f12842ebf5ed3fe78da1eb0e17f5ede8"; - private String MANAGER = "d1a749d4295041fb99854f52ea4dea97"; - private String CLUSTER = MANAGER.substring(0, 15); - private String VERSION = "3.0"; - private String POOLUUID = "f12842eb-f5ed-3fe7-8da1-eb0e17f5ede8"; - private String EMPTY = results.escapeOrNot("" - + "" - + ""); - private String DISCOVERPOOLFS = results - .escapeOrNot("" - + "" + "" - + "" - + TYPE - + "" - + "" - + TARGET - + "" - + "" - + UUID - + "" - + "" - + BASE - + "" - + "" - + MANAGER - + "" - + "" - + VERSION - + "" - + "" - + POOLUUID - + "" - + "" - + ""); - - @Test - public void testDiscoverPoolFS() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(EMPTY)); - results.basicBooleanTest(poolfs.hasAPoolFs(), false); - results.basicBooleanTest(poolfs.hasPoolFs(BOGUSUUID), false); - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOLFS)); - poolfs.discoverPoolFs(); - results.basicStringTest(poolfs.getPoolFsId(), UUID); - results.basicStringTest(poolfs.getPoolFsManagerUuid(), MANAGER); - results.basicStringTest(poolfs.getPoolFsNFSBaseId(), BASE); - results.basicStringTest(poolfs.getPoolFsTarget(), TARGET); - results.basicStringTest(poolfs.getPoolFsUuid(), UUID); - results.basicStringTest(poolfs.getPoolFsVersion(), VERSION); - results.basicStringTest(poolfs.getPoolPoolFsId(), POOLUUID); - results.basicStringTest(poolfs.getPoolFsType(), TYPE); - results.basicBooleanTest(poolfs.hasAPoolFs()); - results.basicBooleanTest(poolfs.hasPoolFs(UUID)); - } - - @Test - public void testCreatePoolFS() throws Ovm3ResourceException { - con.setResult(results.getNil()); - poolfs.createPoolFs(TYPE, TARGET, CLUSTER, UUID, BASE, MANAGER); - - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOLFS)); - results.basicBooleanTest(poolfs.hasPoolFs(UUID)); - poolfs.createPoolFs(TYPE, TARGET, CLUSTER, UUID, BASE, MANAGER); - } - - @Test - public void testDestroyPoolFS() throws Ovm3ResourceException { - con.setResult(results.getNil()); - poolfs.destroyPoolFs(TYPE, TARGET, UUID, BASE); - - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOLFS)); - results.basicBooleanTest(poolfs.hasPoolFs(UUID)); - poolfs.createPoolFs(TYPE, TARGET, CLUSTER, UUID, BASE, MANAGER); - } - - @Test(expected = Ovm3ResourceException.class) - public void testCreatePoolFSError() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOLFS)); - poolfs.createPoolFs(TYPE, TARGET, CLUSTER, BOGUSUUID, BASE, MANAGER); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolTest.java deleted file mode 100644 index 0f955f1e7d9c..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/PoolTest.java +++ /dev/null @@ -1,180 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -public class PoolTest { - ConnectionTest con = new ConnectionTest(); - Pool pool = new Pool(con); - XmlTestResultTest results = new XmlTestResultTest(); - - private String UUID = "0004fb0000020000ba9aaf00ae5e2d73"; - private String BOGUSUUID = "deadbeefdeadbeefdeadbeefdeadbeef"; - private String VIP = "192.168.1.230"; - private String ALIAS = "Pool 0"; - private String HOST = "ovm-1"; - private String HOST2 = "ovm-2"; - private String IP = "192.168.1.64"; - private String IP2 = "192.168.1.65"; - private String EMPTY = results.escapeOrNot("" - + ""); - private String DISCOVERPOOL = results - .escapeOrNot("" - + "" + " " - + " " - + UUID - + "" - + " " - + ALIAS - + "" - + " " - + VIP - + "" - + " " - + " " - + " " - + IP - + "" - + " " - + " " - + " " - + IP2 - + "" - + " " - + " " - + " " + ""); - - - @Test - public void testDiscoverServerPool() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(EMPTY)); - results.basicBooleanTest(pool.isInAPool(), false); - results.basicBooleanTest(pool.isInPool(UUID), false); - results.basicBooleanTest(pool.discoverServerPool(), false); - results.basicBooleanTest(pool.isInPool(UUID), false); - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOL)); - results.basicBooleanTest(pool.discoverServerPool()); - results.basicBooleanTest(pool.isInAPool(), true); - results.basicBooleanTest(pool.isInPool(UUID), true); - results.basicStringTest(pool.getPoolId(), UUID); - results.basicStringTest(pool.getPoolId(), UUID); - results.basicStringTest(pool.getPoolAlias(), ALIAS); - results.basicStringTest(pool.getPoolPrimaryVip(), VIP); - results.basicBooleanTest(pool.getPoolMemberList().contains(IP)); - results.basicBooleanTest(pool.getPoolMemberList().contains(IP2)); - } - - @Test - public void poolMembers() throws Ovm3ResourceException { - List poolHosts = new ArrayList(); - poolHosts.add(IP); - poolHosts.add(IP2); - con.setResult(results.simpleResponseWrapWrapper(EMPTY)); - results.basicBooleanTest(pool.getPoolMemberList().contains(IP), false); - - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOL)); - results.basicBooleanTest(pool.discoverServerPool()); - con.setResult(results.getNil()); - results.basicBooleanTest(pool.removePoolMember(IP), true); - results.basicBooleanTest(pool.addPoolMember(IP), true); - results.basicBooleanTest(pool.setPoolMemberList(poolHosts), true); - } - - @Test - public void testCreateServerPool() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest( - pool.createServerPool(ALIAS, UUID, VIP, 1, HOST, IP), true); - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOL)); - results.basicBooleanTest(pool.discoverServerPool()); - results.basicBooleanTest( - pool.createServerPool(ALIAS, UUID, VIP, 1, HOST, IP), true); - - } - - @Test(expected = Ovm3ResourceException.class) - public void testCreateServerPoolFail1() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOL)); - results.basicBooleanTest( - pool.createServerPool(ALIAS, BOGUSUUID, VIP, 1, HOST, IP), - false); - } - - @Test(expected = Ovm3ResourceException.class) - public void testCreateServerPoolFail2() throws Ovm3ResourceException { - con.setResult(results.errorResponseWrap(1, - "exceptions.Exception:Repository already exists")); - results.basicBooleanTest( - pool.createServerPool(ALIAS, UUID, VIP, 1, HOST, IP), false); - } - - @Test - public void testJoinServerPool() throws Ovm3ResourceException { - con.setResult(results.getNil()); - Integer poolsize = 2; - results.basicBooleanTest( - pool.joinServerPool(ALIAS, UUID, VIP, poolsize, HOST2, IP2), - true); - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOL)); - results.basicBooleanTest(pool.discoverServerPool()); - results.basicBooleanTest( - pool.joinServerPool(ALIAS, UUID, VIP, poolsize, HOST2, IP2), - true); - } - @Test(expected = Ovm3ResourceException.class) - public void testJoinServerPoolFail1() throws Ovm3ResourceException { - Integer poolsize = 2; - con.setResult(results.simpleResponseWrapWrapper(DISCOVERPOOL)); - results.basicBooleanTest(pool.joinServerPool(ALIAS, BOGUSUUID, VIP, - poolsize, HOST2, IP2), false); - } - - @Test(expected = Ovm3ResourceException.class) - public void testJoinServerPoolFail() throws Ovm3ResourceException { - con.setResult(results - .errorResponseWrap(1, - "exceptions.Exception:Server already a member of pool: " - + UUID)); - Integer poolsize = 2; - results.basicBooleanTest(pool.joinServerPool(ALIAS, UUID, VIP, poolsize, - HOST2, IP2), false); - } - - @Test - public void testValidPoolRoles() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(pool.setServerRoles(pool.getValidRoles()), - true); - - } - - @Test(expected = Ovm3ResourceException.class) - public void testValidPoolRolesInvalid() throws Ovm3ResourceException { - String broken = "broken_token"; - con.setResult(results - .errorResponseWrap(1, - "exceptions.Exception:Invalid roles: set(['xen', '" + broken - + "', 'utility'])")); - results.basicBooleanTest(pool.setServerRoles(pool.getValidRoles()), - false); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RemoteTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RemoteTest.java deleted file mode 100644 index db811735d952..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RemoteTest.java +++ /dev/null @@ -1,36 +0,0 @@ -// 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.hypervisor.ovm3.objects; -import org.junit.Test; - -public class RemoteTest { - ConnectionTest con = new ConnectionTest(); - Remote rEm = new Remote(con); - XmlTestResultTest results = new XmlTestResultTest(); - - @Test - public void TestSysShutdown() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(rEm.sysShutdown()); - } - @Test - public void TestSysReboot() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(rEm.sysReboot()); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RepositoryTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RepositoryTest.java deleted file mode 100644 index 54e1ebd53595..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/RepositoryTest.java +++ /dev/null @@ -1,182 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import org.junit.Test; - -public class RepositoryTest { - ConnectionTest con = new ConnectionTest(); - Repository repo = new Repository(con); - XmlTestResultTest results = new XmlTestResultTest(); - - private String REPOID = "f12842ebf5ed3fe78da1eb0e17f5ede8"; - private String MGRID = "d1a749d4295041fb99854f52ea4dea97"; - private String REPOALIAS = "OVS Repository"; - private String REMOTENFS = "cs-mgmt:/volumes/cs-data/primary/ovm"; - private String LOCALMOUNT = "/OVS/Repositories/f12842ebf5ed3fe78da1eb0e17f5ede8"; - private String REPOVERSION = "3.0"; - private String REPOSTATUS = "Mounted"; - private String ISO = "systemvm.iso"; - private String TEMPLATE = "0b53acb1-6554-41b8-b1e1-7b27a01b6acb"; - private String DISK = "cfb5ee12-b99d-41d1-a5b2-44dea36c9de1.raw"; - private String VM = "7efbdbe0-3d01-3b22-a8a0-1d41c6f2502f"; - private String REPODISCOVERXML = "" - + "<?xml version=\"1.0\" ?>" - + "<Discover_Repositories_Result>" + "<RepositoryList>" - + "<Repository Name=\"" - + REPOID - + "\">" - + "<Version>" - + REPOVERSION - + "</Version>" - + "<Manager_UUID>" - + MGRID - + "</Manager_UUID>" - + "<Repository_UUID>" - + REPOID - + "</Repository_UUID>" - + "<Repository_Alias>" - + REPOALIAS - + "</Repository_Alias>" - + "<Assemblies/>" - + "<Templates>" - + "<Template Name=\"" - + TEMPLATE - + "\">" - + "<File>" - + TEMPLATE - + ".raw</File>" - + "</Template>" - + "<Template Name=\"7d5c29db-6343-4431-b509-9646b45cc31b\">" - + "<File>7d5c29db-6343-4431-b509-9646b45cc31b.raw</File>" - + "</Template>" - + "</Templates>" - + "<VirtualMachines>" - + "<VirtualMachine Name=\"" - + VM - + "\">" - + "<File>vm.cfg</File>" - + "</VirtualMachine>" - + "<VirtualMachine Name=\"pool\">" - + "<File>ovspoolfs.img</File>" - + "</VirtualMachine>" - + "<VirtualMachine Name=\"4fb50e31-b032-3012-b70b-7e27c2acdfe2\">" - + "<File>vm.cfg</File>" - + "</VirtualMachine>" - + "<VirtualMachine Name=\"5ffe3ddc-606d-3fec-a956-67638f7ba838\">" - + "<File>vm.cfg</File>" - + "</VirtualMachine>" - + "<VirtualMachine Name=\"14fc3846-45e5-3c08-ad23-432ceb07407b\">" - + "<File>vm.cfg</File>" - + "</VirtualMachine>" - + "</VirtualMachines>" - + "<VirtualDisks>" - + "<Disk>" - + DISK - + "</Disk>" - + "<Disk>b92dd5c5-0f24-4cca-b86a-153ac6e950a8.raw</Disk>" - + "<Disk>d144c278-0825-41d5-b9c6-8bb21f3dd1e7.raw</Disk>" - + "<Disk>99650d9f-c7ee-42df-92e3-6cafc0876141.raw</Disk>" - + "</VirtualDisks>" - + "<ISOs>" - + "<ISO>" - + ISO - + "</ISO>" - + "</ISOs>" - + "</Repository>" - + "</RepositoryList>" - + "</Discover_Repositories_Result>" + ""; - private String REPODBDISCOVERXML = "" - + "<?xml version=\"1.0\" ?>" - + "<Discover_Repository_Db_Result>" - + "<RepositoryDbList>" + "<Repository Uuid=\"" - + REPOID - + "\">" - + "<Fs_location>" - + REMOTENFS - + "</Fs_location>" - + "<Mount_point>" - + LOCALMOUNT - + "</Mount_point>" - + "<Filesystem_type>nfs</Filesystem_type>" - + "<Version>" - + REPOVERSION - + "</Version>" - + "<Alias>" - + REPOALIAS - + "</Alias>" - + "<Manager_uuid>" - + MGRID - + "</Manager_uuid>" - + "<Status>" - + REPOSTATUS - + "</Status>" - + "</Repository>" - + "</RepositoryDbList>" - + "</Discover_Repository_Db_Result>" + ""; - - /* - * @Test Create a test repo that mimics the above so we can test against a - * live box... public void testCreateRepo() throws Ovm3ResourceException { - * con.setResult(null); repo.createRepo(REMOTENFS, LOCALMOUNT, REPOID, - * REPOALIAS); } - */ - @Test - public void testDiscoverRepoBase() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(this.REPODISCOVERXML)); - repo.discoverRepo(REPOID); - results.basicStringTest(repo.getRepo(REPOID).getUuid(), REPOID); - results.basicStringTest(repo.getRepo(REPOID).getAlias(), REPOALIAS); - results.basicStringTest(repo.getRepo(REPOID).getVersion(), REPOVERSION); - results.basicStringTest(repo.getRepo(REPOID).getManagerUuid(), MGRID); - } - - @Test - public void testDiscoverRepoDetails() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(this.REPODISCOVERXML)); - repo.discoverRepo(REPOID); - results.basicBooleanTest(results.basicListHasString(repo - .getRepo(REPOID).getRepoVirtualDisks(), DISK), true); - results.basicBooleanTest(results.basicListHasString(repo - .getRepo(REPOID).getRepoVirtualMachines(), VM), true); - results.basicBooleanTest(results.basicListHasString(repo - .getRepo(REPOID).getRepoTemplates(), TEMPLATE + ".raw"), true); - results.basicBooleanTest(results.basicListHasString(repo - .getRepo(REPOID).getRepoISOs(), ISO), true); - results.basicBooleanTest(results.basicListHasString(repo - .getRepo(REPOID).getRepoISOs(), VM), false); - } - - @Test - public void testDiscoverRepoDb() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(this.REPODBDISCOVERXML)); - repo.discoverRepoDb(); - results.basicStringTest(repo.getRepoDb(REPOID).getUuid(), REPOID); - results.basicStringTest(repo.getRepoDb(REPOID).getAlias(), REPOALIAS); - results.basicStringTest(repo.getRepoDb(REPOID).getVersion(), - REPOVERSION); - results.basicStringTest(repo.getRepoDb(REPOID).getManagerUuid(), MGRID); - results.basicStringTest(repo.getRepoDb(REPOID).getMountPoint(), - LOCALMOUNT); - results.basicStringTest(repo.getRepoDb(REPOID).getFsLocation(), - REMOTENFS); - results.basicStringTest(repo.getRepoDb(REPOID).getStatus(), REPOSTATUS); - results.basicStringTest(repo.getRepoDb(REPOID).getFilesystemType(), - "nfs"); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/StoragePluginTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/StoragePluginTest.java deleted file mode 100644 index d0194db25f43..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/StoragePluginTest.java +++ /dev/null @@ -1,356 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import com.cloud.hypervisor.ovm3.objects.StoragePlugin.FileProperties; -import com.cloud.hypervisor.ovm3.objects.StoragePlugin.StorageDetails; - -public class StoragePluginTest { - ConnectionTest con = new ConnectionTest(); - StoragePlugin sPt = new StoragePlugin(con); - XmlTestResultTest results = new XmlTestResultTest(); - String NFSHOST = "nfs-store-1"; - String NFSPATH = "/volumes/cs-data/primary"; - String NFSMNT = "/nfsmnt"; - String FSPROPUUID = sPt.deDash(sPt.newUuid()); - String FSMNTUUID = sPt.newUuid(); - String POOLUUID = sPt.deDash(FSMNTUUID); - String FILE = "a.file"; - Long SIZE = 2096898048L; - String STORAGEPLUGINXML = "" - + "<?xml version=\"1.0\" ?>" - + "<Discover_Storage_Plugins_Result>" - + "<storage_plugin_info_list>" - + "<storage_plugin_info plugin_impl_name=\"oracle.ocfs2.OCFS2.OCFS2Plugin\">" - + "<fs_api_version>1,2,7</fs_api_version>" - + "<generic_plugin>False</generic_plugin>" - + "<plugin_version>0.1.0-38</plugin_version>" - + "<filesys_type>LocalFS</filesys_type>" - + "<extended_api_version>None</extended_api_version>" - + "<plugin_desc>Oracle OCFS2 File system Storage Connect Plugin</plugin_desc>" - + "<cluster_required>True</cluster_required>" - + "<plugin_name>Oracle OCFS2 File system</plugin_name>" - + "<fs_extra_info_help>None</fs_extra_info_help>" - + "<required_api_vers>1,2,7</required_api_vers>" - + "<file_extra_info_help>None</file_extra_info_help>" - + "<ss_extra_info_help>None</ss_extra_info_help>" - + "<filesys_name>ocfs2</filesys_name>" - + "<vendor_name>Oracle</vendor_name>" - + "<plugin_type>ifs</plugin_type>" - + "<abilities>" - + "<resize_is_sync>YES</resize_is_sync>" - + "<clone_is_sync>YES</clone_is_sync>" - + "<access_control>NO</access_control>" - + "<custom_clone_name>YES</custom_clone_name>" - + "<require_storage_name>NO</require_storage_name>" - + "<backing_device_type>DEVICE_SINGLE</backing_device_type>" - + "<splitclone_while_open>NO</splitclone_while_open>" - + "<custom_snap_name>YES</custom_snap_name>" - + "<snapshot>ONLINE</snapshot>" - + "<splitclone>UNSUPPORTED</splitclone>" - + "<snap_is_sync>YES</snap_is_sync>" - + "<snapclone>ONLINE</snapclone>" - + "<splitclone_is_sync>NO</splitclone_is_sync>" - + "<clone>ONLINE</clone>" - + "<resize>ONLINE</resize>" - + "<snapclone_is_sync>YES</snapclone_is_sync>" - + "</abilities>" - + "</storage_plugin_info>" - + "<storage_plugin_info plugin_impl_name=\"oracle.generic.SCSIPlugin.GenericPlugin\">" - + "<storage_types>SAN,iSCSI</storage_types>" - + "<generic_plugin>True</generic_plugin>" - + "<plugin_version>1.1.0</plugin_version>" - + "<extended_api_version>1,2,9</extended_api_version>" - + "<plugin_desc>Oracle Storage Connect Plugin for Generic FC and iSCSI</plugin_desc>" - + "<plugin_name>Oracle Generic SCSI Plugin</plugin_name>" - + "<sa_api_version>1,2,7</sa_api_version>" - + "<required_api_vers>1,2,7</required_api_vers>" - + "<ss_extra_info_help>None</ss_extra_info_help>" - + "<se_extra_info_help>None</se_extra_info_help>" - + "<vendor_name>Oracle</vendor_name>" - + "<plugin_type>isa</plugin_type>" - + "<abilities>" - + "<resize_is_sync>UNSUPPORTED</resize_is_sync>" - + "<clone_is_sync>UNSUPPORTED</clone_is_sync>" - + "<access_control>NO</access_control>" - + "<custom_clone_name>UNSUPPORTED</custom_clone_name>" - + "<require_storage_name>UNSUPPORTED</require_storage_name>" - + "<custom_snap_name>UNSUPPORTED</custom_snap_name>" - + "<snapshot>UNSUPPORTED</snapshot>" - + "<splitclone>UNSUPPORTED</splitclone>" - + "<snap_is_sync>UNSUPPORTED</snap_is_sync>" - + "<snapclone>UNSUPPORTED</snapclone>" - + "<splitclone_is_sync>UNSUPPORTED</splitclone_is_sync>" - + "<clone>UNSUPPORTED</clone>" - + "<resize>UNSUPPORTED</resize>" - + "<snapclone_is_sync>UNSUPPORTED</snapclone_is_sync>" - + "</abilities>" - + "</storage_plugin_info>" - + "<storage_plugin_info plugin_impl_name=\"oracle.generic.NFSPlugin.GenericNFSPlugin\">" - + "<fs_api_version>1,2,7</fs_api_version>" - + "<generic_plugin>True</generic_plugin>" - + "<plugin_version>1.1.0</plugin_version>" - + "<filesys_type>NetworkFS</filesys_type>" - + "<extended_api_version>None</extended_api_version>" - + "<plugin_desc>Oracle Generic Network File System Storage Connect Plugin</plugin_desc>" - + "<cluster_required>False</cluster_required>" - + "<plugin_name>Oracle Generic Network File System</plugin_name>" - + "<fs_extra_info_help>None</fs_extra_info_help>" - + "<required_api_vers>1,2,7</required_api_vers>" - + "<file_extra_info_help>None</file_extra_info_help>" - + "<ss_extra_info_help>None</ss_extra_info_help>" - + "<filesys_name>NFS</filesys_name>" - + "<vendor_name>Oracle</vendor_name>" - + "<plugin_type>ifs</plugin_type>" - + "<abilities>" - + "<resize_is_sync>UNSUPPORTED</resize_is_sync>" - + "<clone_is_sync>UNSUPPORTED</clone_is_sync>" - + "<access_control>NO</access_control>" - + "<custom_clone_name>UNSUPPORTED</custom_clone_name>" - + "<require_storage_name>NO</require_storage_name>" - + "<backing_device_type>UNSUPPORTED</backing_device_type>" - + "<splitclone_while_open>UNSUPPORTED</splitclone_while_open>" - + "<custom_snap_name>UNSUPPORTED</custom_snap_name>" - + "<snapshot>UNSUPPORTED</snapshot>" - + "<splitclone>UNSUPPORTED</splitclone>" - + "<snap_is_sync>UNSUPPORTED</snap_is_sync>" - + "<snapclone>UNSUPPORTED</snapclone>" - + "<splitclone_is_sync>UNSUPPORTED</splitclone_is_sync>" - + "<clone>UNSUPPORTED</clone>" - + "<resize>UNSUPPORTED</resize>" - + "<snapclone_is_sync>UNSUPPORTED</snapclone_is_sync>" - + "</abilities>" + "</storage_plugin_info>" - + "</storage_plugin_info_list>" - + "</Discover_Storage_Plugins_Result>" + ""; - String NFSMOUNTRESPONSEXML = "" + "" - + "status" + "" - + "" + "" + "uuid" - + "" - + FSPROPUUID - + "" - + "" - + "" - + "ss_uuid" - + "" - + FSMNTUUID - + "" - + "" - + "" - + "size" - + "263166853120" - + "" - + "" - + "free_sz" - + "259377299456" - + "" - + "" - + "state" - + "1" - + "" - + "" - + "mount_options" - + "" - + "" - + "" - + "" - + "access_grp_names" - + "" - + "" - + "" - + "" - + "access_path" - + "" - + NFSHOST - + ":" - + NFSPATH - + "" - + "" - + "" - + "name" - + "nfs:" - + NFSPATH - + "" + "" + ""; - public String getNfsMountResponseXml() { - return NFSMOUNTRESPONSEXML; - } - - public String getNfsFileSystemInfo() { - return NFSFILESYSTEMINFO; - } - public String getFileCreateXml() { - return FILECREATEXML; - } - public Long getFileSize() { - return SIZE; - } - public String getPoolUuid() { - return POOLUUID; - } - public String getFileName() { - return FILE; - } - String NFSFILESYSTEMINFO = NFSMOUNTRESPONSEXML; - String FILECREATEXML = "" + "" + "fr_type" - + "File" + "" + "" - + "ondisk_sz" + "0" - + "" + "" + "fs_uuid" - + "" + FSMNTUUID + "" + "" - + "" + "file_path" - + "/OVS/Repositories/" + POOLUUID + "/VirtualDisks/" - + FILE + "" + "" + "" - + "file_sz" + "" + SIZE - + "" + "" + ""; - - @Test - public void testNFSStorageMountCreation() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(NFSMOUNTRESPONSEXML)); - StorageDetails sd = sPt.storagePluginMountNFS(NFSHOST, NFSPATH, - FSMNTUUID, NFSMNT); - con.setResult(results.simpleResponseWrapWrapper(NFSMOUNTRESPONSEXML)); - NFSMNT = NFSMNT + "/" + FSMNTUUID; - sd = sPt.storagePluginMountNFS(NFSHOST, NFSPATH, FSMNTUUID, NFSMNT); - results.basicLongTest(Long.valueOf(sd.getSize()), 263166853120L); - results.basicLongTest(Long.valueOf(sd.getFreeSize()), 259377299456L); - results.basicStringTest(sd.getName(), "nfs:" + NFSPATH); - results.basicStringTest(sd.getUuid(), FSPROPUUID); - results.basicStringTest(sd.getDetailsRelationalUuid(),FSMNTUUID); - } - - @Test - public void testNFSStorageUnmount() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(sPt.storagePluginUnmountNFS(NFSHOST, NFSPATH, FSMNTUUID, NFSMNT)); - } - - @Test(expected = Ovm3ResourceException.class) - public void testStoragePluginIncorrectSsUuid() throws Ovm3ResourceException { - sPt.getStorageDetails().setDetailsRelationalUuid(FSMNTUUID); - } - - @Test(expected = Ovm3ResourceException.class) - public void testStoragePluginIncorrectMntUuid() - throws Ovm3ResourceException { - sPt.getStorageDetails().setUuid(FSPROPUUID); - } - - @Test(expected = Ovm3ResourceException.class) - public void testStoragePluginIncorrectUuid() throws Ovm3ResourceException { - sPt.getStorageServer().setUuid(FSMNTUUID); - } - - @Test(expected = Ovm3ResourceException.class) - public void testStoragePluginNFSmountInvalidUuid() - throws Ovm3ResourceException { - NFSMOUNTRESPONSEXML = NFSMOUNTRESPONSEXML.replaceAll(FSPROPUUID, - sPt.deDash(FSMNTUUID)); - con.setResult(results.simpleResponseWrapWrapper(NFSMOUNTRESPONSEXML)); - assertNotNull(sPt.storagePluginMountNFS(NFSHOST, NFSPATH, - FSPROPUUID, NFSMNT)); - } - - @Test - public void testStorageFileCreation() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(FILECREATEXML)); - FileProperties file = sPt.storagePluginCreate(FSMNTUUID, NFSHOST, FILE, - SIZE, false); - file.getOnDiskSize(); - } - - @Test(expected = Ovm3ResourceException.class) - public void testStorageFileCreationFileExistS() - throws Ovm3ResourceException { - con.setResult(results - .errorResponseWrap("exceptions OSError:[Errno.17] File exists " - + FILE)); - FileProperties file = sPt.storagePluginCreate(FSMNTUUID, NFSHOST, FILE, - SIZE, false); - file.getSize(); - } - - @Test - public void testStorageFileInfo() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(FILECREATEXML)); - FileProperties file = sPt.storagePluginGetFileInfo(FSMNTUUID, NFSHOST, - FILE); - file.getName(); - file.getUuid(); - file.getType(); - file.getSize(); - } - - @Test - public void testDiscoverStoragePlugins() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(STORAGEPLUGINXML)); - for (String plugin : sPt.discoverStoragePlugins()) { - sPt.checkStoragePluginProperties(plugin, "plugin_version"); - sPt.checkStoragePluginAbility(plugin, "snapshot"); - } - } - - @Test(expected = Ovm3ResourceException.class) - public void testCheckStoragePluginBogusPlugin() - throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(STORAGEPLUGINXML)); - sPt.checkStoragePluginProperties("bogus", "plugin_version"); - } - - @Test(expected = Ovm3ResourceException.class) - public void testCheckStoragePluginBogusProperty() - throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(STORAGEPLUGINXML)); - sPt.checkStoragePluginAbility(sPt.getPluginType(), "blabla"); - } - - @Test - public void testMounts() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(NFSMOUNTRESPONSEXML)); - sPt.storagePluginListFs(NFSHOST); - } - - @Test - public void testGetFileSystemInfo() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(NFSMOUNTRESPONSEXML)); - sPt.storagePluginGetFileSystemInfo(FSPROPUUID, FSMNTUUID, NFSHOST, - NFSPATH); - } - - @Test - public void testStoragepluginDestroy() throws Ovm3ResourceException { - con.setResult(results.getNil()); - sPt.storagePluginDestroy(FSMNTUUID, FILE); - } - - @Test(expected = Ovm3ResourceException.class) - public void testStoragepluginDestroyWrongUUID() - throws Ovm3ResourceException { - con.setResult(results.getNil()); - sPt.storagePluginDestroy(FSPROPUUID, FILE); - } - - @Test - public void testStoragePluginSwitch() throws Ovm3ResourceException { - con.setResult(results.simpleResponseWrapWrapper(STORAGEPLUGINXML)); - sPt.setISCSI(); - sPt.setNFS(); - sPt.setOCFS2(); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XenTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XenTest.java deleted file mode 100644 index 34f67df2d25a..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XenTest.java +++ /dev/null @@ -1,781 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import com.cloud.utils.UuidUtils; -import org.junit.Test; - -public class XenTest { - public XenTest() { - } - ConnectionTest con = new ConnectionTest(); - Xen xEn = new Xen(con); - XmlTestResultTest results = new XmlTestResultTest(); - String DOM0VMNAME = "Domain-0"; - String VMNAME = "i-2-3-VM"; - String VMROOTDISKNAME = "ROOT-3"; - public String getVMNAME() { - return VMNAME; - } - String REPOID = "f12842ebf5ed3fe78da1eb0e17f5ede8"; - public String getRepoId() { - return REPOID; - } - public String getVmId() { - return VMID; - } - String VMNICMAC = "02:00:50:9a:00:01"; - public String getVmNicMac() { - return VMNICMAC; - } - public String getVmNicBridge() { - return VMNICBR; - } - public String getVmNicUuid() { - return VMNICUUID; - } - String VMNICBR = "xenbr0.160"; - String VMNICUUID = "2ad52371-af7d-32d1-ebe1-2b6a811e66c4"; - String VMID = "868a6627-c3b0-3d9b-aea4-f279cbaa253b"; - String VMROOTDISKUUID = "722eb520-dcf5-4113-8f45-22d67c9a2f3c"; - public String getVmRootDiskUuid() { - return VMROOTDISKUUID; - } - public String getVmRootDiskName() { - return VMROOTDISKNAME; - } - String VMROOTDISK = VMROOTDISKUUID + ".raw"; - String VMISO = "xentools.iso"; - String REPOPATH = "/OVS/Repositories"; - String VMROOTDISKPATH = REPOPATH + "/" + REPOID + "/Disks/" + VMROOTDISK; - String VMISOPATH = REPOPATH + "/" + REPOID + "/ISOs/" + VMISO; - String MULTIPLEVMSLISTXML = results - .simpleResponseWrapWrapper(new StringBuilder("\n") - .append("\n\non_xend_stop\nignore\n\n\nfeatures\n\n\n\nimage\n") - .append("\n\ntsc_mode\n\n\n\n\nkernel\n\n\n\nsuperpages\n") - .append("\n\n\n\nnomigrate\n\n\n\n\nexpose_host_uuid\n\n\n\n") - .append("\n\n\ncpus\n\n\n\n\n\n\n\n\n") - .append("\n\n\n\n\n\n\n\n\n\n\n") - .append("\n\n\n10\n11\n12\n13\n") - .append("14\n15\n16\n17\n18\n") - .append("19\n20\n21\n22\n23\n") - .append("24\n25\n26\n27\n28\n") - .append("29\n30\n31\n32\n33\n") - .append("34\n35\n36\n37\n38\n") - .append("39\n40\n41\n42\n43\n") - .append("44\n45\n46\n47\n48\n") - .append("49\n50\n51\n52\n53\n") - .append("54\n55\n56\n57\n58\n") - .append("59\n60\n61\n62\n63\n") - .append("64\n65\n66\n67\n68\n") - .append("69\n70\n71\n72\n73\n") - .append("74\n75\n76\n77\n78\n") - .append("79\n80\n81\n82\n83\n") - .append("84\n85\n86\n87\n88\n") - .append("89\n90\n91\n92\n93\n") - .append("94\n95\n96\n97\n98\n") - .append("99\n100\n101\n102\n103\n") - .append("104\n105\n106\n107\n108\n") - .append("109\n110\n111\n112\n113\n") - .append("114\n115\n116\n117\n118\n") - .append("119\n120\n121\n122\n123\n") - .append("124\n125\n126\n127\n128\n") - .append("129\n130\n131\n132\n133\n") - .append("134\n135\n136\n137\n138\n") - .append("139\n140\n141\n142\n143\n") - .append("144\n145\n146\n147\n148\n") - .append("149\n150\n151\n152\n153\n") - .append("154\n155\n156\n157\n158\n") - .append("159\n\n\n\n\n\n\n\n\n") - .append("\n\n\n\n\n\n\n\n\n\n") - .append("\n\n\n\n10\n11\n12\n") - .append("13\n14\n15\n16\n17\n") - .append("18\n19\n20\n21\n22\n") - .append("23\n24\n25\n26\n27\n") - .append("28\n29\n30\n31\n32\n") - .append("33\n34\n35\n36\n37\n") - .append("38\n39\n40\n41\n42\n") - .append("43\n44\n45\n46\n47\n") - .append("48\n49\n50\n51\n52\n") - .append("53\n54\n55\n56\n57\n") - .append("58\n59\n60\n61\n62\n") - .append("63\n64\n65\n66\n67\n") - .append("68\n69\n70\n71\n72\n") - .append("73\n74\n75\n76\n77\n") - .append("78\n79\n80\n81\n82\n") - .append("83\n84\n85\n86\n87\n") - .append("88\n89\n90\n91\n92\n") - .append("93\n94\n95\n96\n97\n") - .append("98\n99\n100\n101\n102\n") - .append("103\n104\n105\n106\n107\n") - .append("108\n109\n110\n111\n112\n") - .append("113\n114\n115\n116\n117\n") - .append("118\n119\n120\n121\n122\n") - .append("123\n124\n125\n126\n127\n") - .append("128\n129\n130\n131\n132\n") - .append("133\n134\n135\n136\n137\n") - .append("138\n139\n140\n141\n142\n") - .append("143\n144\n145\n146\n147\n") - .append("148\n149\n150\n151\n152\n") - .append("153\n154\n155\n156\n157\n") - .append("158\n159\n\n\n\n\nuuid\n00000000-0000-0000-0000-000000000000\n") - .append("\n\non_reboot\nrestart\n\n\nstate\nr-----\n\n") - .append("\ncpu_weight\n65535\n\n\nonline_vcpus\n\n\n\n") - .append("\nmemory\n672\n\n\ncpu_cap\n\n\n\n\nstatus\n") - .append("\n\n\n\npool_name\nPool-0\n\n\non_poweroff\ndestroy\n") - .append("\n\non_xend_start\nignore\n\n\non_crash\nrestart\n\n") - .append("\ndevice\n\n\n\n\nbootloader\n\n\n\nmaxmem\n") - .append("672\n\n\ncpu_time\n6608.51291287\n\n\nshadow_memory\n\n") - .append("\n\n\nname\nDomain-0\n\n\nbuilder\nlinux\n\n") - .append("\nbootloader_args\n\n\n\ndomid\n\n\n\n\nvcpus\n") - .append("\n\n\n\n\n\non_xend_stop\nignore\n\n\n") - .append("console_mfn\n873706\n\n\nfeatures\n\n\n\nimage\n") - .append("\n\ntsc_mode\n\n\n\n\nkernel\n\n\n") - .append("\nvideoram\n\n\n\n\ndevice_model\n/usr/lib/xen/bin/qemu-dm\n\n") - .append("\nnotesHV_START_LOW4118806528") - .append("FEATURES!writable_page_tables|pae_pgdir_above_4gb") - .append("VIRT_BASE3221225472GUEST_VERSION2.6") - .append("PADDR_OFFSETGUEST_OS") - .append("linuxHYPERCALL_PAGE3238010880") - .append("LOADERgenericSUSPEND_CANCEL") - .append("PAE_MODEyesENTRY") - .append("3242303488XEN_VERSIONxen-3.0") - .append("expose_host_uuidpci") - .append("superpages\n\n\n\n\nnomigrate\n\n\n\n\n\n") - .append("\ncpus\n\n\n\n\n\n\nstore_mfn\n873707\n") - .append("\n\nuuid\n").append(VMID).append("\n\n\non_reboot\nrestart\n\n") - .append("\nstate\n-b----\n\n\ncpu_weight\n27500\n\n\nonline_vcpus\n") - .append("\n\n\n\nmemory\n512\n\n\ncpu_cap\n\n\n") - .append("\n\nstatus\n\n\n\n\npool_name\nPool-0\n\n\ndescription\n") - .append("\n\n\nstart_time\n1408105444.17\n\n\non_poweroff\ndestroy\n") - .append("\n\non_xend_start\nignore\n\n\non_crash\nrestart\n\n") - .append("\ndevice\n\n\nvif\n\n\n\nbridge\n").append(VMNICBR) - .append("\n\n\nmac\n").append(VMNICMAC).append("\n\n\nscript\n/etc/xen/scripts/vif-bridge\n") - .append("\n\nuuid\n").append(VMNICUUID).append("\n\n\nbackend\n\n\n\n") - .append("\n\n\n\nvkbd\n\n\n\nbackend\n\n\n") - .append("\n\n\n\n\nconsole\n\n\n\nprotocol\nvt100\n") - .append("\n\nlocation\n\n\n\n\nuuid\n9beb5016-dde7-8526-491f-e972f262a634\n") - .append("\n\n\n\n\nvfb\n\n\n\nvncunused\n\n") - .append("\n\n\nvnc\n\n\n\n\nxauthority\n/root/.Xauthority\n") - .append("\n\nvnclisten\n0.0.0.0\n\n\nvncpasswd\n7693f834ca67912e\n") - .append("\n\nkeymap\nen-us\n\n\nlocation\n0.0.0.0:5900\n\n") - .append("\nuuid\n78edf954-e375-b142-9c76-791ce805b6ef\n\n\n\n\n\nvbd\n") - .append("\n\n\nprotocol\nx86_32-abi\n\n\nuuid\nbda35954-2596-025e-168c-b82e1cf92369\n") - .append("\n\nbootable\n\n\n\n\ndev\nxvda:disk\n\n\nuname\n") - .append("file:/OVS/Repositories/").append(REPOID).append("/VirtualDisks/").append(VMROOTDISK).append("\n\n\nmode\n\n") - .append("\n\n\nVDI\n\n\n\nbackend\n\n\n\n\n") - .append("\n\n\n\n\nbootloader\n/usr/bin/pygrub\n\n\nmaxmem\n") - .append("512\n\n\ncpu_time\n0.152510481\n\n\nshadow_memory\n\n") - .append("\n\n\nname\n").append(VMNAME).append("\n\n\nbuilder\nlinux\n") - .append("\n\nbootloader_args\n-q\n\n\ndomid\n\n\n\n\n") - .append("vcpus\n\n\n\n\n").toString()); - - public String getSingleVmListXML() { - return SINGLEVMLISTXML; - } - String SINGLEVMLISTXML = results - .simpleResponseWrapWrapper(new StringBuilder("") - .append("") - .append("on_xend_stop") - .append("ignore") - .append("") - .append("") - .append("console_mfn") - .append("873706") - .append("") - .append("") - .append("features") - .append("") - .append("") - .append("") - .append("image") - .append("") - .append("") - .append("tsc_mode") - .append("") - .append("") - .append("") - .append("") - .append("kernel") - .append("") - .append("") - .append("") - .append("videoram") - .append("") - .append("") - .append("") - .append("") - .append("device_model") - .append("/usr/lib/xen/bin/qemu-dm") - .append("") - .append("") - .append("notes") - .append("") - .append("") - .append("HV_START_LOW") - .append("4118806528") - .append("") - .append("") - .append("FEATURES") - .append("!writable_page_tables|pae_pgdir_above_4gb") - .append("") .append("") - .append("VIRT_BASE") - .append("3221225472") - .append("") .append("") - .append("GUEST_VERSION") - .append("2.6") - .append("") .append("") - .append("PADDR_OFFSET") - .append("") .append("") - .append("") .append("") - .append("GUEST_OS") - .append("linux") - .append("") .append("") - .append("HYPERCALL_PAGE") - .append("3238010880") - .append("") .append("") - .append("LOADER") - .append("generic") - .append("") .append("") - .append("SUSPEND_CANCEL") - .append("") .append("") - .append("") .append("") - .append("PAE_MODE") - .append("yes") - .append("") .append("") - .append("ENTRY") - .append("3242303488") - .append("") .append("") - .append("XEN_VERSION") - .append("xen-3.0") - .append("") .append("") - .append("") .append("") - .append("expose_host_uuid") .append("") - .append("") .append("") .append("") - .append("pci") .append("") - .append("") .append("") .append("") - .append("superpages") .append("") - .append("") .append("") .append("") - .append("nomigrate") .append("") - .append("") .append("") .append("") - .append("") .append("") .append("cpus") - .append("") .append("") - .append("") .append("") - .append("") .append("") .append("store_mfn") - .append("873707") .append("") - .append("") .append("uuid") .append("") - .append(VMID) - .append("") - .append("") - .append("") - .append("on_reboot") - .append("restart") - .append("") - .append("") - .append("state") - .append("-b----") - .append("") - .append("") - .append("cpu_weight") - .append("27500") - .append("") - .append("") - .append("online_vcpus") - .append("") - .append("") - .append("") - .append("") - .append("memory") - .append("512") - .append("") - .append("") - .append("cpu_cap") - .append("") - .append("") - .append("") - .append("") - .append("status") - .append("") - .append("") - .append("") - .append("") - .append("pool_name") - .append("Pool-0") - .append("") - .append("") - .append("description") - .append("") - .append("") - .append("") - .append("start_time") - .append("1408105444.17") - .append("") - .append("") - .append("on_poweroff") - .append("destroy") - .append("") - .append("") - .append("on_xend_start") - .append("ignore") - .append("") - .append("") - .append("on_crash") - .append("restart") - .append("") - .append("") - .append("device") - .append("") - .append("") - .append("vif") - .append("") - .append("") - .append("") - .append("bridge") - .append("").append(VMNICBR).append("") - .append("") - .append("") - .append("mac") - .append("").append(VMNICMAC).append("") - .append("") - .append("") - .append("script") - .append("/etc/xen/scripts/vif-bridge") - .append("") - .append("") - .append("uuid") - .append("").append(VMNICUUID).append("") - .append("") - .append("") - .append("backend") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("vkbd") - .append("") - .append("") - .append("") - .append("backend") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("console") - .append("") - .append("") - .append("") - .append("protocol") - .append("vt100") - .append("") - .append("") - .append("location") - .append("") - .append("") - .append("") - .append("") - .append("uuid") - .append("9beb5016-dde7-8526-491f-e972f262a634") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("vfb") - .append("") - .append("") - .append("") - .append("vncunused") - .append("") - .append("") - .append("") - .append("") - .append("vnc") - .append("") - .append("") - .append("") - .append("") - .append("xauthority") - .append("/root/.Xauthority") - .append("") - .append("") - .append("vnclisten") - .append("0.0.0.0") - .append("") - .append("") - .append("vncpasswd") - .append("7693f834ca67912e") - .append("") - .append("") - .append("keymap") - .append("en-us") - .append("") - .append("") - .append("location") - .append("0.0.0.0:5900") - .append("") - .append("") - .append("uuid") - .append("78edf954-e375-b142-9c76-791ce805b6ef") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("vbd") - .append("") - .append("") - .append("") - .append("protocol") - .append("x86_32-abi") - .append("") - .append("") - .append("uuid") - .append("bda35954-2596-025e-168c-b82e1cf92369") - .append("") - .append("") - .append("bootable") - .append("") - .append("") - .append("") - .append("") - .append("dev") - .append("xvda:disk") - .append("") - .append("") - .append("uname") - .append("file:/OVS/Repositories/") - .append(REPOID) - .append("/VirtualDisks/") - .append(VMROOTDISK) - .append("") - .append("") - .append("") - .append("mode") - .append("") - .append("") - .append("") - .append("") - .append("VDI") - .append("") - .append("") - .append("") - .append("backend") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("") - .append("bootloader") - .append("/usr/bin/pygrub") - .append("") - .append("") - .append("maxmem") - .append("512") - .append("") - .append("") - .append("cpu_time") - .append("5.627111952") - .append("") - .append("") - .append("shadow_memory") - .append("") - .append("") - .append("") - .append("") - .append("name") - .append("") - .append(VMNAME) - .append("") - .append("") - .append("") - .append("builder") - .append("linux") - .append("") - .append("") - .append("bootloader_args") - .append("-q") - .append("") - .append("") - .append("domid") - .append("") - .append("") - .append("") - .append("") - .append("vcpus") - .append("") - .append("") .append("") .append("").toString()); - - public String getSingleVmConfigXML() { - return this.SINGLEVMCONFIGXML; - } - String SINGLEVMCONFIGXML = results - .simpleResponseWrapWrapper(new StringBuilder("") - .append("") - .append("vif") - .append("") - .append("mac=").append(VMNICMAC).append(",bridge=").append(VMNICBR).append("") - .append("mac=02:00:50:9a:00:02,bridge=xenbr0.240") - .append("") .append("") .append("") - .append("extra") .append("") - .append("") .append("") .append("OVM_simple_name") - .append("") - .append(VMNAME) - .append("") - .append("") - .append("") - .append("disk") - .append("") - .append("file:/OVS/Repositories/") - .append(REPOID) - .append("/VirtualDisks/") - .append(VMROOTDISK) - .append(",xvda,w") - .append("") - .append("") - .append("") - .append("bootargs") - .append("") - .append("") - .append("") - .append("uuid") - .append("") - .append(VMID) - .append("") - .append("") - .append("") - .append("on_reboot") - .append("restart") - .append("") - .append("") - .append("cpu_weight") - .append("27500") - .append("") - .append("") - .append("memory") - .append("512") - .append("") - .append("") - .append("cpu_cap") - .append("0") - .append("") - .append("") - .append("maxvcpus") - .append("1") - .append("") - .append("") - .append("OVM_high_availability") - .append("0") - .append("") - .append("") - .append("OVM_description") - .append("") - .append("") - .append("") - .append("on_poweroff") - .append("destroy") - .append("") - .append("") - .append("on_crash") - .append("restart") - .append("") - .append("") - .append("bootloader") - .append("/usr/bin/pygrub") - .append("") - .append("") - .append("guest_os_type") - .append("Other.Linux") - .append("") - .append("") - .append("name") - .append("") - .append(VMNAME) - .append("") - .append("") - .append("") - .append("vfb") - .append("") - .append("vncunused=1,vncpasswd=7693f834ca67912e,keymap=en-us,type=vnc,vnclisten=0.0.0.0") - .append("") - .append("") - .append("") - .append("vcpus") - .append("1") - .append("") - .append("") - .append("OVM_cpu_compat_group") - .append("") - .append("") - .append("") - .append("OVM_domain_type") - .append("xen_pvm") - .append("") - .append("").toString()); - - /* fix */ - @Test - public void testListVm() throws Ovm3ResourceException { - con.setResult(this.SINGLEVMLISTXML); - results.basicBooleanTest(xEn.listVm(REPOID, VMID)); - con.setResult(results.getNil()); - results.basicBooleanTest(xEn.listVm(REPOID, VMID), false); - } - - @Test - public void testGetRunningVmConfig() throws Ovm3ResourceException { - con.setResult(this.MULTIPLEVMSLISTXML); - Xen.Vm domU = xEn.getRunningVmConfig(VMNAME); - - /* only works from a live configuration */ - results.basicStringTest(domU.getVmRootDiskPoolId(), REPOID); - results.basicIntTest(domU.getVncPort(), 5900); - results.basicStringTest(domU.getVncAddress(), "0.0.0.0"); - } - - @Test - public void testGetVmConfig() throws Ovm3ResourceException { - con.setResult(this.SINGLEVMCONFIGXML); - Xen.Vm domU = xEn.getVmConfig(REPOID, VMID); - /* getVncPort doesn't work with live config due to a bug in the agent */ - // results.basicIntTest(domU.getVncPort(), 5900); - results.basicStringTest(domU.getVmName(), VMNAME); - results.basicIntTest(domU.getVifIdByMac(VMNICMAC), 0); - results.basicIntTest(domU.getVifIdByMac("02:00:50:9a:00:02"), 1); - results.basicIntTest(domU.getVifIdByMac("02:00:50:9a:00:03"), -1); - con.setResult(results.getNil()); - xEn.getVmConfig(REPOID, VMID); - - con.setResult(results.getNil()); - } - - @Test - public void testRebootVM() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(xEn.rebootVm(REPOID, VMID)); - results.basicBooleanTest(xEn.rebootVm(REPOID, VMID, 1)); - } - - @Test - public void testControlDomain() throws Ovm3ResourceException { - con.setResult(this.MULTIPLEVMSLISTXML); - Xen.Vm dom0 = xEn.getRunningVmConfig(DOM0VMNAME); - results.basicBooleanTest(dom0.isControlDomain(), true); - Xen.Vm domU = xEn.getRunningVmConfig(VMNAME); - results.basicBooleanTest(domU.isControlDomain(), false); - con.setResult(results.getNil()); - } - - @Test - public void testCreateVm() throws Ovm3ResourceException { - Xen.Vm domU = xEn.getVmConfig(); - domU.setVmCpus(1); - domU.setVmMemory(512); - domU.setVmDomainType("default"); - domU.setVmUuid(UuidUtils.nameUUIDFromBytes(VMNAME.getBytes()).toString()); - domU.setVmName(VMNAME); - domU.addRootDisk(VMROOTDISK); - domU.setPrimaryPoolUuid(REPOID); - - domU.addVif(0, VMNICBR, VMNICMAC); - domU.addVif(0, "xenbr0.240", "02:00:50:9a:00:02"); - domU.removeVif("xenbr0.240", "02:00:50:9a:00:02"); - domU.setVnc("0.0.0.0", "gobbeldygoo"); - con.setResult(results.getNil()); - xEn.createVm(REPOID, VMID); - xEn.configureVmHa(REPOID, VMID, true); - xEn.startVm(REPOID, VMID); - - domU.addIso(VMISO); - domU.addIso(VMISO); - xEn.configureVm(REPOID, domU.getVmUuid()); - domU.removeDisk(VMISO); - domU.removeDisk("bogus"); - domU.getVmVifs(); - xEn.configureVm(REPOID, domU.getVmUuid()); - xEn.stopVm(REPOID, VMID, true); - - Xen.Vm domU2 = xEn.getVmConfig(); - domU2.setVmDomainType("hvm"); - domU2.addRootDisk(VMROOTDISK); - domU2.addDataDisk(VMROOTDISK); - domU2.getPrimaryPoolUuid(); - } - - @Test - public void testRemoveMissingVif() throws Ovm3ResourceException { - Xen.Vm domU = xEn.getVmConfig(); - domU.removeVif("xenbr0.240", "02:00:50:9a:00:02"); - } - - @Test - public void testVmDomainType() throws Ovm3ResourceException { - Xen.Vm domU = xEn.getVmConfig(); - domU.getVmDomainType(); - } - - @Test(expected = Ovm3ResourceException.class) - public void testMissingVncPort() throws Ovm3ResourceException { - Xen.Vm domU = xEn.getVmConfig(); - domU.getVncPort(); - } - - @Test - public void testVmCpusExceedsMaxVCPUs() throws Ovm3ResourceException { - Xen.Vm domU = xEn.getVmConfig(); - domU.setVmMaxCpus(2); - results.basicIntTest(domU.getVmMaxCpus(), 2); - domU.setVmCpus(4); - results.basicIntTest(domU.getVmCpus(), 2); - domU.setVmMaxCpus(12); - results.basicIntTest(domU.getVmCpus(), 2); - domU.setVmCpus(12); - results.basicIntTest(domU.getVmCpus(), 12); - domU.setVmMaxCpus(0); - results.basicIntTest(domU.getVmCpus(), 12); - } - - @Test - public void testStopVm() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(xEn.stopVm(REPOID, VMID)); - results.basicBooleanTest(xEn.stopVm(REPOID, VMID, true)); - } - - @Test - public void testPauseVm() throws Ovm3ResourceException { - con.setResult(results.getNil()); - results.basicBooleanTest(xEn.pauseVm(REPOID, VMID)); - } - - public String getMultipleVmsListXML() { - return MULTIPLEVMSLISTXML; - } - public String getVmName() { - return VMNAME; - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XmlTestResultTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XmlTestResultTest.java deleted file mode 100644 index b175a164baa1..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/objects/XmlTestResultTest.java +++ /dev/null @@ -1,134 +0,0 @@ -// 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.hypervisor.ovm3.objects; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.List; - -import org.apache.commons.lang3.StringEscapeUtils; - -public class XmlTestResultTest { - private static final String NULL = ""; - - private String brack(String type, String s) { - return "<" + type + ">" + s + ""; - } - - public String escapeOrNot(String s) { - if (s.startsWith("<")) { - return StringEscapeUtils.escapeXml10(s); - } - return s; - } - - public String errorResponseWrap(String message) { - return errorResponseWrap(1, message); - } - - /* - * example exceptions.OSError:[Errno.17].File.exists: - * '/OVS/Repositories/f12842ebf5ed3fe78da1eb0e17f5ede8/VilualDisks/test.raw' - */ - public String errorResponseWrap(Integer faultCode, String message) { - String rs = "" + "" + "" - + "" + "" + "faultCode" - + "" + faultCode + "" + "" - + "" + "faultString" + "" - + message + "" + "" - + "" + "" + ""; - return rs; - } - - public String methodResponseWrap(String towrap) { - return "\n" + "\n" + "\n" - + towrap + "\n" + ""; - } - - public String simpleResponseWrapWrapper(String s) { - return methodResponseWrap("\n" + "" + s + "\n" - + "\n"); - } - - /* brack the entire wrap ? :) */ - public String simpleResponseWrap(String type, String s) { - if (type.contentEquals(NULL)) { - s = NULL; - } else { - s = brack(type, s); - } - return simpleResponseWrapWrapper(s); - } - - public String simpleResponseWrap(String s) { - return simpleResponseWrapWrapper(s); - } - - public String getBoolean(boolean bool) { - String b = "1"; - if (!bool) { - b = "0"; - } - return simpleResponseWrap("boolean", b); - } - - public String getString(String s) { - return simpleResponseWrap("string", s); - } - - public String getNil() { - return simpleResponseWrap(NULL, NULL); - } - - public void basicBooleanTest(boolean result) { - basicBooleanTest(result, true); - } - - public void basicBooleanTest(boolean result, boolean desired) { - assertNotNull(result); - assertEquals(desired, result); - } - - public void basicStringTest(String result, String desired) { - assertNotNull(result); - assertEquals(desired, result); - } - - public void basicIntTest(Integer result, Integer desired) { - assertNotNull(result); - assertEquals(desired, result); - } - - public void basicLongTest(Long result, Long desired) { - assertEquals(desired, result); - } - - public Boolean basicListHasString(List list, String x) { - for (String y : list) { - if (y.matches(x)) { - return true; - } - } - return false; - } - - public void basicDoubleTest(Double result, Double desired) { - assertEquals(desired, result); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResourceTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResourceTest.java deleted file mode 100644 index f668cc62223c..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3HypervisorResourceTest.java +++ /dev/null @@ -1,364 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.junit.Test; -import org.mockito.Mockito; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.RebootCommand; -import com.cloud.agent.api.StartCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StopCommand; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.NfsTO; -import com.cloud.agent.api.to.NicTO; -import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.host.Host; -import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.NetworkTest; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.Xen; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3Configuration; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3ConfigurationTest; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; -import com.cloud.network.Networks; -import com.cloud.storage.Volume; -import com.cloud.template.VirtualMachineTemplate.BootloaderType; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.Type; - -public class Ovm3HypervisorResourceTest { - ConnectionTest con; - OvmObject ovmObject = new OvmObject(); - XmlTestResultTest results = new XmlTestResultTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3SupportTest support = new Ovm3SupportTest(); - NetworkTest net = new NetworkTest(); - // LinuxTest linux = new LinuxTest(); - CloudStackPluginTest csp = new CloudStackPluginTest(); - XenTest xen = new XenTest(); - String currentStatus = "put"; - String vmName = "i-2-3-VM"; - - @Test - public void configureTest() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - } - - /* fails */ - /* - @Test(expected = CloudRuntimeException.class) - public void configureFailBaseConnectionTest() throws - ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - results.basicBooleanTest(hypervisor.configure(con.getHostName(), - configTest.getParams())); - } - */ - - @Test - public void configureControlInterfaceTest() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - String netdef = net.getDiscoverNetwork(); - netdef = netdef.replaceAll(config.getAgentControlNetworkName(), - "thisisnotit0"); - con = support.prepConnectionResults(); - con.removeMethodResponse("discover_network"); - con.setResult(results.simpleResponseWrapWrapper(netdef)); - con.addResult(results.simpleResponseWrapWrapper(net - .getDiscoverNetwork())); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - } - - @Test - public void startCommandTest() { - } - - @Test - public void getCurrentStatusAndConfigureTest() - throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - assertNotNull(hypervisor.getCurrentStatus(1L)); - assertNotNull(hypervisor.getCurrentStatus(1L)); - } - - @Test - public void getCurrentStatusFailTest() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - con.setResult(results.simpleResponseWrapWrapper("fail")); - con.removeMethodResponse("echo"); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - assertNull(hypervisor.getCurrentStatus(1L)); - } - - @Test - public void getCurrentStatusExceptionTest() throws ConfigurationException { - con = new ConnectionTest(); - hypervisor.setConnection(con); - assertNull(hypervisor.getCurrentStatus(1L)); - } - - /* gives an IOException on ssh */ - @Test - public void initializeTest() throws Exception { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - con.setIp(config.getAgentIp()); - for (StartupCommand start : hypervisor.initialize()) { - assertNotNull(start); - } - } - - private Ovm3HypervisorResource vmActionPreparation() - throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - return hypervisor; - } - - private Boolean rebootVm(String name) throws ConfigurationException { - hypervisor = vmActionPreparation(); - con.removeMethodResponse("list_vms"); - con.addResult(xen.getMultipleVmsListXML()); - con.addResult(xen.getMultipleVmsListXML()); - RebootCommand cmd = new RebootCommand(name, true); - Answer ra = hypervisor.executeRequest(cmd); - return ra.getResult(); - } - - @Test - public void rebootCommandTest() throws ConfigurationException { - results.basicBooleanTest(rebootVm(vmName)); - } - - @Test - public void rebootCommandFailTest() throws ConfigurationException { - results.basicBooleanTest(rebootVm("bogus"), false); - } - - @Test - public void stopVmTest() throws ConfigurationException { - hypervisor = vmActionPreparation(); - con.removeMethodResponse("list_vms"); - con.setResult(xen.getMultipleVmsListXML()); - con.addResult(xen.getMultipleVmsListXML().replace(vmName, - vmName + "-hide")); - StopCommand cmd = new StopCommand(vmName, true, true); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - - /* takes too long */ - /* - * @Test - * public void stopVmTestFail() throws ConfigurationException { - * stopVm(); - * con.addResult(xen.getVmListXML().replace(vmName, vmName)); - * StopCommand cmd = new StopCommand(vmName, true, true); - * StopAnswer ra = hypervisor.execute(cmd); - * results.basicBooleanTest(ra.getResult(), false); - * } - */ - - @Test - public void stopVmTreatAsStoppedTest() throws ConfigurationException { - hypervisor = vmActionPreparation(); - con.setMethodResponse("list_vms", - xen.getMultipleVmsListXML().replace(vmName, vmName + "-hide")); - StopCommand cmd = new StopCommand(vmName, true, true); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - - @Test - public void stopVmExceptionTest() throws ConfigurationException { - hypervisor = vmActionPreparation(); - con.removeMethodResponse("list_vms"); - StopCommand cmd = new StopCommand(vmName, true, true); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } - - /* not relevant atm */ - public void addNicsToSpec(VirtualMachineTO vmspec, List list) { - for (String vif : list) { - String parts[] = vif.split("[,=.]+"); - addNicToSpec(vmspec, parts[1], parts[3], parts[4]); - } - } - - public void addNicToSpec(VirtualMachineTO vmspec, String mac, - String bridge, String vlan) { - ArrayList nics; - if (vmspec.getNics() != null) { - nics = new ArrayList(Arrays.asList(vmspec.getNics())); - } else { - nics = new ArrayList(); - } - NicTO nic = new NicTO(); - - nic.setType(Networks.TrafficType.Guest); - nic.setMac(mac); - nic.setDeviceId(nics.size()); - nics.add(nic); - vmspec.setNics(nics.toArray(new NicTO[nics.size()])); - } - - /* hardcoded, dirty */ - public void addDisksToSpec(VirtualMachineTO vmspec, List list) { - for (String disk : list) { - String parts[] = disk.split("[:,.]+"); - String partdeux[] = parts[1].split("/"); - String diskuuid = partdeux[partdeux.length - 1]; - String dsuuid = partdeux[3]; - String path = parts[1].replace("/" + diskuuid, ""); - addDiskToSpec(vmspec, diskuuid, dsuuid, path); - } - } - - public void addDiskToSpec(VirtualMachineTO vmspec, String uuid, - String dsuuid, String path) { - ArrayList disks; - if (vmspec.getDisks() != null) { - disks = new ArrayList(Arrays.asList(vmspec.getDisks())); - } else { - disks = new ArrayList(); - } - DiskTO disk = new DiskTO(); - VolumeObjectTO volume = new VolumeObjectTO(); - NfsTO nfsDataStore = new NfsTO(); - nfsDataStore.setUuid(dsuuid); - volume.setDataStore(nfsDataStore); - volume.setPath(path); - volume.setUuid(uuid); - disk.setData(volume); - disk.setType(Volume.Type.ROOT); - disks.add(disk); - vmspec.setDisks(disks.toArray(new DiskTO[disks.size()])); - } - - public Host getHost(String ip) { - Host host = Mockito.mock(Host.class); - Mockito.when(host.getPrivateIpAddress()).thenReturn(ip); - return host; - } - - public VirtualMachineTO createVm(String vmName) throws Ovm3ResourceException { - con = support.prepConnectionResults(); - Xen vdata = new Xen(con); - Xen.Vm vm = vdata.getVmConfig(vmName); - vdata.listVm(xen.getRepoId(), xen.getVmId()); - - // Ovm3VmGuestTypes types = new Ovm3VmGuestTypes(); - Long id = 1L; - String instanceName = vm.getVmName(); - VirtualMachine.Type type = Type.User; - int cpus = 1; // vm.getVmCpus(); - Integer speed = 0; - long minRam = vm.getVmMemory(); - long maxRam = vm.getVmMemory(); - BootloaderType bootloader = BootloaderType.PyGrub; - String os = "Oracle Enterprise Linux 6.0 (64-bit)"; - boolean enableHA = true; - boolean limitCpuUse = false; - String vncPassword = "gobbeldygoo"; - VirtualMachineTO vmspec = new VirtualMachineTO(id, instanceName, type, - cpus, speed, minRam, maxRam, bootloader, os, enableHA, - limitCpuUse, vncPassword); - vmspec.setBootArgs(""); - addDisksToSpec(vmspec, vm.getVmDisks()); - addNicsToSpec(vmspec, vm.getVmVifs()); - return vmspec; - } - - @Test - public void createVmTest() throws ConfigurationException, - Ovm3ResourceException { - VirtualMachineTO vmspec = createVm(vmName); - hypervisor = vmActionPreparation(); - StartCommand cmd = new StartCommand(vmspec, - getHost(hypervisor.getName()), true); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - - @Test - public void createOtherVmTest() throws ConfigurationException, - Ovm3ResourceException { - VirtualMachineTO vmspec = createVm(vmName); - vmspec.setOs("bogus"); - hypervisor = vmActionPreparation(); - StartCommand cmd = new StartCommand(vmspec, - getHost(hypervisor.getName()), true); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - - @Test - public void startResourceTest() { - results.basicBooleanTest(hypervisor.start()); - } - - @Test - public void stopResourceTest() { - results.basicBooleanTest(hypervisor.stop()); - } - @Test - public void readyCommandTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - ReadyCommand ready = new ReadyCommand(); - Answer ra = hypervisor.executeRequest(ready); - results.basicBooleanTest(ra.getResult()); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessorTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessorTest.java deleted file mode 100644 index a64a09e05e03..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3StorageProcessorTest.java +++ /dev/null @@ -1,342 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.storage.command.CopyCmdAnswer; -import org.apache.cloudstack.storage.command.CopyCommand; -import org.apache.cloudstack.storage.command.CreateObjectCommand; -import org.apache.cloudstack.storage.command.DeleteCommand; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.cloudstack.storage.to.TemplateObjectTO; -import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.junit.Test; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.agent.api.to.NfsTO; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.LinuxTest; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.StoragePluginTest; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3Configuration; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3ConfigurationTest; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; -import com.cloud.storage.Volume; -import com.cloud.vm.DiskProfile; - -public class Ovm3StorageProcessorTest { - ConnectionTest con = new ConnectionTest(); - OvmObject ovmObject = new OvmObject(); - XmlTestResultTest results = new XmlTestResultTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3SupportTest support = new Ovm3SupportTest(); - LinuxTest linux = new LinuxTest(); - XenTest xen = new XenTest(); - StoragePluginTest storageplugin = new StoragePluginTest(); - - private ConnectionTest prepare() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - return con; - } - - /* these could all actually be condensed to a DiskTO */ - private TemplateObjectTO template(final String uuid, final String dsuuid, - final String storeUrl, final String path) { - TemplateObjectTO template = new TemplateObjectTO(); - NfsTO nfsDataStore = new NfsTO(); - nfsDataStore.setUuid(dsuuid); - nfsDataStore.setUrl(storeUrl); - template.setDataStore(nfsDataStore); - template.setPath(path); - template.setUuid(uuid); - return template; - } - - private VolumeObjectTO volume(final String uuid, final String dsuuid, - final String storeUrl, final String path) { - VolumeObjectTO volume = new VolumeObjectTO(); - NfsTO nfsDataStore = new NfsTO(); - nfsDataStore.setUuid(dsuuid); - nfsDataStore.setUrl(storeUrl); - volume.setDataStore(nfsDataStore); - volume.setPath(path); - volume.setUuid(uuid); - return volume; - } - - private SnapshotObjectTO snapshot(final String uuid, final String dsuuid, - final String storeUrl, final String path) { - SnapshotObjectTO volume = new SnapshotObjectTO(); - NfsTO nfsDataStore = new NfsTO(); - nfsDataStore.setUuid(dsuuid); - nfsDataStore.setUrl(storeUrl); - volume.setDataStore(nfsDataStore); - volume.setPath(path); - // volume.setUuid(uuid); - return volume; - } - - private DiskTO disk(final String uuid, final String dsuuid, - final String storeUrl, final String path, Volume.Type type) { - DiskTO disk = new DiskTO(); - disk.setType(type); - disk.setPath(""); - TemplateObjectTO template = template(uuid, dsuuid, storeUrl, path); - disk.setData(template); - return disk; - } - - /** - * Copy template from primary to primary volume - * - * @throws ConfigurationException - */ - @Test - public void copyCommandTemplateToVolumeTest() throws ConfigurationException { - con = prepare(); - String voluuid = ovmObject.newUuid(); - TemplateObjectTO src = template(ovmObject.newUuid(), - ovmObject.newUuid(), linux.getRepoId(), linux.getTemplatesDir()); - VolumeObjectTO dest = volume(voluuid, ovmObject.newUuid(), - linux.getRepoId(), linux.getVirtualDisksDir()); - CopyCommand copy = new CopyCommand(src, dest, 0, true); - CopyCmdAnswer ra = (CopyCmdAnswer) hypervisor.executeRequest(copy); - VolumeObjectTO vol = (VolumeObjectTO) ra.getNewData(); - results.basicStringTest(vol.getUuid(), voluuid); - results.basicStringTest(vol.getPath(), voluuid); - results.basicBooleanTest(ra.getResult()); - } - - /** - * Copy template from secondary to primary template - * - * @throws ConfigurationException - */ - @Test - public void copyCommandTemplateToTemplateTest() - throws ConfigurationException { - con = prepare(); - con.setMethodResponse("storage_plugin_mount", - results.simpleResponseWrapWrapper(storageplugin - .getNfsFileSystemInfo())); - /* - * because the template requires a reference to the name for the uuid... - * -sigh- - */ - String templateid = ovmObject.newUuid(); - String targetid = ovmObject.newUuid(); - String templatedir = "template/tmpl/1/11" + templateid + ".raw"; - String storeUrl = "nfs://" + linux.getRemoteHost() + "/" - + linux.getRemoteDir(); - TemplateObjectTO src = template(templateid, linux.getRepoId(), - storeUrl, templatedir); - TemplateObjectTO dest = template(targetid, - linux.getRepoId(), linux.getRepoId(), linux.getTemplatesDir()); - CopyCommand copy = new CopyCommand(src, dest, 0, true); - CopyCmdAnswer ra = (CopyCmdAnswer) hypervisor.executeRequest(copy); - TemplateObjectTO vol = (TemplateObjectTO) ra.getNewData(); - results.basicStringTest(vol.getUuid(), targetid); - results.basicStringTest(vol.getPath(), targetid); - results.basicBooleanTest(ra.getResult()); - } - - /** - * Copy template from secondary to primary template - * - * @throws ConfigurationException - */ - @Test - public void copyCommandBogusTest() throws ConfigurationException { - con = prepare(); - VolumeObjectTO src = volume(ovmObject.newUuid(), ovmObject.newUuid(), - ovmObject.newUuid(linux.getRemote()), linux.getRemote()); - VolumeObjectTO dest = volume(ovmObject.newUuid(), ovmObject.newUuid(), - linux.getRepoId(), linux.getVirtualDisksDir()); - CopyCommand copy = new CopyCommand(src, dest, 0, false); - Answer ra = hypervisor.executeRequest(copy); - results.basicBooleanTest(ra.getResult(), false); - } - - /** - * Delete an object - * - * @throws ConfigurationException - */ - @Test - public void deleteCommandTest() throws ConfigurationException { - con = prepare(); - VolumeObjectTO vol = volume(ovmObject.newUuid(), ovmObject.newUuid(), - linux.getRepoId(), linux.getVirtualDisksDir()); - DeleteCommand delete = new DeleteCommand(vol); - Answer ra = hypervisor.executeRequest(delete); - results.basicBooleanTest(ra.getResult()); - TemplateObjectTO template = template(ovmObject.newUuid(), - ovmObject.newUuid(), ovmObject.newUuid(linux.getRemote()), - linux.getRemote()); - delete = new DeleteCommand(template); - ra = hypervisor.executeRequest(delete); - results.basicBooleanTest(ra.getResult(), false); - SnapshotObjectTO snap = snapshot(ovmObject.newUuid(), - ovmObject.newUuid(), ovmObject.newUuid(linux.getRemote()), - linux.getRemote()); - delete = new DeleteCommand(snap); - ra = hypervisor.executeRequest(delete); - results.basicBooleanTest(ra.getResult(), false); - } - - public DiskProfile diskProfile() { - DiskProfile dp = new DiskProfile(1L, Volume.Type.ROOT, - xen.getVmRootDiskName(), 1, storageplugin.getFileSize(), - new String[0], false, false, 1L); - return dp; - } - - /* - * unused ? - * - * @Test - * public void createCommandTest() throws ConfigurationException { - * con = prepare(); - * DiskProfile disk = diskProfile(); - * String templateUrl = null; - * StoragePoolVO poolio = new StoragePoolVO(); - * poolio.setPath(linux.getTemplatesDir()); - * poolio.setHostAddress(linux.getRemoteHost()); - * - * CreateCommand create = new CreateCommand(disk, templateUrl, poolio , - * false); - * Answer ra = hypervisor.executeRequest(create); - * results.basicBooleanTest(ra.getResult()); - * } - */ - @Test - public void createTemplateObjectCommandTest() throws ConfigurationException { - con = prepare(); - String tempuuid = ovmObject.newUuid(); - TemplateObjectTO template = template(tempuuid, ovmObject.newUuid(), - ovmObject.newUuid(linux.getRemote()), linux.getRemote()); - template.setSize(storageplugin.getFileSize()); - String response = storageplugin.getFileCreateXml().replace( - storageplugin.getFileName(), tempuuid + ".raw"); - response = response.replace(storageplugin.getPoolUuid(), - ovmObject.deDash(linux.getRepoId())); - con.setMethodResponse("storage_plugin_create", - results.simpleResponseWrapWrapper(response)); - CreateObjectCommand create = new CreateObjectCommand(template); - Answer ra = hypervisor.executeRequest(create); - results.basicBooleanTest(ra.getResult(), false); - } - - @Test - public void createVolumeObjectCommandTest() throws ConfigurationException { - con = prepare(); - String voluuid = ovmObject.newUuid(); - VolumeObjectTO vol = volume(voluuid, linux.getRepoId(), "", - linux.getVirtualDisksDir()); - vol.setSize(storageplugin.getFileSize()); - String response = storageplugin.getFileCreateXml().replace( - storageplugin.getFileName(), voluuid + ".raw"); - response = response.replace(storageplugin.getPoolUuid(), - ovmObject.deDash(linux.getRepoId())); - con.setMethodResponse("storage_plugin_create", - results.simpleResponseWrapWrapper(response)); - CreateObjectCommand create = new CreateObjectCommand(vol); - Answer ra = hypervisor.executeRequest(create); - results.basicBooleanTest(ra.getResult()); - } - - @Test - public void createSnapshotObjectCommandTest() throws ConfigurationException { - con = prepare(); - String snapuuid = ovmObject.newUuid(); - SnapshotObjectTO snap = snapshot(snapuuid, linux.getRepoId(), "", - linux.getVirtualDisksDir()); - String response = storageplugin.getFileCreateXml().replace( - storageplugin.getFileName(), snapuuid + ".raw"); - response = response.replace(storageplugin.getPoolUuid(), - ovmObject.deDash(linux.getRepoId())); - con.setMethodResponse("storage_plugin_create", - results.simpleResponseWrapWrapper(response)); - CreateObjectCommand create = new CreateObjectCommand(snap); - Answer ra = hypervisor.executeRequest(create); - results.basicBooleanTest(ra.getResult(), false); - } - - /* - * used ? - * - * @Test - * public void isoAttachTest() throws ConfigurationException { - * con = prepare(); - * con.setMethodResponse("storage_plugin_mount", - * results.simpleResponseWrapWrapper(storageplugin.getNfsFileSystemInfo())); - * String diskid = ovmObject.newUuid(); - * String storeUrl = "nfs://" + linux.getRemoteHost() + "/" + - * linux.getIsoDir(); - * DiskTO disk = disk(diskid, ovmObject.newUuid(), storeUrl, "bla", - * Volume.Type.ISO); - * AttachCommand at = new AttachCommand((DiskTO) disk, xen.getVmName()); - * Answer ra = storage.attachIso(at); - * System.out.println(ra); - * } - */ - @Test - public void isoDettachTest() throws ConfigurationException { - con = prepare(); - - } - - @Test - public void copyVolumeCommandTest() throws ConfigurationException { - con = prepare(); - String src = linux.getVirtualDisksDir() + ovmObject.newUuid() + ".raw"; - String dst = linux.getVirtualDisksDir() + ovmObject.newUuid() + ".raw"; - StoragePoolVO poolio = new StoragePoolVO(); - CopyVolumeCommand copy = new CopyVolumeCommand(0, src, poolio, dst, - true, 0, false); - Answer ra = hypervisor.executeRequest(copy); - results.basicBooleanTest(ra.getResult()); - copy = new CopyVolumeCommand(0, src, poolio, dst, false, 0, false); - ra = hypervisor.executeRequest(copy); - results.basicBooleanTest(ra.getResult()); - } - - /* - * unused ? - * - * @Test - * public void destroyCommandTest() throws ConfigurationException { - * con = prepare(); - * DestroyCommand destroy = new DestroyCommand(support.pool, - * (Volume) volume(xen.getVmRootDiskUuid(), linux.getRepoId(), "", - * linux.getVirtualDisksDir()), - * xen.getVmName()); - * } - */ -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResourceTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResourceTest.java deleted file mode 100644 index 5bcec76275a5..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/Ovm3VirtualRoutingResourceTest.java +++ /dev/null @@ -1,233 +0,0 @@ -// 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.hypervisor.ovm3.resources; - -import java.util.ArrayList; -import java.util.List; - -import javax.naming.ConfigurationException; - -import org.junit.Test; - -import com.cloud.agent.api.routing.IpAssocCommand; -import com.cloud.agent.api.routing.IpAssocVpcCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.to.IpAddressTO; -import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.LinuxTest; -import com.cloud.hypervisor.ovm3.objects.NetworkTest; -import com.cloud.hypervisor.ovm3.objects.OvmObject; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3Configuration; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3ConfigurationTest; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; -import com.cloud.network.Networks.TrafficType; -import com.cloud.utils.ExecutionResult; - -public class Ovm3VirtualRoutingResourceTest { - ConnectionTest con; - OvmObject ovmObject = new OvmObject(); - XmlTestResultTest results = new XmlTestResultTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3VirtualRoutingResource virtualrouting = new Ovm3VirtualRoutingResource(); - Ovm3SupportTest support = new Ovm3SupportTest(); - XenTest xen = new XenTest(); - NetworkTest net = new NetworkTest(); - LinuxTest linux = new LinuxTest(); - CloudStackPluginTest csp = new CloudStackPluginTest(); - String dom0Ip = csp.getDom0Ip(); - String domrIp = csp.getDomrIp(); - String routerip = "64.1.1.10"; - /* cheat */ - String cmd = "ls"; - String args = ""; - - @Test - public void executeInVRTest() { - con = support.prepConnectionResults(); - cmd = "/opt/cloud/bin/" + cmd; - virtualrouting.setConnection(con); - ExecutionResult result = virtualrouting.executeInVR(domrIp, cmd, args); - results.basicBooleanTest(result.isSuccess()); - } - - @Test - public void executeInVRFailTest() { - ConnectionTest con = new ConnectionTest(); - virtualrouting.setConnection(con); - ExecutionResult result = virtualrouting.executeInVR(domrIp, cmd, args); - results.basicBooleanTest(result.isSuccess(), false); - } - - @Test - public void createFileInVRTest() { - con = support.prepConnectionResults(); - virtualrouting.setConnection(con); - ExecutionResult result = virtualrouting.createFileInVR(domrIp, "/tmp", - "test", "1 2 3"); - results.basicBooleanTest(result.isSuccess()); - } - - @Test - public void createFileInVRFailTest() { - ConnectionTest con = new ConnectionTest(); - virtualrouting.setConnection(con); - ExecutionResult result = virtualrouting.createFileInVR(domrIp, "/tmp", - "test", "1 2 3"); - results.basicBooleanTest(result.isSuccess(), false); - } - - private ConnectionTest prepare() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - virtualrouting.setConnection(con); - return con; - } - - @Test - public void prepareVpcCommandFailTest() throws ConfigurationException { - prepare(); - IpAssocVpcCommand vpc = generateIpAssocVpcCommand(xen.getVmNicMac() - .replace("0", "A")); - results.basicBooleanTest(hypervisor.executeRequest(vpc).getResult(), - false); - } - - @Test - public void prepareVpcCommandFailHeavierTest() - throws ConfigurationException { - prepare(); - con.removeMethodResponse("list_vms"); - IpAssocVpcCommand vpc = generateIpAssocVpcCommand(xen.getVmNicMac() - .replace("0", "F")); - results.basicBooleanTest(hypervisor.executeRequest(vpc).getResult(), - false); - } - - @Test - public void prepareCommandTest() throws ConfigurationException { - prepare(); - IpAssocCommand rvm = generateIpAssocCommand(xen.getVmNicMac()); - results.basicBooleanTest(hypervisor.executeRequest(rvm).getResult()); - } - - /** - * Test is not broken, but code broke somewhere look for the mac that doesn' - "nics": [ - { - "deviceId": 2, - "networkRateMbps": 200, - "defaultNic": true, - "pxeDisable": true, - "nicUuid": "80bd3c5b-a0f0-4de5-894a-999c83210d7c", - "uuid": "eec7acd1-2845-4e46-9226-bd211bb97f28", - "ip": "192.168.1.154", - "netmask": "255.255.255.0", - "gateway": "192.168.1.1", - "mac": "06:83:0c:00:00:1e", - "dns1": "192.168.1.60", - "dns2": "192.168.1.1", - "broadcastType": "Vlan", - "type": "Public", - "broadcastUri": "vlan://0", - "isolationUri": "vlan://0", - "isSecurityGroupEnabled": false - }, - { - "com.cloud.agent.api.routing.IpAssocCommand": { - "ipAddresses": [ - { - "accountId": 2, - "publicIp": "192.168.1.154", - "sourceNat": true, - "add": true, - "oneToOneNat": false, - "firstIP": true, - "broadcastUri": "vlan://0", - "vlanGateway": "192.168.1.1", - "vlanNetmask": "255.255.255.0", - "vifMacAddress": "06:74:f6:00:00:1e", - "networkRate": 200, - "trafficType": "Public", - "newNic": false - } - * @throws ConfigurationException - */ - @Test - public void prepareCommandFailTest() throws ConfigurationException { - prepare(); - IpAssocCommand rvm = generateIpAssocCommand(xen.getVmNicMac().replace( - "0", "F")); - boolean res = hypervisor.executeRequest(rvm).getResult(); - // this should be false... - results.basicBooleanTest(res, - true); - } - - @Test - public void prepareCommandFailHeavierTest() throws ConfigurationException { - prepare(); - con.removeMethodResponse("list_vms"); - IpAssocCommand rvm = generateIpAssocCommand(xen.getVmNicMac().replace( - "0", "F")); - results.basicBooleanTest(hypervisor.executeRequest(rvm).getResult(), - false); - } - - @Test - public void prepareVpcCommandTest() throws ConfigurationException { - prepare(); - IpAssocVpcCommand vpc = generateIpAssocVpcCommand(xen.getVmNicMac()); - results.basicBooleanTest(hypervisor.executeRequest(vpc).getResult()); - } - - private IpAddressTO[] getIp(String mac) { - String br[] = xen.getVmNicBridge().split("[.]"); - List ips = new ArrayList(); - IpAddressTO ip = new IpAddressTO(1, routerip, true, true, true, "vlan://" - + br[1], "64.1.1.1", "255.255.255.0", mac, 1000, false); - ip.setTrafficType(TrafficType.Public); - ips.add(ip); - IpAddressTO[] ipArray = ips.toArray(new IpAddressTO[ips.size()]); - return ipArray; - } - - private IpAssocVpcCommand generateIpAssocVpcCommand(String mac) { - IpAssocVpcCommand cmd = new IpAssocVpcCommand(getIp(mac)); - cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, xen.getVmName()); - cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, routerip); - // assertEquals(6, cmd.getAnswersCount()); // AnswersCount is clearly - // wrong as it doesn't know enough to tell - return cmd; - } - - private IpAssocCommand generateIpAssocCommand(String mac) { - IpAssocCommand cmd = new IpAssocCommand(getIp(mac)); - cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, xen.getVmName()); - cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, routerip); - // assertEquals(6, cmd.getAnswersCount()); // AnswersCount is clearly - // wrong as it doesn't know enough to tell - return cmd; - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3ConfigurationTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3ConfigurationTest.java deleted file mode 100644 index 2665975f5ab4..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3ConfigurationTest.java +++ /dev/null @@ -1,111 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.util.HashMap; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.junit.Test; - -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; - -public class Ovm3ConfigurationTest { - XmlTestResultTest results = new XmlTestResultTest(); - private Ovm3Configuration ovm3config; - private static HashMap params; - static { - params = new HashMap(); - params.put("agentusername", "oracle"); - params.put("xenserver.heartbeat.interval", "60"); - params.put("public.network.device", "xenbr0"); - params.put("private.network.device", "xenbr0"); - params.put("agentpassword", "unknown"); - params.put("secondary.storage.vm", "false"); - params.put("Hypervisor.Version", "4.1.3OVM"); - params.put("Host.OS", "Oracle VM Server"); - params.put("ipaddress", "192.168.1.64"); - params.put("ovm3pool", "true"); - params.put("password", "unknown"); - params.put("username", "root"); - params.put("pool", "a9c1219d-817d-4242-b23e-2607801c79d5"); - params.put("isprimary", "false"); - params.put("storage.network.device", "xenbr0"); - params.put("Host.OS.Version", "5.7"); - params.put("xenserver.nics.max", "7"); - params.put("agentVersion", "3.2.1-183"); - params.put("router.aggregation.command.each.timeout", "3"); - params.put("pod", "1"); - params.put("max.template.iso.size", "50"); - params.put("host", "ovm-1"); - params.put("com.cloud.network.Networks.RouterPrivateIpStrategy", - "DcGlobal"); - params.put("agentport", "8899"); - params.put("Host.OS.Kernel.Version", "2.6.39-300.22.2.el5uek"); - params.put("migratewait", "3600"); - params.put("storage.network.device1", "xenbr0"); - params.put("ovm3cluster", "false"); - params.put("ip", "192.168.1.64"); - params.put("guid", "19e5f1e7-22f4-3b6d-8d41-c82f89c65295"); - params.put("ovm3vip", "192.168.1.230"); - params.put("hasprimary", "true"); - params.put("guest.network.device", "xenbr0"); - params.put("cluster", "1"); - params.put("xenserver.heartbeat.timeout", "120"); - params.put("ovm3.heartbeat.timeout", "120"); - params.put("ovm3.heartbeat.interval", "1"); - params.put("zone", "1"); - params.put("istest", true); - } - - @Test - public void testConfigLoad() throws ConfigurationException { - params.put("pod", "1"); - ovm3config = new Ovm3Configuration(params); - results.basicStringTest(ovm3config.getAgentHostname(), "ovm-1"); - } - - @Test(expected = ConfigurationException.class) - public void testFailedParams() throws ConfigurationException { - HashMap par = new HashMap(params); - par.put("pod", null); - ovm3config = new Ovm3Configuration(par); - } - @Test - public void testValidatePool() throws ConfigurationException { - HashMap par = new HashMap(params); - par.put("cluster", "1"); - par.put("ovm3vip", "this is not an IP!"); - ovm3config = new Ovm3Configuration(par); - results.basicBooleanTest(ovm3config.getAgentInOvm3Pool(), false); - results.basicBooleanTest(ovm3config.getAgentInOvm3Cluster(), false); - results.basicStringTest(ovm3config.getOvm3PoolVip(), ""); - } - @Test - public void testAgentPort() throws ConfigurationException { - HashMap par = new HashMap(params); - String altPort="6333"; - par.put("agentport", altPort); - ovm3config = new Ovm3Configuration(par); - results.basicIntTest(Integer.parseInt(altPort), ovm3config.getAgentOvsAgentPort()); - } - public Map getParams() { - return params; - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3GuestTypesTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3GuestTypesTest.java deleted file mode 100644 index 908183bda3a2..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3GuestTypesTest.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import org.junit.Test; - -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; - -public class Ovm3GuestTypesTest { - XmlTestResultTest results = new XmlTestResultTest(); - String ora = "Oracle Enterprise Linux 6.0 (64-bit)"; - Ovm3VmGuestTypes ovm3gt = new Ovm3VmGuestTypes(); - - @Test - public void testGetPvByOs() { - results.basicStringTest(ovm3gt.getOvm3GuestType(ora), "xen_pvm"); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetworkTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetworkTest.java deleted file mode 100644 index 3b5f5981949a..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorNetworkTest.java +++ /dev/null @@ -1,127 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.util.ArrayList; -import java.util.List; - -import javax.naming.ConfigurationException; - -import org.junit.Test; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckNetworkCommand; -import com.cloud.agent.api.PingTestCommand; -import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.NetworkTest; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResource; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResourceTest; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; -import com.cloud.network.PhysicalNetworkSetupInfo; - -public class Ovm3HypervisorNetworkTest { - ConnectionTest con = new ConnectionTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3SupportTest support = new Ovm3SupportTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3HypervisorResourceTest hyperTest = new Ovm3HypervisorResourceTest(); - CloudStackPluginTest csp = new CloudStackPluginTest(); - XenTest xen = new XenTest(); - NetworkTest network = new NetworkTest(); - XmlTestResultTest results = new XmlTestResultTest(); - - @Test - public void CheckNetworkCommandTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - List setups = new ArrayList(); - PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo(); - setups.add(networkInfo); - CheckNetworkCommand cmd = new CheckNetworkCommand(setups); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void CheckNetworkCommandGuestFailTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - List setups = new ArrayList(); - PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo(); - networkInfo.setGuestNetworkName(network.getInterface() + "." + 3000); - setups.add(networkInfo); - CheckNetworkCommand cmd = new CheckNetworkCommand(setups); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } - @Test - public void CheckNetworkCommandPublicFailTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - List setups = new ArrayList(); - PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo(); - networkInfo.setPublicNetworkName(network.getInterface() + "." + 3000); - setups.add(networkInfo); - CheckNetworkCommand cmd = new CheckNetworkCommand(setups); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } - @Test - public void CheckNetworkCommandPrivateFailTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - List setups = new ArrayList(); - PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo(); - networkInfo.setPrivateNetworkName(network.getInterface() + "." + 3000); - setups.add(networkInfo); - CheckNetworkCommand cmd = new CheckNetworkCommand(setups); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } - @Test - public void CheckNetworkCommandStorageFalseTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - List setups = new ArrayList(); - PhysicalNetworkSetupInfo networkInfo = new PhysicalNetworkSetupInfo(); - networkInfo.setStorageNetworkName(network.getInterface() + "." + 3000); - setups.add(networkInfo); - CheckNetworkCommand cmd = new CheckNetworkCommand(setups); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void PingTestCommandWeDontPingRouterTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - PingTestCommand cmd = new PingTestCommand(csp.getDom0Ip(), csp.getDomrIp()); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(),false); - } - @Test - public void PingTestCommandComputeTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - PingTestCommand cmd = new PingTestCommand(csp.getDom0Ip()); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void PingTestCommandComputeFalseTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - support.getConnection().setMethodResponse("ping", results.simpleResponseWrap("boolean", "0")); - PingTestCommand cmd = new PingTestCommand(csp.getDom0Ip()); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupportTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupportTest.java deleted file mode 100644 index c3614888ef3e..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3HypervisorSupportTest.java +++ /dev/null @@ -1,280 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import static org.junit.Assert.assertNull; - -import javax.naming.ConfigurationException; - -import org.junit.Test; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckHealthCommand; -import com.cloud.agent.api.CheckVirtualMachineCommand; -import com.cloud.agent.api.FenceCommand; -import com.cloud.agent.api.GetHostStatsCommand; -import com.cloud.agent.api.GetVncPortCommand; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.LinuxTest; -import com.cloud.hypervisor.ovm3.objects.NetworkTest; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResource; -import com.cloud.hypervisor.ovm3.resources.Ovm3StorageProcessor; -import com.cloud.hypervisor.ovm3.resources.Ovm3VirtualRoutingResource; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; -import com.cloud.vm.VirtualMachine.State; - -public class Ovm3HypervisorSupportTest { - ConnectionTest con = new ConnectionTest(); - XmlTestResultTest results = new XmlTestResultTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3VirtualRoutingResource virtualrouting = new Ovm3VirtualRoutingResource(); - Ovm3SupportTest support = new Ovm3SupportTest(); - Ovm3StorageProcessor storage; - Ovm3StoragePool pool; - XenTest xen = new XenTest(); - String vmName = xen.getVmName(); - String unknown = "------"; - String running = "r-----"; - String blocked = "-b----"; - String paused = "--p---"; - String shutdown = "---s--"; - String crashed = "----c-"; - String dying = "-----d"; - - /* we only want this for the xml results */ - String dom0stats = results.simpleResponseWrapWrapper("" - + "" + "rx" - + "25069761" + "" - + "" + "total" - + "4293918720" + "" - + "" + "tx" - + "37932556" + "" - + "" + "cpu" - + "2.4" + "" + "" - + "free" - + "1177550848" + "" - + ""); - - private ConnectionTest prepare() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con = support.prepConnectionResults(); - pool = new Ovm3StoragePool(con, config); - storage = new Ovm3StorageProcessor(con, config, pool); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - virtualrouting.setConnection(con); - return con; - } - @Test - public void ReportedVmStatesTest() throws ConfigurationException, - Ovm3ResourceException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con.setResult(xen.getMultipleVmsListXML()); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - hypervisor.vmStateMapClear(); - - State vmState = hypervisor.getVmState(vmName); - results.basicStringTest(vmState.toString(), State.Running.toString()); - hypervisor.setVmStateStarting(vmName); - results.basicStringTest(hypervisor.getVmState(vmName).toString(), - State.Starting.toString()); - hypervisor.setVmState(vmName, State.Running); - results.basicStringTest(hypervisor.getVmState(vmName).toString(), - State.Running.toString()); - hypervisor.revmoveVmState(vmName); - assertNull(hypervisor.getVmState(vmName)); - } - - @Test - public void HypervisorVmStateTest() throws ConfigurationException, - Ovm3ResourceException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - setHypervisorVmState(hypervisor, blocked, unknown, State.Unknown); - setHypervisorVmState(hypervisor, blocked, running, State.Running); - setHypervisorVmState(hypervisor, blocked, blocked, State.Running); - setHypervisorVmState(hypervisor, blocked, paused, State.Running); - /* TODO: ehm wtf ? */ - setHypervisorVmState(hypervisor, blocked, shutdown, State.Running); - setHypervisorVmState(hypervisor, blocked, crashed, State.Error); - setHypervisorVmState(hypervisor, blocked, dying, State.Stopping); - } - - @Test - public void CombinedVmStateTest() throws ConfigurationException, - Ovm3ResourceException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - con.setResult(xen.getMultipleVmsListXML()); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - hypervisor.vmStateMapClear(); - /* test starting */ - hypervisor.setVmState(vmName, State.Starting); - // System.out.println(hypervisor.getVmState(vmName)); - hypervisor.syncState(); - // System.out.println(hypervisor.getVmState(vmName)); - - // setHypervisorVmState(hypervisor, blocked, paused, State.Stopped); - - hypervisor.setVmState(vmName, State.Stopping); - hypervisor.setVmState(vmName, State.Migrating); - // setHypervisorVmState(hypervisor, blocked, running, State.Running); - hypervisor.setVmState(vmName, State.Stopped); - - // setHypervisorVmState(hypervisor, blocked, running, State.Migrating); - - } - - /** - * Sets the state, original, of the fake VM to replace. - * - * @param hypervisor - * @param original - * @param replace - * @param state - * @throws Ovm3ResourceException - */ - public void setHypervisorVmState(Ovm3HypervisorSupport hypervisor, - String original, String replace, State state) - throws Ovm3ResourceException { - String x = xen.getMultipleVmsListXML().replaceAll(original, replace); - con.setResult(x); - hypervisor.syncState(); - results.basicStringTest(hypervisor.getVmState(vmName).toString(), - state.toString()); - } - - @Test - public void getSystemVMKeyFileTest() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - hypervisor.getSystemVMKeyFile(config.getAgentSshKeyFileName()); - } - @Test - public void getSystemVMKeyFileMissingTest() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - hypervisor.getSystemVMKeyFile("missing"); - } - - @Test - public void checkHealthTest() throws ConfigurationException { - con = prepare(); - CheckHealthCommand cmd = new CheckHealthCommand(); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - - @Test - public void primaryCheckTest() throws ConfigurationException { - con = prepare(); - // System.out.println(hypervisor.primaryCheck()); - } - - @Test - public void GetHostStatsCommandTest() throws ConfigurationException { - con = prepare(); - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - GetHostStatsCommand cmd = new GetHostStatsCommand(config.getCsHostGuid(), - config.getAgentName(), 1L); - con.setResult(this.dom0stats); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - - @Test - public void GetHostStatsCommandFailTest() throws ConfigurationException { - con = prepare(); - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - GetHostStatsCommand cmd = new GetHostStatsCommand(config.getCsHostGuid(), - config.getAgentName(), 1L); - con.setNull(); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } - - @Test - public void CheckVirtualMachineCommandTest() throws ConfigurationException { - con = prepare(); - CheckVirtualMachineCommand cmd = new CheckVirtualMachineCommand(xen.getVmName()); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void MaintainCommandTest() throws ConfigurationException { - con = prepare(); - MaintainCommand cmd = new MaintainCommand(); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void GetVncPortCommandTest() throws ConfigurationException { - con = prepare(); - GetVncPortCommand cmd = new GetVncPortCommand(0, xen.getVmName()); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - /* We can't fence yet... */ - @Test - public void FenceCommandTest() throws ConfigurationException { - con = prepare(); - FenceCommand cmd = new FenceCommand(); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult(), false); - } - - @Test - public void fillHostinfoTest() throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - ConnectionTest con = new ConnectionTest(); - con.setIp(config.getAgentIp()); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - LinuxTest linuxTest = new LinuxTest(); - NetworkTest networkTest = new NetworkTest(); - StartupRoutingCommand srCmd = new StartupRoutingCommand(); - con.setResult(results.simpleResponseWrapWrapper(linuxTest - .getDiscoverHw())); - con.addResult(results.simpleResponseWrapWrapper(linuxTest - .getDiscoverserver())); - con.addResult(results.simpleResponseWrapWrapper(networkTest - .getDiscoverNetwork())); - hypervisor.fillHostInfo(srCmd); - } - - /* @Test(expected = CloudRuntimeException.class) - public void setupServerTest() throws ConfigurationException, IOException { - Ovm3Configuration config = new Ovm3Configuration(configTest.getParams()); - ConnectionTest con = new ConnectionTest(); - con.setIp("127.0.0.1"); - Ovm3HypervisorSupport hypervisor = new Ovm3HypervisorSupport(con, - config); - hypervisor.setupServer(config.getAgentSshKeyFileName()); - } */ -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupportTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupportTest.java deleted file mode 100644 index 081adacb4744..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VirtualRoutingSupportTest.java +++ /dev/null @@ -1,88 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import javax.naming.ConfigurationException; - -import org.junit.Test; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.NetworkUsageCommand; -import com.cloud.agent.api.check.CheckSshCommand; -import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResource; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; - -public class Ovm3VirtualRoutingSupportTest { - ConnectionTest con = new ConnectionTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3SupportTest support = new Ovm3SupportTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - CloudStackPluginTest csp = new CloudStackPluginTest(); - XmlTestResultTest results = new XmlTestResultTest(); - - @Test - public void NetworkUsageCommandTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - NetworkUsageCommand nuc = new NetworkUsageCommand(csp.getDomrIp(), "something", "", false); - Answer ra = hypervisor.executeRequest(nuc); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void NetworkUsageVpcCommandTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - NetworkUsageCommand nuc = new NetworkUsageCommand(csp.getDomrIp(), "something", "", true); - Answer ra = hypervisor.executeRequest(nuc); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void NetworkVpcGetCommandTest() throws ConfigurationException { - NetworkVpcCommandTest("get"); - } - @Test - public void NetworkVpcCreateCommandTest() throws ConfigurationException { - NetworkVpcCommandTest("create"); - } - @Test - public void NetworkVpcResetCommandTest() throws ConfigurationException { - NetworkVpcCommandTest("reset"); - } - @Test - public void NetworkVpcVpnCommandTest() throws ConfigurationException { - NetworkVpcCommandTest("vpn"); - } - @Test - public void NetworkVpcRemoveCommandTest() throws ConfigurationException { - NetworkVpcCommandTest("remove"); - } - public void NetworkVpcCommandTest(String cmd) throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - NetworkUsageCommand nuc = new NetworkUsageCommand(csp.getDomrIp(), "something", cmd, true); - Answer ra = hypervisor.executeRequest(nuc); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void CheckSshCommandTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - CheckSshCommand ssh = new CheckSshCommand("name", csp.getDomrIp(), 8899); - Answer ra = hypervisor.executeRequest(ssh); - results.basicBooleanTest(ra.getResult()); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupportTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupportTest.java deleted file mode 100644 index e65f0d4f762f..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/resources/helpers/Ovm3VmSupportTest.java +++ /dev/null @@ -1,128 +0,0 @@ -// 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.hypervisor.ovm3.resources.helpers; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import javax.naming.ConfigurationException; -import org.junit.Test; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.GetVmStatsCommand; -import com.cloud.agent.api.MigrateCommand; -import com.cloud.agent.api.PlugNicCommand; -import com.cloud.agent.api.PrepareForMigrationCommand; -import com.cloud.agent.api.UnPlugNicCommand; -import com.cloud.agent.api.to.NicTO; -import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.Ovm3ResourceException; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResource; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResourceTest; -import com.cloud.hypervisor.ovm3.support.Ovm3SupportTest; -import com.cloud.network.Networks.TrafficType; -import com.cloud.vm.VirtualMachine; - -public class Ovm3VmSupportTest { - ConnectionTest con = new ConnectionTest(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - Ovm3SupportTest support = new Ovm3SupportTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3HypervisorResourceTest hyperTest = new Ovm3HypervisorResourceTest(); - CloudStackPluginTest csp = new CloudStackPluginTest(); - XenTest xen = new XenTest(); - XmlTestResultTest results = new XmlTestResultTest(); - - private NicTO prepNic(String mac, Integer vlan, TrafficType type) throws URISyntaxException { - return prepNic(mac, vlan, type, 0); - } - private NicTO prepNic(String mac, Integer vlan, TrafficType type, Integer id) throws URISyntaxException { - URI iso = new URI("vlan://" + vlan.toString()); - NicTO nic = new NicTO(); - nic.setType(type); - /* Isolation is not what it seems.... */ - /* nic.setIsolationuri(iso); */ - nic.setBroadcastUri(iso); - nic.setMac(mac); - nic.setDeviceId(id); - return nic; - } - @Test - public void PlugNicTest() throws ConfigurationException, URISyntaxException { - hypervisor = support.prepare(configTest.getParams()); - NicTO nic = prepNic(xen.getVmNicMac(), 200, TrafficType.Guest); - PlugNicCommand plug = new PlugNicCommand(nic,xen.getVmName(), VirtualMachine.Type.User); - Answer ra = hypervisor.executeRequest(plug); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void PlugNicBreakTest() throws ConfigurationException, URISyntaxException { - hypervisor = support.prepare(configTest.getParams()); - NicTO nic = prepNic(xen.getVmNicMac(), 240, TrafficType.Guest); - PlugNicCommand plug = new PlugNicCommand(nic,xen.getVmName(), VirtualMachine.Type.User); - Answer ra = hypervisor.executeRequest(plug); - results.basicBooleanTest(ra.getResult(), false); - } - @Test - public void unPlugNicTest() throws ConfigurationException, URISyntaxException { - hypervisor = support.prepare(configTest.getParams()); - NicTO nic = prepNic(xen.getVmNicMac(), 200, TrafficType.Guest); - UnPlugNicCommand plug = new UnPlugNicCommand(nic, xen.getVmName()); - Answer ra = hypervisor.executeRequest(plug); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void unPlugNicBreakTest() throws ConfigurationException, URISyntaxException { - hypervisor = support.prepare(configTest.getParams()); - NicTO nic = prepNic(xen.getVmNicMac(), 240, TrafficType.Guest); - UnPlugNicCommand plug = new UnPlugNicCommand(nic, xen.getVmName()); - Answer ra = hypervisor.executeRequest(plug); - results.basicBooleanTest(ra.getResult(), false); - } - @Test - public void GetVmStatsCommandTest() throws ConfigurationException { - hypervisor = support.prepare(configTest.getParams()); - Ovm3Configuration configuration = new Ovm3Configuration(configTest.getParams()); - List vms = new ArrayList(); - vms.add(xen.getVmName()); - GetVmStatsCommand cmd = new GetVmStatsCommand(vms, configuration.getCsHostGuid(), hypervisor.getName()); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - cmd = new GetVmStatsCommand(vms, configuration.getCsHostGuid(), hypervisor.getName()); - ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void PrepareForMigrationCommandTest() throws ConfigurationException, Ovm3ResourceException { - hypervisor = support.prepare(configTest.getParams()); - PrepareForMigrationCommand cmd = new PrepareForMigrationCommand(hyperTest.createVm(xen.getVmName())); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } - @Test - public void MigrateCommandTest() throws ConfigurationException, Ovm3ResourceException { - Ovm3Configuration configuration = new Ovm3Configuration(configTest.getParams()); - hypervisor = support.prepare(configTest.getParams()); - MigrateCommand cmd = new MigrateCommand(xen.getVmName(), configuration.getAgentIp(), false, hyperTest.createVm(xen.getVmName()), false); - Answer ra = hypervisor.executeRequest(cmd); - results.basicBooleanTest(ra.getResult()); - } -} diff --git a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/support/Ovm3SupportTest.java b/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/support/Ovm3SupportTest.java deleted file mode 100644 index 8d9fb858af7a..000000000000 --- a/plugins/hypervisors/ovm3/src/test/java/com/cloud/hypervisor/ovm3/support/Ovm3SupportTest.java +++ /dev/null @@ -1,112 +0,0 @@ -// 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.hypervisor.ovm3.support; - -import java.util.Map; - -import javax.naming.ConfigurationException; - -import com.cloud.hypervisor.ovm3.objects.CloudStackPluginTest; -import com.cloud.hypervisor.ovm3.objects.ConnectionTest; -import com.cloud.hypervisor.ovm3.objects.LinuxTest; -import com.cloud.hypervisor.ovm3.objects.NetworkTest; -import com.cloud.hypervisor.ovm3.objects.XenTest; -import com.cloud.hypervisor.ovm3.objects.XmlTestResultTest; -import com.cloud.hypervisor.ovm3.resources.Ovm3HypervisorResource; -import com.cloud.hypervisor.ovm3.resources.Ovm3VirtualRoutingResource; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3Configuration; -import com.cloud.hypervisor.ovm3.resources.helpers.Ovm3ConfigurationTest; - -public class Ovm3SupportTest { - ConnectionTest con = new ConnectionTest(); - XmlTestResultTest results = new XmlTestResultTest(); - NetworkTest net = new NetworkTest(); - LinuxTest linux = new LinuxTest(); - XenTest xen = new XenTest(); - CloudStackPluginTest csp = new CloudStackPluginTest(); - Ovm3HypervisorResource hypervisor = new Ovm3HypervisorResource(); - Ovm3VirtualRoutingResource virtualrouting = new Ovm3VirtualRoutingResource(); - Ovm3ConfigurationTest configTest = new Ovm3ConfigurationTest(); - - public ConnectionTest prepConnectionResults() { - ConnectionTest con = new ConnectionTest(); - con.setIp(con.getHostName()); - return configureResult(con); - } - - public Ovm3HypervisorResource prepare(Map params) throws ConfigurationException { - Ovm3Configuration config = new Ovm3Configuration(params); - con = prepConnectionResults(); - hypervisor.setConnection(con); - results.basicBooleanTest(hypervisor.configure(config.getAgentName(), - configTest.getParams())); - return hypervisor; - } - public ConnectionTest getConnection() { - return con; - } - - public ConnectionTest configureResult(ConnectionTest con) { - con.setMethodResponse("check_dom0_ip", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("ovs_ip_config", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("ovs_local_config", - results.simpleResponseWrap("string", "start")); - con.setMethodResponse("ovs_control_interface", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("update_server_roles", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("discover_network", - results.simpleResponseWrapWrapper(net.getDiscoverNetwork())); - con.setMethodResponse("discover_hardware", - results.simpleResponseWrapWrapper(linux.getDiscoverHw())); - con.setMethodResponse("discover_server", - results.simpleResponseWrapWrapper(linux.getDiscoverserver())); - con.setMethodResponse("discover_mounted_file_systems", - results.simpleResponseWrapWrapper(linux.getDiscoverFs())); - con.setMethodResponse("get_vncport", results.simpleResponseWrapWrapper("5900")); - con.setMethodResponse("echo", results.simpleResponseWrapWrapper("put")); - con.setMethodResponse("list_vms", xen.getMultipleVmsListXML()); - con.setMethodResponse("list_vm", xen.getSingleVmListXML()); - con.setMethodResponse("get_vm_config", xen.getSingleVmConfigXML()); - con.setMethodResponse("create_vm", results.getNil()); - con.setMethodResponse("start_vm", results.getNil()); - con.setMethodResponse("reboot_vm", results.getNil()); - con.setMethodResponse("stop_vm", results.getNil()); - con.setMethodResponse("configure_vm", results.getNil()); - con.setMethodResponse("migrate_vm", results.getNil()); - con.setMethodResponse("copy_file", results.getNil()); - con.setMethodResponse("storage_plugin_destroy", results.getNil()); - con.setMethodResponse("ping", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("check_domr_ssh", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("check_domr_port", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("exec_domr", csp.getDomrExecXml()); - con.setMethodResponse("ovs_domr_upload_file", - results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("ovs_domU_stats", (csp.getDomuStatsXml())); - con.setMethodResponse("check_dom0_status", (csp.getDom0StorageCheckXml())); - con.setMethodResponse("check_dom0_storage_health", results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("check_dom0_port", results.simpleResponseWrap("boolean", "1")); - con.setMethodResponse("check_dom0_storage_health_check", (csp.getDom0StorageCheckXml())); - return con; - } -} diff --git a/plugins/hypervisors/ovm3/src/test/resources/log4j.properties b/plugins/hypervisors/ovm3/src/test/resources/log4j.properties deleted file mode 100644 index 0f72e39d8554..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/log4j.properties +++ /dev/null @@ -1,25 +0,0 @@ -# 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. - -# Root logger option -log4j.rootLogger=DEBUG, stdout - -# Direct log messages to stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/clean_primary.sh b/plugins/hypervisors/ovm3/src/test/resources/scripts/clean_primary.sh deleted file mode 100755 index 5086a16fa79f..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/clean_primary.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash -# -# 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. -# -for i in `xm list | awk '{ print $1 }' | grep -E -v "Name|Domain-0"` -do - xm destroy $i -done -rm /etc/ovs-agent/db/server -rm /etc/ovs-agent/db/repository -rm /etc/ocfs2/cluster.conf -rm /nfsmnt/*/*.img -rm /nfsmnt/*/.ovspoolfs -rm /nfsmnt/*/.generic_fs_stamp -rm /OVS/Repositories/*/.generic_fs_stamp -rm /OVS/Repositories/*/.ovsrepo -/etc/init.d/ovs-agent restart -/etc/init.d/ocfs2 restart -for i in `mount | grep cs-mgmt | awk '{ print $1 }'` -do - umount $i -done -rm -rf /OVS/Repositories/* -rm -rf /nfsmnt/* -ip addr del 192.168.1.230 dev c0a80100 -ip addr del 192.168.1.161 dev c0a80100 -rm /etc/sysconfig/network-scripts/ifcfg-control0 -reboot diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/clean_secondary.sh b/plugins/hypervisors/ovm3/src/test/resources/scripts/clean_secondary.sh deleted file mode 100755 index 3d5133971526..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/clean_secondary.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -# -# 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. -# -for i in `xm list | awk '{ print $1 }' | grep -E -v "Name|Domain-0"` -do - xm destroy $i -done -rm /etc/ovs-agent/db/server -rm /etc/ovs-agent/db/repository -rm /etc/ocfs2/cluster.conf -/etc/init.d/ovs-agent restart -/etc/init.d/ocfs2 restart -for i in `mount | grep cs-mgmt | awk '{ print $1 }'` -do - umount $i -done diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/create_pool_cluster.py b/plugins/hypervisors/ovm3/src/test/resources/scripts/create_pool_cluster.py deleted file mode 100755 index f3bb59e72432..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/create_pool_cluster.py +++ /dev/null @@ -1,270 +0,0 @@ -#!/usr/bin/python -# -# 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. -# -import os, sys, subprocess -from xml.dom.minidom import parseString - -from xmlrpclib import ServerProxy, Error - -server = ServerProxy("http://localhost:8899") - -pooledFs = 1 -normalRepo = 0 - -try: - if normalRepo: - print("normal repo") - # this literally throws EVERYTHING away on the repo - repoDom = parseString(server.discover_repository_db()) - for node in repoDom.getElementsByTagName('Repository'): - repoUuid = node.attributes['Uuid'] - remoteMount = node.getElementsByTagName('Fs_location')[0].firstChild.nodeValue - localMount = node.getElementsByTagName('Mount_point')[0].firstChild.nodeValue - - # there is a "strong" relation between repo's and VMs - # unfortunately there is no reference in the vm.cfg - # or any known info in the configuration of the VM - # in which repo it lives.... - for dirname, dirnames, filenames in os.walk('%s/VirtualMachines/' % localMount): - for vm in dirnames: - print("Destroying vm: %s on repo %s" % (vm, repoUuid.value)) - try: - mVm = server.list_vm(repoUuid.value, vm) - if mVm is not None: - print(server.stop_vm(repoUuid.value, vm)) - print(server.delete_vm(repoUuid.value, vm)) - else: - print("%s already not in repo %s" % (repoUuid.value, vm)) - except Error as v: - print("Unable to destroy: %s" % v) - continue - - # VMs = server.list_vms() - # for vm in VMs: - # if vm['domid'] != '0': - # print vm - # print server.delete_vm(repoUuid.value, vm['uuid']) - - rc = server.delete_repository(repoUuid.value, True) - # Set to false if you want to keep data: ^^^^ - print("Repository: %s" % repoUuid.value) - if rc is None: - print("Ok repo: %s destroyed!" % repoUuid.value) - # now unmount the FS - # print server.unmount_repository_fs(localMount) - else: - print("Failed repo: %s not destroyed!" % repoUuid.value) - - # for now only treat NFS stuff as we're testing with that. - nfsHost = 'cs-mgmt' - nfsDom = server.storage_plugin_listMountPoints( - 'oracle.generic.NFSPlugin.GenericNFSPlugin', - { 'status': '', - 'admin_user': '', - 'admin_host': '', - 'uuid': '', - 'total_sz': 0, - 'admin_passwd': '', - 'free_sz': 0, - 'name': '', - 'access_host': nfsHost, - 'storage_type': 'FileSys', - 'alloc_sz': 0, - 'access_grps': [], - 'used_sz': 0, - 'storage_desc': '' - }) - for node in nfsDom: - props = {'status': node['status'], - 'uuid': '', - 'access_host': nfsHost, - 'storage_type': 'FileSys', - 'name': '' } - extprops = {'status': node['status'], - 'uuid': node['fs_uuid'], - 'ss_uuid': '', - 'size': 0, - 'free_sz': '', - 'state': 1, - 'access_grp_names': [], - 'access_path': nfsHost + ':' + '/volumes/cs-data/secondary', - 'name': ''} - # rc = server.storage_plugin_unmount('oracle.generic.NFSPlugin.GenericNFSPlugin', props, extprops, nfsMnt, True) - # print rc - - nfsDom = parseString(server.discover_mounted_file_systems('nfs')) - for node in nfsDom.getElementsByTagName('Mount'): - nfsMnt = node.attributes['Dir'].value - print('Mountpoint: %s' % nfsMnt) - fsStamp = '%s/.generic_fs_stamp' % nfsMnt - # remove this so we don't cock up next run - if os.path.isfile(fsStamp): - print("Stamp found: %s" % fsStamp) - os.unlink(fsStamp) - - rc = server.storage_plugin_unmount('oracle.generic.NFSPlugin.GenericNFSPlugin', props, extprops, nfsMnt, True) - print(rc) - - if pooledFs: - print("pooling") - # pool stuff - poolalias = "ItsMyPool" - poolmvip = "192.168.1.161" - poolfirsthost = { - 'ip': "192.168.1.64", - 'hn': "ovm-1", - 'id': 0, - 'role': 'utility,xen' - } - fstype = "nfs" - fstarget = "cs-mgmt:/volumes/cs-data/primary" - poolid = "0004fb0000020000ba9aaf00ae5e2d73" - clusterid = "ba9aaf00ae5e2d72" - poolfsuuid = "0004fb0000050000e70fbddeb802208f" - poolfsnfsbaseuuid = "b8ca41cb-3469-4f74-a086-dddffe37dc2d" - manageruuid = "0004fb00000100000af70d20dcce7d65" - pooluuid = "0004fb0000020000ba9aaf00ae5e2d73" - blocksize = "" - clustersize = "" - journalesize = "" - - # o2cb is the problem.... /etc/init.d/o2cb - # sets its config in /etc/sysconfig/o2cb (can be removed) - # dmsetup requires the stopping of o2cb first, - # then the removal of the config, after which dmsetup - # can remove the device from /dev/mapper/ - # eventually cluster cleanup can be done by removing - # stuff from /etc/ovs-agent/db - # also clean /etc/ocfs2/cluster.conf - print(server.create_pool_filesystem( - fstype, - fstarget, - clusterid, - poolfsuuid, - poolfsnfsbaseuuid, - manageruuid, - pooluuid - )) - - # poolDom = server.discover_server_pool() - # print poolDom - # poolDom = parseString(server.discover_server_pool()) - # if poolDom.getElementsByTagName('Server_Pool'): - # get unique id - cluster = server.is_cluster_online() - if cluster: - print("clean up pool") - # print server.destroy_cluster(poolfsuuid) - # deconfigure cluster - # print server.destroy_server_pool(poolid) - - if not cluster: - print("create_server_pool") - # first take ownership. without an owner nothing happens - print(server.take_ownership(manageruuid, "")) - # we need to add the first host first to the pool.... - poolDom = server.discover_server_pool() - print(poolDom) - poolDom = parseString(server.discover_server_pool()) - if poolDom.getElementsByTagName('Server_Pool'): - print(server.destroy_server_pool(pooluuid)) - - print(server.create_pool_filesystem( - fstype, - fstarget, - clusterid, - poolfsuuid, - poolfsnfsbaseuuid, - manageruuid, - pooluuid - )) - print(server.create_server_pool(poolalias, - pooluuid, - poolmvip, - poolfirsthost['id'], - poolfirsthost['hn'], - poolfirsthost['ip'], - poolfirsthost['role'])) - - print("configure_virtual_ip") - server.configure_virtual_ip(poolmvip, poolfirsthost['ip']) - server.set_pool_member_ip_list(['192.168.1.64', '192.168.1.65'],) - print("configure for cluster") - server.configure_server_for_cluster( - { - 'O2CB_HEARTBEAT_THRESHOLD': '61', - 'O2CB_RECONNECT_DELAY_MS': '2000', - 'O2CB_KEEPALIVE_DELAY_MS': '2000', - 'O2CB_BOOTCLUSTER': clusterid, - 'O2CB_IDLE_TIMEOUT_MS': '60000', - 'O2CB_ENABLED': 'true', - 'O2CB_STACK': 'o2cb' - }, - { - 'node': [ - { - 'ip_port': 7777, - 'cluster': clusterid, - 'ip_address': poolfirsthost['ip'], - 'name': poolfirsthost['hn'], - 'number': poolfirsthost['id'] - } - ], - 'heartbeat': [ - { - 'cluster': clusterid, - # uppercase poolfsuuid - 'region': '0004FB0000050000E70FBDDEB802208F' - } - ], - 'cluster': [ - { - 'heartbeat_mode': 'global', - 'node_count': 1, - 'name': clusterid - } - ] - }, - 'nfs', - 'cs-mgmt:/volumes/cs-data/primary', - poolfsuuid, - poolfsnfsbaseuuid - ) - print("create cluster") - server.create_cluster(poolfsuuid,) - - poolDom = parseString(server.discover_server_pool()) - for node in poolDom.getElementsByTagName('Server_Pool'): - id = node.getElementsByTagName('Unique_Id')[0].firstChild.nodeValue - alias = node.getElementsByTagName('Pool_Alias')[0].firstChild.nodeValue - mvip = node.getElementsByTagName('Primary_Virtual_Ip')[0].firstChild.nodeValue - print("pool: %s, %s, %s" % (id, mvip, alias)) - members = node.getElementsByTagName('Member') - for member in members: - mip = member.getElementsByTagName('Registered_IP')[0].firstChild.nodeValue - print("member: %s" % mip) - - print(server.is_cluster_online()) - print(server.discover_cluster()) - print(server.discover_pool_filesystem()) - print(server.discover_server_pool()) - # server.destroy_server_pool(pooluuid) - -except Error as v: - print("ERROR", v) diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/info.py b/plugins/hypervisors/ovm3/src/test/resources/scripts/info.py deleted file mode 100755 index be2f8b18c9ba..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/info.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# 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. -# -import os, sys, subprocess, socket,fcntl, struct -from socket import gethostname -import errno -from socket import error as socket_error -from xml.dom.minidom import parseString - -from xmlrpclib import ServerProxy, Error - -def spCon(proto, auth, host, port): - print "trying %s on %s@%s:%s" % (proto, auth, host, port) - try: - x=ServerProxy("%s://%s@%s:%s" % (proto, auth, host, port)) - x.echo(proto) - return x - except Error, v: - return - except socket_error, serr: - return - -def getCon(auth, host, port): - try: - server = spCon("http", auth, host, port) - if server: - return server - else: - server = spCon("https", auth, host, port) - except Error, v: - print "ERROR", v - return server - -def get_ip_address(ifname): - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - return socket.inet_ntoa(fcntl.ioctl( - s.fileno(), - 0x8915, # SIOCGIFADDR - struct.pack('256s', ifname[:15]) - )[20:24]) - -def is_it_up(host, port): - try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(1) - s.connect((host, port)) - s.close() - except: - print "host: %s:%s DOWN" % (host, port) - return False - - print "host: %s:%s UP" % (host, port) - return True - -# hmm primary actions don't apply to a secondary -primary="192.168.1.161" -port=8899 -user = "oracle" -password = "test123" -auth = "%s:%s" % (user, password) -server = getCon(auth, 'localhost', port) -mserver = getCon(auth, primary, port) -poolNode=True -interface = "c0a80100" -role='xen,utility' -hostname=gethostname() -ip = get_ip_address(interface) -poolMembers = [] -xserver = server -poolCount = 0 - -try: - print server.discover_pool_filesystem() - print - print server.discover_server_pool() - poolDom = parseString(server.discover_server_pool()) - for node in poolDom.getElementsByTagName('Server_Pool'): - id = node.getElementsByTagName('Unique_Id')[0].firstChild.nodeValue - alias = node.getElementsByTagName('Pool_Alias')[0].firstChild.nodeValue - mvip = node.getElementsByTagName('Primary_Virtual_Ip')[0].firstChild.nodeValue - print "pool: %s, %s, %s" % (id, mvip, alias) - members = node.getElementsByTagName('Member') - for member in members: - poolCount = poolCount + 1 - mip = member.getElementsByTagName('Registered_IP')[0].firstChild.nodeValue - print "member: %s" % (mip) - if mip == ip: - pooled = True - else: - poolMembers.append(mip) - - # print server.discover_server() - -except Error, v: - print "ERROR", v diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/password.py b/plugins/hypervisors/ovm3/src/test/resources/scripts/password.py deleted file mode 100755 index c8ab89e7a638..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/password.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# 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. -# -import os, sys, subprocess, socket, fcntl, struct -from socket import gethostname -from xml.dom.minidom import parseString - -from xmlrpclib import ServerProxy, Error - -def spCon(proto, host, port): - print "trying %s on %s:%s" % (proto, host, port) - try: - x = ServerProxy("%s://%s:%s" % (proto, host, port)) - x.echo(proto) - return x - except Error, v: - print "ERROR", v - return - -def getCon(host, port): - try: - server = spCon("http", host, port) - except Error, v: - print "ERROR", v - server = spCon("https", host, port) - - return server - -# hmm primary actions don't apply to a secondary -port = 8899 -user = "oracle" -password = "test123" -auth = "%s:%s" % (user, password) -host = "localhost" - -print "setting up password" -try: - con = getCon(host, port) - print con.update_agent_password(user, password) -except Error, v: - print "ERROR", v diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/repo_pool.py b/plugins/hypervisors/ovm3/src/test/resources/scripts/repo_pool.py deleted file mode 100755 index f9a47dbf68c0..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/repo_pool.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/python -# -# 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. -# -import os, sys, subprocess, socket, fcntl, struct -from socket import gethostname -from xml.dom.minidom import parseString - -from xmlrpclib import ServerProxy, Error - -def get_ip_address(ifname): - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - return socket.inet_ntoa(fcntl.ioctl( - s.fileno(), - 0x8915, # SIOCGIFADDR - struct.pack('256s', ifname[:15]) - )[20:24]) - -def is_it_up(host, port): - try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(1) - s.connect((host, port)) - s.close() - except: - print "host: %s:%s DOWN" % (host, port) - return False - - print "host: %s:%s UP" % (host, port) - return True - -# hmm primary actions don't apply to a secondary -primary = "192.168.1.161" -port = 8899 -user = "oracle" -password = "*******" -auth = "%s:%s" % (user, password) -server = ServerProxy("http://%s:%s" % ("localhost", port)) -mserver = ServerProxy("http://%s@%s:%s" % (auth, primary, port)) -poolNode = True -interface = "c0a80100" -role = 'xen,utility' -hostname = gethostname() -ip = get_ip_address(interface) -poolMembers = [] -xserver = server - -print "setting up password" -server.update_agent_password(user, password) - -if (is_it_up(primary, port)): - print "primary seems to be up, will become secondary" - xserver = mserver -else: - print "no primary yet, will become primary" - -# other mechanism must be used to make interfaces equal... -try: - # pooling related same as primary storage! - poolalias = "Pool 0" - poolid = "0004fb0000020000ba9aaf00ae5e2d73" - poolfsnfsbaseuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a" - pooluuid = poolid - poolfsuuid = poolid - clusterid = "ba9aaf00ae5e2d72" - mgr = "d1a749d4295041fb99854f52ea4dea97" - poolmvip = primary - - poolfsnfsbaseuuid = "6824e646-5908-48c9-ba44-bb1a8a778084" - repoid = "6824e646590848c9ba44bb1a8a778084" - poolid = repoid - repo = "/OVS/Repositories/%s" % (repoid) - repomount = "cs-mgmt:/volumes/cs-data/secondary" - - # primary - primuuid = "7718562d872f47a7b4548f9cac4ffa3a" - ssuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a" - fshost = "cs-mgmt" - fstarget = "/volumes/cs-data/primary" - fstype = "nfs" - fsname = "Primary storage" - fsmntpoint = "%s:%s" % (fshost, fstarget) - fsmnt = "/nfsmnt/%s" % (ssuuid) - fsplugin = "oracle.generic.NFSPlugin.GenericNFSPlugin" - - # set the basics we require to "operate" - print server.take_ownership(mgr, '') - print server.update_server_roles(role,) - - # if we're pooling pool... - if (poolNode == True): - poolCount = 0 - pooled = False - - # check pooling - try: - poolDom = parseString(xserver.discover_server_pool()) - print xserver.discover_server_pool() - for node in poolDom.getElementsByTagName('Server_Pool'): - id = node.getElementsByTagName('Unique_Id')[0].firstChild.nodeValue - alias = node.getElementsByTagName('Pool_Alias')[0].firstChild.nodeValue - mvip = node.getElementsByTagName('Primary_Virtual_Ip')[0].firstChild.nodeValue - print "pool: %s, %s, %s" % (id, mvip, alias) - members = node.getElementsByTagName('Member') - for member in members: - poolCount = poolCount + 1 - mip = member.getElementsByTagName('Registered_IP')[0].firstChild.nodeValue - print "member: %s" % (mip) - if mip == ip: - pooled = True - else: - poolMembers.append(mip) - - except Error, v: - print "no primary will become primary, %s" % v - - if (pooled == False): - # setup the repository - print "setup repo" - print server.mount_repository_fs(repomount, repo) - try: - print "adding repo" - print server.add_repository(repomount, repo) - except Error, v: - print "will create the repo, as it's not there", v - print server.create_repository(repomount, repo, repoid, "repo") - - print "not pooled!" - if (poolCount == 0): - print "no pool yet, create it" - # check if a pool exists already if not create - # pool if so add us to the pool - print "create pool fs" - print server.create_pool_filesystem( - fstype, - "%s/VirtualMachines/" % repomount, - clusterid, - poolfsuuid, - poolfsnfsbaseuuid, - mgr, - pooluuid - ) - print "create pool" - print server.create_server_pool(poolalias, - pooluuid, - poolmvip, - poolCount, - hostname, - ip, - role - ) - else: - print "join the pool" - print server.join_server_pool(poolalias, - pooluuid, - poolmvip, - poolCount, - hostname, - ip, - role - ) - - # add member to ip list ? - poolMembers.append(ip) - print "mambers for pool: %s" % poolMembers - print xserver.set_pool_member_ip_list(poolMembers) - - print server.discover_server_pool() - -except Error, v: - print "ERROR", v diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/simple_pool.py b/plugins/hypervisors/ovm3/src/test/resources/scripts/simple_pool.py deleted file mode 100755 index 4ded83ef0053..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/simple_pool.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/usr/bin/python -# -# 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. -# -import os, sys, subprocess, socket, fcntl, struct -from socket import gethostname -from xml.dom.minidom import parseString -import errno -from socket import error as socket_error - -from xmlrpclib import ServerProxy, Error - -def spCon(proto, auth, host, port): - print "trying %s on %s@%s:%s" % (proto, auth, host, port) - try: - x = ServerProxy("%s://%s@%s:%s" % (proto, auth, host, port)) - x.echo(proto) - return x - except Error, v: - return - except socket_error, serr: - return - -def getCon(auth, host, port): - try: - server = spCon("http", auth, host, port) - if server: - return server - else: - server = spCon("https", auth, host, port) - except Error, v: - print "ERROR", v - return server - -def get_ip_address(ifname): - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - return socket.inet_ntoa(fcntl.ioctl( - s.fileno(), - 0x8915, # SIOCGIFADDR - struct.pack('256s', ifname[:15]) - )[20:24]) - -# hmm primary actions don't apply to a secondary -primary = "192.168.1.161" -port = 8899 -passw = 'test123' -user = 'oracle' -auth = "%s:%s" % (user, passw) -server = getCon(auth, "localhost", port) -mserver = getCon(auth, primary, port) -try: - mserver.echo("test") -except AttributeError, v: - print "no mserver, becoming mserver" - mserver = server - -poolNode = True -interface = "c0a80100" -role = 'xen,utility' -hostname = gethostname() -ip = get_ip_address(interface) -nodes = [] - -try: - # pooling related same as primary storage! - poolalias = "Pool 0" - clusterid = "ba9aaf00ae5e2d72" - mgr = "d1a749d4295041fb99854f52ea4dea97" - poolmvip = primary - - # primary - primuuid = "7718562d872f47a7b4548f9cac4ffa3a" - ssuuid = "7718562d-872f-47a7-b454-8f9cac4ffa3a" - fshost = "cs-mgmt" - fstarget = "/volumes/cs-data/primary/ovm" - fstype = "nfs" - fsname = "Primary storage" - fsmntpoint = "%s:%s" % (fshost, fstarget) - fsmntpoint2 = "%s:%s" % (fshost, "/volumes/cs-data/secondary") - fsmntpoint = "%s/VirtualMachines" % (fsmntpoint2) - fsmnt = "/nfsmnt/%s" % (ssuuid) - fsplugin = "oracle.generic.NFSPlugin.GenericNFSPlugin" - repo = "/OVS/Repositories/%s" % (primuuid) - - # set the basics we require to "operate" - print server.take_ownership(mgr, '') - print server.update_server_roles(role,) - - # setup the repository - print server.mount_repository_fs(fsmntpoint2, repo) - try: - print server.add_repository(fsmntpoint2, repo) - except Error, v: - print "will create the repo, as it's not there", v - print server.create_repository(fsmntpoint2, repo, primuuid, "A repository") - - # if we're pooling pool... - if (poolNode == True): - poolCount = 0 - pooled = False - - # check pooling - poolDom = parseString(mserver.discover_server_pool()) - for node in poolDom.getElementsByTagName('Server_Pool'): - id = node.getElementsByTagName('Unique_Id')[0].firstChild.nodeValue - alias = node.getElementsByTagName('Pool_Alias')[0].firstChild.nodeValue - mvip = node.getElementsByTagName('Primary_Virtual_Ip')[0].firstChild.nodeValue - print "pool: %s, %s, %s" % (id, mvip, alias) - members = node.getElementsByTagName('Member') - for member in members: - poolCount = poolCount + 1 - mip = member.getElementsByTagName('Registered_IP')[0].firstChild.nodeValue - if (mip == ip): - pooled = True - else: - nodes.append(mip) - print "member: %s" % (mip) - - # if (pooled == False): - try: - if (poolCount == 0): - print "primary" - # check if a pool exists already if not create - # pool if so add us to the pool - print server.configure_virtual_ip(primary, ip) - print server.create_pool_filesystem( - fstype, - fsmntpoint, - clusterid, - primuuid, - ssuuid, - mgr, - primuuid - ) - print server.create_server_pool(poolalias, - primuuid, - poolmvip, - poolCount, - hostname, - ip, - role - ) - else: - try: - print "secondary" - print server.join_server_pool(poolalias, - primuuid, - poolmvip, - poolCount, - hostname, - ip, - role - ) - except Error, v: - print "host already part of pool?: %s" % (v) - - nodes.append(ip) - for node in nodes: - # con = getCon(auth, node, port) - # print con.set_pool_member_ip_list(nodes); - print mserver.dispatch("http://%s@%s:%s/api/3" % (auth, node, port), "set_pool_member_ip_list", nodes) - # print server.configure_virtual_ip(primary, ip) - except Error, e: - print "something went wrong: %s" % (e) - - # sys.exit() - # mount the primary fs - print server.storage_plugin_mount( - fsplugin, - { - 'uuid': primuuid, - 'storage_desc': fsname, - 'access_host': fshost, - 'storage_type': 'FileSys', - 'name':primuuid - }, - { - 'status': '', - 'uuid': ssuuid, - 'ss_uuid': primuuid, - 'size': 0, - 'state': 1, - 'access_grp_names': [], - 'access_path': fsmntpoint, - 'name': fsname - }, - fsmnt, - '', - True, - [] - ) - -except Error, v: - print "ERROR", v diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/socat.sh b/plugins/hypervisors/ovm3/src/test/resources/scripts/socat.sh deleted file mode 100755 index 6072bb64644d..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/socat.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -# 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. - -CERT="/etc/ovs-agent/cert" -socat OPENSSL-LISTEN:8899,reuseaddr,fork,verify=0,key=$CERT/key.pem,cert=$CERT/certificate.pem TCP:localhost:8898 & diff --git a/plugins/hypervisors/ovm3/src/test/resources/scripts/tail.sh b/plugins/hypervisors/ovm3/src/test/resources/scripts/tail.sh deleted file mode 100755 index 458f3ec74bad..000000000000 --- a/plugins/hypervisors/ovm3/src/test/resources/scripts/tail.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash - -# 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. - -cd /var/log -tail -f ovm-consoled.log devmon.log messages ovs-agent.log ovmwatch.log diff --git a/plugins/hypervisors/ucs/pom.xml b/plugins/hypervisors/ucs/pom.xml deleted file mode 100644 index 67bde3b64294..000000000000 --- a/plugins/hypervisors/ucs/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - 4.0.0 - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - cloud-plugin-hypervisor-ucs - Apache CloudStack Plugin - Hypervisor UCS - http://maven.apache.org - - - org.apache.cloudstack - cloud-utils - ${project.version} - - - org.apache.cloudstack - cloud-api - ${project.version} - - - diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDao.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDao.java deleted file mode 100644 index a0f5563e180f..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDao.java +++ /dev/null @@ -1,24 +0,0 @@ -// 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.ucs.database; - -import com.cloud.utils.db.GenericDao; - -public interface UcsBladeDao extends GenericDao { - -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDaoImpl.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDaoImpl.java deleted file mode 100644 index b3aea1eafb43..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeDaoImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -// 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.ucs.database; - - -import com.cloud.utils.db.DB; -import com.cloud.utils.db.GenericDaoBase; - -@DB() -public class UcsBladeDaoImpl extends GenericDaoBase implements UcsBladeDao { - -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeVO.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeVO.java deleted file mode 100644 index 233a7782d156..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsBladeVO.java +++ /dev/null @@ -1,102 +0,0 @@ -// 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.ucs.database; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - -@Entity -@Table(name = "ucs_blade") -public class UcsBladeVO implements InternalIdentity, Identity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "ucs_manager_id") - private long ucsManagerId; - - @Column(name = "host_id") - private Long hostId; - - @Column(name = "dn") - private String dn; - - @Column(name = "profile_dn") - private String profileDn; - - @Override - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public long getUcsManagerId() { - return ucsManagerId; - } - - public void setUcsManagerId(long ucsManagerId) { - this.ucsManagerId = ucsManagerId; - } - - public Long getHostId() { - return hostId; - } - - public void setHostId(Long hostId) { - this.hostId = hostId; - } - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } - - @Override - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getProfileDn() { - return profileDn; - } - - public void setProfileDn(String profileDn) { - this.profileDn = profileDn; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDao.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDao.java deleted file mode 100644 index 5ffabeb633b3..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDao.java +++ /dev/null @@ -1,23 +0,0 @@ -// 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.ucs.database; - -import com.cloud.utils.db.GenericDao; - -public interface UcsManagerDao extends GenericDao { -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDaoImpl.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDaoImpl.java deleted file mode 100644 index 16f093acea0a..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerDaoImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -// 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.ucs.database; - - -import com.cloud.utils.db.DB; -import com.cloud.utils.db.GenericDaoBase; - -@DB() -public class UcsManagerDaoImpl extends GenericDaoBase implements UcsManagerDao { -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerVO.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerVO.java deleted file mode 100644 index 110b1ae83c6a..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/database/UcsManagerVO.java +++ /dev/null @@ -1,116 +0,0 @@ -// 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.ucs.database; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - -import com.cloud.utils.db.Encrypt; - -@Entity -@Table(name = "ucs_manager") -public class UcsManagerVO implements InternalIdentity, Identity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "zone_id") - private long zoneId; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "name") - private String name; - - @Column(name = "url") - private String url; - - @Column(name = "username") - private String username; - - @Encrypt - @Column(name = "password") - private String password; - - @Override - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - @Override - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public long getZoneId() { - return zoneId; - } - - public void setZoneId(long zoneId) { - this.zoneId = zoneId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/StringTemplate.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/StringTemplate.java deleted file mode 100644 index 2ce8e01302da..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/StringTemplate.java +++ /dev/null @@ -1,39 +0,0 @@ -// 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.ucs.manager; - -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class StringTemplate { - public static String replaceTokens(String text, Map replacements) { - Pattern pattern = Pattern.compile("\\[(.+?)\\]"); - Matcher matcher = pattern.matcher(text); - StringBuffer buffer = new StringBuffer(); - while (matcher.find()) { - String replacement = replacements.get(matcher.group(1)); - if (replacement != null) { - matcher.appendReplacement(buffer, ""); - buffer.append(replacement); - } - } - matcher.appendTail(buffer); - return buffer.toString(); - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsCommands.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsCommands.java deleted file mode 100644 index 5d88c67fbb7e..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsCommands.java +++ /dev/null @@ -1,107 +0,0 @@ -// 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.ucs.manager; - -import com.cloud.utils.xmlobject.XmlObject; - -public class UcsCommands { - public static String loginCmd(String username, String password) { - XmlObject cmd = new XmlObject("aaaLogin"); - cmd.putElement("inName", username); - cmd.putElement("inPassword", password); - return cmd.dump(); - } - - public static String refreshCmd(String username, String password, String cookie) { - XmlObject cmd = new XmlObject("aaaRefresh"); - cmd.putElement("inName", username); - cmd.putElement("inPassword", password); - cmd.putElement("inCookie", cookie); - return cmd.dump(); - } - - public static String listComputeBlades(String cookie) { - XmlObject cmd = new XmlObject("configResolveClass"); - cmd.putElement("classId", "computeBlade"); - cmd.putElement("cookie", cookie); - cmd.putElement("inHierarchical", "false"); - return cmd.dump(); - } - - public static String listProfiles(String cookie) { - XmlObject cmd = new XmlObject("configFindDnsByClassId"); - cmd.putElement("classId", "lsServer"); - cmd.putElement("cookie", cookie); - return cmd.dump(); - } - - public static String cloneProfile(String cookie, String srcDn, String newProfileName) { - XmlObject cmd = new XmlObject("lsClone"); - cmd.putElement("cookie", cookie); - cmd.putElement("dn", srcDn); - cmd.putElement("inTargetOrg", "org-root"); - cmd.putElement("inServerName", newProfileName); - cmd.putElement("inHierarchical", "false"); - return cmd.dump(); - } - - public static String configResolveDn(String cookie, String dn) { - XmlObject cmd = new XmlObject("configResolveDn"); - cmd.putElement("cookie", cookie); - cmd.putElement("dn", dn); - return cmd.toString(); - } - - public static String associateProfileToBlade(String cookie, String profileDn, String bladeDn) { - XmlObject cmd = - new XmlObject("configConfMos").putElement("cookie", cookie) - .putElement("inHierarchical", "true") - .putElement( - "inConfigs", - new XmlObject("inConfigs").putElement( - "pair", - new XmlObject("pair").putElement("key", profileDn).putElement( - "lsServer", - new XmlObject("lsServer").putElement("agentPolicyName", "") - .putElement("biosProfileName", "") - .putElement("bootPolicyName", "") - .putElement("descr", "") - .putElement("dn", profileDn) - .putElement("dynamicConPolicyName", "") - .putElement("extIPState", "none") - .putElement("hostFwPolicyName", "") - .putElement("identPoolName", "") - .putElement("localDiskPolicyName", "") - .putElement("maintPolicyName", "") - .putElement("mgmtAccessPolicyName", "") - .putElement("mgmtFwPolicyName", "") - .putElement("powerPolicyName", "") - .putElement("scrubPolicyName", "") - .putElement("solPolicyName", "") - .putElement("srcTemplName", "") - .putElement("statsPolicyName", "default") - .putElement("status", "") - .putElement("usrLbl", "") - .putElement("uuid", "") - .putElement("vconProfileName", "") - .putElement("lsBinding", - new XmlObject("lsBinding").putElement("pnDn", bladeDn).putElement("restrictMigration", "no").putElement("rn", "pn"))))); - - return cmd.dump(); - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsHttpClient.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsHttpClient.java deleted file mode 100644 index 16d21f07d4a9..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsHttpClient.java +++ /dev/null @@ -1,78 +0,0 @@ -// 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.ucs.manager; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.URI; -import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.httpclient.protocol.Protocol; - -import com.cloud.utils.exception.CloudRuntimeException; - -public class UcsHttpClient { - private static HttpClient client = new HttpClient(); - private static Protocol ucsHttpsProtocol = new org.apache.commons.httpclient.protocol.Protocol("https", new EasySSLProtocolSocketFactory(), 443); - private final String url; - - public UcsHttpClient(String ip) { - url = String.format("http://%s/nuova", ip); - Protocol.registerProtocol("https", ucsHttpsProtocol); - } - - public String call(String xml) { - PostMethod post = new PostMethod(url); - post.setRequestEntity(new StringRequestEntity(xml)); - post.setRequestHeader("content-type", "text/xml"); - //post.setFollowRedirects(true); - try { - int result = client.executeMethod(post); - if (result == 302) { - // Handle HTTPS redirect - // Ideal way might be to configure from add manager API - // for using either HTTP / HTTPS - // Allow only one level of redirect - String redirectLocation; - Header locationHeader = post.getResponseHeader("location"); - if (locationHeader != null) { - redirectLocation = locationHeader.getValue(); - } else { - throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager"); - } - post.setURI(new URI(redirectLocation)); - result = client.executeMethod(post); - } - // Check for errors - if (result != 200) { - throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString()); - } - String res = post.getResponseBodyAsString(); - if (res.contains("errorCode")) { - String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res); - throw new CloudRuntimeException(err); - } - return res; - } catch (Exception e) { - throw new CloudRuntimeException(e.getMessage(), e); - } finally { - post.releaseConnection(); - } - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManager.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManager.java deleted file mode 100644 index 24356172a9e3..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManager.java +++ /dev/null @@ -1,45 +0,0 @@ -// 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.ucs.manager; - -import org.apache.cloudstack.api.AddUcsManagerCmd; -import org.apache.cloudstack.api.AssociateUcsProfileToBladeCmd; -import org.apache.cloudstack.api.ListUcsBladeCmd; -import org.apache.cloudstack.api.ListUcsManagerCmd; -import org.apache.cloudstack.api.ListUcsProfileCmd; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.UcsBladeResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; -import org.apache.cloudstack.api.response.UcsProfileResponse; - -import com.cloud.utils.component.Manager; -import com.cloud.utils.component.PluggableService; - -public interface UcsManager extends Manager, PluggableService { - UcsManagerResponse addUcsManager(AddUcsManagerCmd cmd); - - ListResponse listUcsProfiles(ListUcsProfileCmd cmd); - - ListResponse listUcsManager(ListUcsManagerCmd cmd); - - UcsBladeResponse associateProfileToBlade(AssociateUcsProfileToBladeCmd cmd); - - ListResponse listUcsBlades(ListUcsBladeCmd cmd); - - void deleteUcsManager(Long id); -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManagerImpl.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManagerImpl.java deleted file mode 100644 index 6127ed012f35..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/manager/UcsManagerImpl.java +++ /dev/null @@ -1,512 +0,0 @@ -// 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.ucs.manager; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.api.AddUcsManagerCmd; -import org.apache.cloudstack.api.AssociateUcsProfileToBladeCmd; -import org.apache.cloudstack.api.DeleteUcsManagerCmd; -import org.apache.cloudstack.api.ListUcsBladeCmd; -import org.apache.cloudstack.api.ListUcsManagerCmd; -import org.apache.cloudstack.api.ListUcsProfileCmd; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.UcsBladeResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; -import org.apache.cloudstack.api.response.UcsProfileResponse; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.managed.context.ManagedContextRunnable; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.configuration.Config; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.resource.ResourceService; -import com.cloud.ucs.database.UcsBladeDao; -import com.cloud.ucs.database.UcsBladeVO; -import com.cloud.ucs.database.UcsManagerDao; -import com.cloud.ucs.database.UcsManagerVO; -import com.cloud.ucs.structure.ComputeBlade; -import com.cloud.ucs.structure.UcsCookie; -import com.cloud.ucs.structure.UcsProfile; -import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.QueryBuilder; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.xmlobject.XmlObject; -import com.cloud.utils.xmlobject.XmlObjectParser; - -public class UcsManagerImpl implements UcsManager { - protected Logger logger = LogManager.getLogger(getClass()); - public static final Long COOKIE_TTL = TimeUnit.MILLISECONDS.convert(100L, TimeUnit.MINUTES); - public static final Long COOKIE_REFRESH_TTL = TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES); - - @Inject - private UcsManagerDao ucsDao; - @Inject - private ResourceService resourceService; - @Inject - private ClusterDao clusterDao; - @Inject - private ClusterDetailsDao clusterDetailsDao; - @Inject - private UcsBladeDao bladeDao; - @Inject - private HostDao hostDao; - @Inject - private DataCenterDao dcDao; - @Inject - private ConfigurationDao configDao; - - private final Map cookies = new HashMap(); - private String name; - private int runLevel; - private Map params; - private ScheduledExecutorService syncBladesExecutor; - private int syncBladeInterval; - - private class SyncBladesThread extends ManagedContextRunnable { - - private void discoverNewBlades(Map previous, Map now, UcsManagerVO mgr) { - for (Map.Entry e : now.entrySet()) { - String dn = e.getKey(); - if (previous.keySet().contains(dn)) { - continue; - } - - ComputeBlade nc = e.getValue(); - UcsBladeVO vo = new UcsBladeVO(); - vo.setDn(nc.getDn()); - vo.setUcsManagerId(mgr.getId()); - vo.setUuid(UUID.randomUUID().toString()); - bladeDao.persist(vo); - logger.debug(String.format("discovered a new UCS blade[dn:%s] during sync", nc.getDn())); - } - } - - private void decommissionFadedBlade(Map previous, Map now) { - for (Map.Entry e : previous.entrySet()) { - String dn = e.getKey(); - if (now.keySet().contains(dn)) { - continue; - } - - UcsBladeVO vo = e.getValue(); - bladeDao.remove(vo.getId()); - logger.debug(String.format("decommission faded blade[dn:%s] during sync", vo.getDn())); - } - } - - private void syncBlades(UcsManagerVO mgr) { - QueryBuilder q = QueryBuilder.create(UcsBladeVO.class); - q.and(q.entity().getUcsManagerId(), Op.EQ, mgr.getId()); - List pblades = q.list(); - if (pblades.isEmpty()) { - return; - } - - Map previousBlades = new HashMap(pblades.size()); - for (UcsBladeVO b : pblades) { - previousBlades.put(b.getDn(), b); - } - - List cblades = listBlades(mgr.getId()); - Map currentBlades = new HashMap(cblades.size()); - for (ComputeBlade c : cblades) { - currentBlades.put(c.getDn(), c); - } - - discoverNewBlades(previousBlades, currentBlades, mgr); - decommissionFadedBlade(previousBlades, currentBlades); - } - - @Override - protected void runInContext() { - try { - List mgrs = ucsDao.listAll(); - for (UcsManagerVO mgr : mgrs) { - syncBlades(mgr); - } - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - return true; - } - - @Override - public boolean start() { - try { - syncBladeInterval = Integer.parseInt(configDao.getValue(Config.UCSSyncBladeInterval.key())); - } catch (NumberFormatException e) { - syncBladeInterval = 600; - } - syncBladesExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("UCS-SyncBlades")); - syncBladesExecutor.scheduleAtFixedRate(new SyncBladesThread(), syncBladeInterval, syncBladeInterval, TimeUnit.SECONDS); - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return name; - } - - private void discoverBlades(UcsManagerVO ucsMgrVo) { - List blades = listBlades(ucsMgrVo.getId()); - for (ComputeBlade b : blades) { - UcsBladeVO vo = new UcsBladeVO(); - vo.setDn(b.getDn()); - vo.setUcsManagerId(ucsMgrVo.getId()); - vo.setUuid(UUID.randomUUID().toString()); - bladeDao.persist(vo); - } - } - - @Override - @DB - public UcsManagerResponse addUcsManager(AddUcsManagerCmd cmd) { - QueryBuilder q = QueryBuilder.create(UcsManagerVO.class); - q.and(q.entity().getUrl(), Op.EQ, cmd.getUrl()); - UcsManagerVO mgrvo = q.find(); - if (mgrvo != null) { - throw new IllegalArgumentException(String.format("duplicate UCS manager. url[%s] is used by another UCS manager already", cmd.getUrl())); - } - - try { - UcsManagerVO vo = new UcsManagerVO(); - vo.setUuid(UUID.randomUUID().toString()); - vo.setPassword(cmd.getPassword()); - vo.setUrl(cmd.getUrl()); - vo.setUsername(cmd.getUsername()); - vo.setZoneId(cmd.getZoneId()); - vo.setName(cmd.getName()); - - mgrvo = ucsDao.persist(vo); - UcsManagerResponse rsp = new UcsManagerResponse(); - rsp.setId(String.valueOf(vo.getId())); - rsp.setName(vo.getName()); - rsp.setUrl(vo.getUrl()); - rsp.setZoneId(String.valueOf(vo.getZoneId())); - - discoverBlades(vo); - return rsp; - } catch (CloudRuntimeException e) { - if (mgrvo != null) { - ucsDao.remove(mgrvo.getId()); - } - throw e; - } - } - - private String getCookie(Long ucsMgrId) { - try { - UcsCookie ucsCookie = cookies.get(ucsMgrId); - long currentTime = System.currentTimeMillis(); - UcsManagerVO mgrvo = ucsDao.findById(ucsMgrId); - UcsHttpClient client = new UcsHttpClient(mgrvo.getUrl()); - String cmd = null; - if (ucsCookie == null) { - cmd = UcsCommands.loginCmd(mgrvo.getUsername(), mgrvo.getPassword()); - } else { - String cookie = ucsCookie.getCookie(); - long cookieStartTime = ucsCookie.getStartTime(); - if (currentTime - cookieStartTime > COOKIE_TTL) { - cmd = UcsCommands.loginCmd(mgrvo.getUsername(), mgrvo.getPassword()); - } else if (currentTime - cookieStartTime > COOKIE_REFRESH_TTL) { - cmd = UcsCommands.refreshCmd(mgrvo.getUsername(), mgrvo.getPassword(), cookie); - } - } - if (!(cmd == null)) { - String ret = client.call(cmd); - XmlObject xo = XmlObjectParser.parseFromString(ret); - String cookie = xo.get("outCookie"); - ucsCookie = new UcsCookie(cookie, currentTime); - cookies.put(ucsMgrId, ucsCookie); - //cookiesTime.put(cookie, currentTime); //This is currentTime on purpose, and not latest time. - } - return ucsCookie.getCookie(); - } catch (Exception e) { - throw new CloudRuntimeException("Cannot get cookie", e); - } - } - - private List listBlades(Long ucsMgrId) { - String cookie = getCookie(ucsMgrId); - UcsManagerVO mgrvo = ucsDao.findById(ucsMgrId); - UcsHttpClient client = new UcsHttpClient(mgrvo.getUrl()); - String cmd = UcsCommands.listComputeBlades(cookie); - String ret = client.call(cmd); - return ComputeBlade.fromXmString(ret); - } - - private List getUcsProfiles(Long ucsMgrId) { - String cookie = getCookie(ucsMgrId); - UcsManagerVO mgrvo = ucsDao.findById(ucsMgrId); - String cmd = UcsCommands.listProfiles(cookie); - UcsHttpClient client = new UcsHttpClient(mgrvo.getUrl()); - String res = client.call(cmd); - List profiles = UcsProfile.fromXmlString(res); - return profiles; - } - - @Override - public ListResponse listUcsProfiles(ListUcsProfileCmd cmd) { - List profiles = getUcsProfiles(cmd.getUcsManagerId()); - ListResponse response = new ListResponse(); - List rs = new ArrayList(); - for (UcsProfile p : profiles) { - UcsProfileResponse r = new UcsProfileResponse(); - r.setObjectName("ucsprofile"); - r.setDn(p.getDn()); - rs.add(r); - } - response.setResponses(rs); - return response; - } - - private String cloneProfile(Long ucsMgrId, String srcDn, String newProfileName) { - UcsManagerVO mgrvo = ucsDao.findById(ucsMgrId); - UcsHttpClient client = new UcsHttpClient(mgrvo.getUrl()); - String cookie = getCookie(ucsMgrId); - String cmd = UcsCommands.cloneProfile(cookie, srcDn, newProfileName); - String res = client.call(cmd); - XmlObject xo = XmlObjectParser.parseFromString(res); - return xo.get("outConfig.lsServer.dn"); - } - - private boolean isProfileAssociated(Long ucsMgrId, String dn) { - UcsManagerVO mgrvo = ucsDao.findById(ucsMgrId); - UcsHttpClient client = new UcsHttpClient(mgrvo.getUrl()); - String cookie = getCookie(ucsMgrId); - String cmd = UcsCommands.configResolveDn(cookie, dn); - String res = client.call(cmd); - XmlObject xo = XmlObjectParser.parseFromString(res); - logger.debug(String.format("association response is %s", res)); - - if (xo.get("outConfig.computeBlade.association").equals("none")) { - throw new CloudRuntimeException(String.format("cannot associated a profile to blade[dn:%s]. please check your UCS manasger for detailed error information", - dn)); - } - - return xo.get("outConfig.computeBlade.association").equals("associated"); - } - - @Override - public UcsBladeResponse associateProfileToBlade(AssociateUcsProfileToBladeCmd cmd) { - QueryBuilder q = QueryBuilder.create(UcsBladeVO.class); - q.and(q.entity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); - q.and(q.entity().getId(), Op.EQ, cmd.getBladeId()); - UcsBladeVO bvo = q.find(); - if (bvo == null) { - throw new IllegalArgumentException(String.format("cannot find UCS blade[id:%s, ucs manager id:%s]", cmd.getBladeId(), cmd.getUcsManagerId())); - } - - if (bvo.getHostId() != null) { - throw new CloudRuntimeException(String.format("blade[id:%s, dn:%s] has been associated with host[id:%s]", bvo.getId(), bvo.getDn(), bvo.getHostId())); - } - - UcsManagerVO mgrvo = ucsDao.findById(cmd.getUcsManagerId()); - String cookie = getCookie(cmd.getUcsManagerId()); - String pdn = cloneProfile(mgrvo.getId(), cmd.getProfileDn(), "profile-for-blade-" + bvo.getId()); - String ucscmd = UcsCommands.associateProfileToBlade(cookie, pdn, bvo.getDn()); - UcsHttpClient client = new UcsHttpClient(mgrvo.getUrl()); - String res = client.call(ucscmd); - int count = 0; - int timeout = 600; - while (count < timeout) { - if (isProfileAssociated(mgrvo.getId(), bvo.getDn())) { - break; - } - - try { - TimeUnit.SECONDS.sleep(2); - } catch (InterruptedException e) { - throw new CloudRuntimeException(e); - } - - count += 2; - } - - if (count >= timeout) { - throw new CloudRuntimeException(String.format("associating profile[%s] to balde[%s] timeout after 600 seconds", pdn, bvo.getDn())); - } - - bvo.setProfileDn(pdn); - bladeDao.update(bvo.getId(), bvo); - - UcsBladeResponse rsp = bladeVOToResponse(bvo); - - logger.debug(String.format("successfully associated profile[%s] to blade[%s]", pdn, bvo.getDn())); - return rsp; - } - - private String hostIdToUuid(Long hostId) { - if (hostId == null) { - return null; - } - HostVO vo = hostDao.findById(hostId); - return vo.getUuid(); - } - - private String zoneIdToUuid(Long zoneId) { - DataCenterVO vo = dcDao.findById(zoneId); - return vo.getUuid(); - } - - private String ucsManagerIdToUuid(Long ucsMgrId) { - UcsManagerVO vo = ucsDao.findById(ucsMgrId); - return vo.getUuid(); - } - - @Override - public ListResponse listUcsManager(ListUcsManagerCmd cmd) { - List rsps = new ArrayList(); - ListResponse response = new ListResponse(); - if (cmd.getId() != null) { - UcsManagerVO vo = ucsDao.findById(cmd.getId()); - UcsManagerResponse rsp = new UcsManagerResponse(); - rsp.setObjectName("ucsmanager"); - rsp.setId(vo.getUuid()); - rsp.setName(vo.getName()); - rsp.setUrl(vo.getUrl()); - rsp.setZoneId(zoneIdToUuid(vo.getZoneId())); - rsps.add(rsp); - response.setResponses(rsps); - return response; - } - - QueryBuilder serv = QueryBuilder.create(UcsManagerVO.class); - serv.and(serv.entity().getZoneId(), Op.EQ, cmd.getZoneId()); - List vos = serv.list(); - - for (UcsManagerVO vo : vos) { - UcsManagerResponse rsp = new UcsManagerResponse(); - rsp.setObjectName("ucsmanager"); - rsp.setId(vo.getUuid()); - rsp.setName(vo.getName()); - rsp.setUrl(vo.getUrl()); - rsp.setZoneId(zoneIdToUuid(vo.getZoneId())); - rsps.add(rsp); - } - response.setResponses(rsps); - return response; - } - - private UcsBladeResponse bladeVOToResponse(UcsBladeVO vo) { - UcsBladeResponse rsp = new UcsBladeResponse(); - rsp.setObjectName("ucsblade"); - rsp.setId(vo.getUuid()); - rsp.setDn(vo.getDn()); - rsp.setHostId(hostIdToUuid(vo.getHostId())); - rsp.setAssociatedProfileDn(vo.getProfileDn()); - rsp.setUcsManagerId(ucsManagerIdToUuid(vo.getUcsManagerId())); - return rsp; - } - - @Override - public ListResponse listUcsBlades(ListUcsBladeCmd cmd) { - QueryBuilder serv = QueryBuilder.create(UcsBladeVO.class); - serv.and(serv.entity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); - List vos = serv.list(); - - List rsps = new ArrayList(vos.size()); - for (UcsBladeVO vo : vos) { - UcsBladeResponse rsp = bladeVOToResponse(vo); - rsps.add(rsp); - } - - ListResponse response = new ListResponse(); - response.setResponses(rsps); - - return response; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public void setConfigParams(Map params) { - this.params = params; - } - - @Override - public Map getConfigParams() { - return params; - } - - @Override - public int getRunLevel() { - return runLevel; - } - - @Override - public void setRunLevel(int level) { - runLevel = level; - } - - @Override - public List> getCommands() { - List> cmds = new ArrayList>(); - cmds.add(ListUcsBladeCmd.class); - cmds.add(ListUcsManagerCmd.class); - cmds.add(ListUcsProfileCmd.class); - cmds.add(AddUcsManagerCmd.class); - cmds.add(AssociateUcsProfileToBladeCmd.class); - cmds.add(DeleteUcsManagerCmd.class); - return cmds; - } - - @Override - public void deleteUcsManager(Long id) { - QueryBuilder serv = QueryBuilder.create(UcsBladeVO.class); - serv.and(serv.entity().getUcsManagerId(), Op.EQ, id); - List vos = serv.list(); - for (UcsBladeVO vo : vos) { - bladeDao.remove(vo.getId()); - } - ucsDao.remove(id); - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/ComputeBlade.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/ComputeBlade.java deleted file mode 100644 index bac8efdd8903..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/ComputeBlade.java +++ /dev/null @@ -1,220 +0,0 @@ -// 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.ucs.structure; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.utils.xmlobject.XmlObject; -import com.cloud.utils.xmlobject.XmlObjectParser; - -public class ComputeBlade { - String adminPower; - String adminState; - String assignedToDn; - String association; - String availability; - String availableMemory; - String chassisId; - String dn; - String name; - String numOfAdaptors; - String numOfCores; - String numOfCoresEnabled; - String numOfCpus; - String numOfEthHostIfs; - String numOfFcHostIfs; - String numOfThreads; - String operPower; - String totalMemory; - String uuid; - - public static List fromXmString(String xmlstr) { - XmlObject root = XmlObjectParser.parseFromString(xmlstr); - List lst = root.getAsList("outConfigs.computeBlade"); - List blades = new ArrayList(); - if (lst == null) { - return blades; - } - for (XmlObject xo : lst) { - blades.add(fromXmlObject(xo)); - } - return blades; - } - - public static ComputeBlade fromXmlObject(XmlObject obj) { - ComputeBlade ret = new ComputeBlade(); - return obj.evaluateObject(ret); - } - - public String getAdminPower() { - return adminPower; - } - - public void setAdminPower(String adminPower) { - this.adminPower = adminPower; - } - - public String getAdminState() { - return adminState; - } - - public void setAdminState(String adminState) { - this.adminState = adminState; - } - - public String getAssignedToDn() { - return assignedToDn; - } - - public void setAssignedToDn(String assignedToDn) { - this.assignedToDn = assignedToDn; - } - - public String getAssociation() { - return association; - } - - public void setAssociation(String association) { - this.association = association; - } - - public String getAvailability() { - return availability; - } - - public void setAvailability(String availability) { - this.availability = availability; - } - - public String getAvailableMemory() { - return availableMemory; - } - - public void setAvailableMemory(String availableMemory) { - this.availableMemory = availableMemory; - } - - public String getChassisId() { - return chassisId; - } - - public void setChassisId(String chassisId) { - this.chassisId = chassisId; - } - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getNumOfAdaptors() { - return numOfAdaptors; - } - - public void setNumOfAdaptors(String numOfAdaptors) { - this.numOfAdaptors = numOfAdaptors; - } - - public String getNumOfCores() { - return numOfCores; - } - - public void setNumOfCores(String numOfCores) { - this.numOfCores = numOfCores; - } - - public String getNumOfCoresEnabled() { - return numOfCoresEnabled; - } - - public void setNumOfCoresEnabled(String numOfCoresEnabled) { - this.numOfCoresEnabled = numOfCoresEnabled; - } - - public String getNumOfCpus() { - return numOfCpus; - } - - public void setNumOfCpus(String numOfCpus) { - this.numOfCpus = numOfCpus; - } - - public String getNumOfEthHostIfs() { - return numOfEthHostIfs; - } - - public void setNumOfEthHostIfs(String numOfEthHostIfs) { - this.numOfEthHostIfs = numOfEthHostIfs; - } - - public String getNumOfFcHostIfs() { - return numOfFcHostIfs; - } - - public void setNumOfFcHostIfs(String numOfFcHostIfs) { - this.numOfFcHostIfs = numOfFcHostIfs; - } - - public String getNumOfThreads() { - return numOfThreads; - } - - public void setNumOfThreads(String numOfThreads) { - this.numOfThreads = numOfThreads; - } - - public String getOperPower() { - return operPower; - } - - public void setOperPower(String operPower) { - this.operPower = operPower; - } - - public String getTotalMemory() { - return totalMemory; - } - - public void setTotalMemory(String totalMemory) { - this.totalMemory = totalMemory; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public boolean isAssociated() { - return this.assignedToDn.equals(""); - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsCookie.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsCookie.java deleted file mode 100644 index 560f58417b2a..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsCookie.java +++ /dev/null @@ -1,38 +0,0 @@ -// 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.ucs.structure; - -/* Class to store cookie and associated timestamp for communication with UCS manager*/ -public class UcsCookie { - private final String cookie; - private final Long startTime; - - public UcsCookie(String cookie, Long startTime) { - this.cookie = cookie; - this.startTime = startTime; - } - - public String getCookie() { - return cookie; - } - - public Long getStartTime() { - return startTime; - } - -} diff --git a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsProfile.java b/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsProfile.java deleted file mode 100644 index b3849466f25b..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/com/cloud/ucs/structure/UcsProfile.java +++ /dev/null @@ -1,56 +0,0 @@ -// 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.ucs.structure; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.utils.xmlobject.XmlObject; -import com.cloud.utils.xmlobject.XmlObjectParser; - -public class UcsProfile { - private String dn; - - public static UcsProfile fromXmlObject(XmlObject xo) { - UcsProfile p = new UcsProfile(); - return xo.evaluateObject(p); - } - - public static List fromXmlString(String xmlstr) { - List ps = new ArrayList(); - XmlObject xo = XmlObjectParser.parseFromString(xmlstr); - List xos = xo.getAsList("outDns.dn"); - if (xos != null) { - for (XmlObject x : xos) { - //UcsProfile p = UcsProfile.fromXmlObject(x); - UcsProfile p = new UcsProfile(); - p.setDn(x.get("value").toString()); - ps.add(p); - } - } - return ps; - } - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AddUcsManagerCmd.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AddUcsManagerCmd.java deleted file mode 100644 index 72d693d1d80b..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AddUcsManagerCmd.java +++ /dev/null @@ -1,120 +0,0 @@ -// 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 org.apache.cloudstack.api; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.response.UcsManagerResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.ucs.manager.UcsManager; -import com.cloud.user.Account; - -@APICommand(name = "addUcsManager", description = "Adds a Ucs manager", responseObject = UcsManagerResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddUcsManagerCmd extends BaseCmd { - - @Inject - private UcsManager mgr; - - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, description = "The Zone ID for the ucs manager", entityType = ZoneResponse.class, required = true) - private Long zoneId; - - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "The name of UCS manager") - private String name; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, description = "The name of UCS URL", required = true) - private String url; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "The username of UCS", required = true) - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "The password of UCS", required = true) - private String password; - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - UcsManagerResponse rsp = mgr.addUcsManager(this); - rsp.setObjectName("ucsmanager"); - rsp.setResponseName(getCommandName()); - this.setResponseObject(rsp); - } catch (Exception e) { - logger.warn("Exception: ", e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return "addUcsManagerResponse"; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - public Long getZoneId() { - return zoneId; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AssociateUcsProfileToBladeCmd.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AssociateUcsProfileToBladeCmd.java deleted file mode 100644 index 42e370272ba3..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/AssociateUcsProfileToBladeCmd.java +++ /dev/null @@ -1,100 +0,0 @@ -// 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 org.apache.cloudstack.api; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.response.UcsBladeResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; - -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.ucs.manager.UcsManager; -import com.cloud.user.Account; - -@APICommand(name = "associateUcsProfileToBlade", description = "Associate a profile to a blade", responseObject = UcsBladeResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AssociateUcsProfileToBladeCmd extends BaseAsyncCmd { - - @Inject - private UcsManager mgr; - - @Parameter(name = ApiConstants.UCS_MANAGER_ID, type = CommandType.UUID, description = "UCS manager ID", entityType = UcsManagerResponse.class, required = true) - private Long ucsManagerId; - @Parameter(name = ApiConstants.UCS_PROFILE_DN, type = CommandType.STRING, description = "Profile dn", required = true) - private String profileDn; - @Parameter(name = ApiConstants.UCS_BLADE_ID, type = CommandType.UUID, entityType = UcsBladeResponse.class, description = "Blade ID", required = true) - private Long bladeId; - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - UcsBladeResponse rsp = mgr.associateProfileToBlade(this); - rsp.setResponseName(getCommandName()); - this.setResponseObject(rsp); - } catch (Exception e) { - logger.warn("Exception: ", e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - public Long getUcsManagerId() { - return ucsManagerId; - } - - public void setUcsManagerId(Long ucsManagerId) { - this.ucsManagerId = ucsManagerId; - } - - public String getProfileDn() { - return profileDn; - } - - public void setProfileDn(String profileDn) { - this.profileDn = profileDn; - } - - public Long getBladeId() { - return bladeId; - } - - public void setBladeId(Long bladeId) { - this.bladeId = bladeId; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_UCS_ASSOCIATED_PROFILE; - } - - @Override - public String getEventDescription() { - return "associating a ucs profile to blade"; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/DeleteUcsManagerCmd.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/DeleteUcsManagerCmd.java deleted file mode 100644 index 7d8710aa1405..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/DeleteUcsManagerCmd.java +++ /dev/null @@ -1,76 +0,0 @@ -// 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 org.apache.cloudstack.api; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.ucs.manager.UcsManager; -import com.cloud.user.Account; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteUcsManager", description = "Delete a Ucs manager", responseObject = SuccessResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteUcsManagerCmd extends BaseCmd { - - @Inject - private UcsManager mgr; - - @Parameter(name = ApiConstants.UCS_MANAGER_ID, - type = BaseCmd.CommandType.UUID, - description = "Ucs manager ID", - entityType = UcsManagerResponse.class, - required = true) - private Long ucsManagerId; - - public Long getUcsManagerId() { - return ucsManagerId; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - mgr.deleteUcsManager(ucsManagerId); - SuccessResponse rsp = new SuccessResponse(); - rsp.setResponseName(getCommandName()); - rsp.setObjectName("success"); - this.setResponseObject(rsp); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - throw new CloudRuntimeException(e); - } - } - - @Override - public String getCommandName() { - return "deleteUcsManagerResponse"; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsBladeCmd.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsBladeCmd.java deleted file mode 100644 index f3bb3269b1a9..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsBladeCmd.java +++ /dev/null @@ -1,83 +0,0 @@ -// 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 org.apache.cloudstack.api; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.UcsBladeResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.ucs.manager.UcsManager; -import com.cloud.user.Account; - -@APICommand(name = "listUcsBlades", description = "List ucs blades", responseObject = UcsBladeResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListUcsBladeCmd extends BaseListCmd { - - @Inject - private UcsManager mgr; - - @Parameter(name = ApiConstants.UCS_MANAGER_ID, type = CommandType.UUID, description = "Ucs manager ID", entityType = UcsManagerResponse.class, required = true) - private Long ucsManagerId; - - public UcsManager getMgr() { - return mgr; - } - - public void setMgr(UcsManager mgr) { - this.mgr = mgr; - } - - public Long getUcsManagerId() { - return ucsManagerId; - } - - public void setUcsManagerId(Long ucsManagerId) { - this.ucsManagerId = ucsManagerId; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - ListResponse response = mgr.listUcsBlades(this); - response.setResponseName(getCommandName()); - response.setObjectName("ucsblade"); - this.setResponseObject(response); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return "listucsbladeresponse"; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsManagerCmd.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsManagerCmd.java deleted file mode 100644 index 45a94790c669..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsManagerCmd.java +++ /dev/null @@ -1,95 +0,0 @@ -// 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. -// -// Automatically generated by addcopyright.py at 02/28/2013 -// regarding copyright ownership. The ASF licenses this file -// "License"); you may not use this file except in compliance -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -package org.apache.cloudstack.api; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; -import org.apache.cloudstack.api.response.ZoneResponse; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.ucs.manager.UcsManager; -import com.cloud.user.Account; - -@APICommand(name = "listUcsManagers", description = "List ucs manager", responseObject = UcsManagerResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListUcsManagerCmd extends BaseListCmd { - - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, description = "The zone ID", entityType = ZoneResponse.class) - private Long zoneId; - - @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = UcsManagerResponse.class, description = "The ID of the ucs manager") - private Long id; - - @Inject - private UcsManager mgr; - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - ListResponse response = mgr.listUcsManager(this); - response.setResponseName(getCommandName()); - response.setObjectName("ucsmanager"); - this.setResponseObject(response); - } catch (Exception e) { - logger.warn("Exception: ", e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return "listucsmanagerresponse"; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - public Long getZoneId() { - return zoneId; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsProfileCmd.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsProfileCmd.java deleted file mode 100644 index 8bc1ab490e46..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/ListUcsProfileCmd.java +++ /dev/null @@ -1,81 +0,0 @@ -// 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 org.apache.cloudstack.api; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.UcsManagerResponse; -import org.apache.cloudstack.api.response.UcsProfileResponse; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.ucs.manager.UcsManager; -import com.cloud.user.Account; - -@APICommand(name = "listUcsProfiles", description = "List profile in ucs manager", responseObject = UcsProfileResponse.class, - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListUcsProfileCmd extends BaseListCmd { - - @Inject - UcsManager mgr; - - @Parameter(name = ApiConstants.UCS_MANAGER_ID, - type = CommandType.UUID, - entityType = UcsManagerResponse.class, - description = "The ID for the ucs manager", - required = true) - private Long ucsManagerId; - - public Long getUcsManagerId() { - return ucsManagerId; - } - - public void setUcsManagerId(Long ucsManagerId) { - this.ucsManagerId = ucsManagerId; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - ListResponse response = mgr.listUcsProfiles(this); - response.setResponseName(getCommandName()); - response.setObjectName("ucsprofiles"); - this.setResponseObject(response); - } catch (Exception e) { - logger.warn("Exception: ", e); - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return "listucsprofileresponse"; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsBladeResponse.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsBladeResponse.java deleted file mode 100644 index dbf392677eee..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsBladeResponse.java +++ /dev/null @@ -1,86 +0,0 @@ -// 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 org.apache.cloudstack.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.serializer.Param; -import com.cloud.ucs.database.UcsBladeVO; - -@EntityReference(value = UcsBladeVO.class) -public class UcsBladeResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "UCS blade ID") - private String id; - @SerializedName(ApiConstants.UCS_MANAGER_ID) - @Param(description = "UCS manager ID") - private String ucsManagerId; - @SerializedName(ApiConstants.HOST_ID) - @Param(description = "CloudStack host ID this blade associates to") - private String hostId; - @SerializedName(ApiConstants.UCS_BLADE_DN) - @Param(description = "UCS blade dn") - private String dn; - @SerializedName(ApiConstants.UCS_PROFILE_DN) - @Param(description = "Associated UCS profile dn") - private String associatedProfileDn; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getUcsManagerId() { - return ucsManagerId; - } - - public void setUcsManagerId(String ucsManagerId) { - this.ucsManagerId = ucsManagerId; - } - - public String getHostId() { - return hostId; - } - - public void setHostId(String hostId) { - this.hostId = hostId; - } - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } - - public String getAssociatedProfileDn() { - return associatedProfileDn; - } - - public void setAssociatedProfileDn(String associatedProfileDn) { - this.associatedProfileDn = associatedProfileDn; - } - -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsManagerResponse.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsManagerResponse.java deleted file mode 100644 index 418061bea2a4..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsManagerResponse.java +++ /dev/null @@ -1,78 +0,0 @@ -// 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 org.apache.cloudstack.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.serializer.Param; -import com.cloud.ucs.database.UcsManagerVO; - -@EntityReference(value = UcsManagerVO.class) -public class UcsManagerResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "The ID of the UCS manager") - private String id; - - @SerializedName(ApiConstants.NAME) - @Param(description = "The name of UCS manager") - private String name; - - @SerializedName(ApiConstants.URL) - @Param(description = "The URL of UCS manager") - private String url; - - @SerializedName(ApiConstants.ZONE_ID) - @Param(description = "The zone ID of UCS manager") - private String zoneId; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getZoneId() { - return zoneId; - } - - public void setZoneId(String zoneId) { - this.zoneId = zoneId; - } -} diff --git a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsProfileResponse.java b/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsProfileResponse.java deleted file mode 100644 index dda823233fc9..000000000000 --- a/plugins/hypervisors/ucs/src/main/java/org/apache/cloudstack/api/response/UcsProfileResponse.java +++ /dev/null @@ -1,39 +0,0 @@ -// 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 org.apache.cloudstack.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; - -import com.cloud.serializer.Param; - -public class UcsProfileResponse extends BaseResponse { - @SerializedName(ApiConstants.UCS_DN) - @Param(description = "UCS profile dn") - private String dn; - - public String getDn() { - return dn; - } - - public void setDn(String dn) { - this.dn = dn; - } -} diff --git a/plugins/hypervisors/ucs/src/main/resources/META-INF/cloudstack/core/spring-ucs-core-context.xml b/plugins/hypervisors/ucs/src/main/resources/META-INF/cloudstack/core/spring-ucs-core-context.xml deleted file mode 100644 index 1d5af47e3695..000000000000 --- a/plugins/hypervisors/ucs/src/main/resources/META-INF/cloudstack/core/spring-ucs-core-context.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - diff --git a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/guru/VmwareVmImplementer.java b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/guru/VmwareVmImplementer.java index 3885e06e7408..69d5087faa2a 100644 --- a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/guru/VmwareVmImplementer.java +++ b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/guru/VmwareVmImplementer.java @@ -294,17 +294,7 @@ private void addReservationDetails(long clusterId, Map details) } private List getNicProfiles(VirtualMachineProfile vm, Map details) { - List nicProfiles = vm.getNics(); - - for (NicProfile nicProfile : nicProfiles) { - if (nicProfile.getTrafficType() == Networks.TrafficType.Guest) { - if (networkModel.isProviderSupportServiceInNetwork(nicProfile.getNetworkId(), Network.Service.Firewall, Network.Provider.CiscoVnmc)) { - details.put("ConfigureVServiceInNexus", Boolean.TRUE.toString()); - } - break; - } - } - return nicProfiles; + return vm.getNics(); } private void setDiskControllers(VirtualMachineProfile vm, Map details, boolean userVm) { diff --git a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 621f0086acc1..dcf2669c0584 100644 --- a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -301,7 +301,6 @@ import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.mgmt.PropertyMapDynamicBean; import com.cloud.utils.net.NetUtils; -import com.cloud.utils.nicira.nvp.plugin.NiciraNvpApiVersion; import com.cloud.utils.script.Script; import com.cloud.utils.ssh.SshHelper; import com.cloud.utils.validation.ChecksumUtil; @@ -2465,8 +2464,6 @@ protected StartAnswer execute(StartCommand cmd) { VirtualEthernetCardType nicDeviceType; - NiciraNvpApiVersion.logNiciraApiVersion(); - Map nicUuidToDvSwitchUuid = new HashMap<>(); for (NicTO nicTo : sortNicsByDeviceId(nics)) { logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo)); @@ -2483,28 +2480,25 @@ protected StartAnswer execute(StartCommand cmd) { VirtualMachine.Type vmType = cmd.getVirtualMachine().getType(); Pair networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, configureVServiceInNexus, vmSpec.getNetworkIdToNetworkNameMap().getOrDefault(nicTo.getNetworkId(), null), vmType); - if ((nicTo.getBroadcastType() != BroadcastDomainType.Lswitch) - || (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch && NiciraNvpApiVersion.isApiVersionLowerThan("4.2"))) { - if (VmwareHelper.isDvPortGroup(networkInfo.first())) { - String dvSwitchUuid; - ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter(); - DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); - ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first()); - dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); - logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); - nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, - nicTo.getMac(), i + 1, true, true); - if (nicTo.getUuid() != null) { - nicUuidToDvSwitchUuid.put(nicTo.getUuid(), dvSwitchUuid); - } - } else { - logger.info("Preparing NIC device on network " + networkInfo.second()); - nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), - nicTo.getMac(), i + 1, true, true); + if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) { + // For Lswitch (NSX), connect to br-int (nsx.network) via opaque network + nic = VmwareHelper.prepareNicOpaque(vmMo, nicDeviceType, networkInfo.second(), + nicTo.getMac(), i + 1, true, true); + } else if (VmwareHelper.isDvPortGroup(networkInfo.first())) { + String dvSwitchUuid; + ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter(); + DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); + ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first()); + dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); + logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); + nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, + nicTo.getMac(), i + 1, true, true); + if (nicTo.getUuid() != null) { + nicUuidToDvSwitchUuid.put(nicTo.getUuid(), dvSwitchUuid); } } else { - //if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour - nic = VmwareHelper.prepareNicOpaque(vmMo, nicDeviceType, networkInfo.second(), + logger.info("Preparing NIC device on network " + networkInfo.second()); + nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), i + 1, true, true); } diff --git a/plugins/network-elements/bigswitch/findbugsExcludeFilter.xml b/plugins/network-elements/bigswitch/findbugsExcludeFilter.xml deleted file mode 100644 index d37285017e89..000000000000 --- a/plugins/network-elements/bigswitch/findbugsExcludeFilter.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/bigswitch/pom.xml b/plugins/network-elements/bigswitch/pom.xml deleted file mode 100644 index cd5ca8b5e999..000000000000 --- a/plugins/network-elements/bigswitch/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-bigswitch - Apache CloudStack Plugin - BigSwitch Virtual Network Segment - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfAnswer.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfAnswer.java deleted file mode 100644 index 45bb0245dd86..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfAnswer.java +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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.api; - -public class BcfAnswer extends Answer{ - private final String hash; - - public BcfAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - this.hash = ""; - } - - public BcfAnswer(final Command command, final boolean success, final String details, final String hash) { - super(command, success, details); - this.hash = hash; - } - - public BcfAnswer(final Command command, final Exception e) { - super(command, e); - this.hash = ""; - } - - public String getHash() { - return hash; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfCommand.java deleted file mode 100644 index 6e08dadcc1bf..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/BcfCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -// -// 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.api; - -import com.cloud.network.bigswitch.TopologyData; - -public class BcfCommand extends Command { - private TopologyData topology; - private boolean topologySyncRequested; - - @Override - public boolean executeInSequence() { - return false; - } - - public TopologyData getTopology() { - return topology; - } - - public void setTopology(final TopologyData topology) { - this.topology = topology; - } - - public boolean isTopologySyncRequested() { - return topologySyncRequested; - } - - public void setTopologySyncRequested(final boolean requested) { - this.topologySyncRequested = requested; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CacheBcfTopologyCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CacheBcfTopologyCommand.java deleted file mode 100644 index 1ab22a52db4b..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CacheBcfTopologyCommand.java +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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.api; - -import com.cloud.network.bigswitch.TopologyData; - -public class CacheBcfTopologyCommand extends Command{ - private final TopologyData _topology; - - public CacheBcfTopologyCommand(final TopologyData topology){ - this._topology = topology; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public TopologyData getTopology() { - return _topology; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfAttachmentCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfAttachmentCommand.java deleted file mode 100644 index 74e1215d45a0..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfAttachmentCommand.java +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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.api; - -public class CreateBcfAttachmentCommand extends BcfCommand { - private final String _tenantId; - private final String _tenantName; - private final String _networkId; - private final String _portId; - private final String _nicId; - private final Integer _vlan; - private final String _ipv4; - private final String _mac; - - public CreateBcfAttachmentCommand(final String tenantId, final String tenantName, - final String networkId, final String portId, final String nicId, - final Integer vlan, final String ipv4, final String mac) { - this._tenantId = tenantId; - this._tenantName = tenantName; - this._networkId = networkId; - this._portId = portId; - this._nicId = nicId; - this._vlan = vlan; - this._ipv4 = ipv4; - this._mac = mac; - } - - public String getTenantId() { - return _tenantId; - } - - public String getTenantName() { - return _tenantName; - } - public String getNetworkId() { - return _networkId; - } - - public String getPortId() { - return _portId; - } - - public String getNicId() { - return _nicId; - } - - public Integer getVlan() { - return _vlan; - } - - public String getIpv4() { - return _ipv4; - } - - public String getMac() { - return _mac; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterCommand.java deleted file mode 100644 index 8fcab6b597ba..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterCommand.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.api; - -public class CreateBcfRouterCommand extends BcfCommand { - private final String _tenantId; - - public CreateBcfRouterCommand(final String tenantId){ - this._tenantId = tenantId; - } - - public String getTenantId() { - return _tenantId; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterInterfaceCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterInterfaceCommand.java deleted file mode 100644 index 66ad1a056307..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfRouterInterfaceCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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.api; - -public class CreateBcfRouterInterfaceCommand extends BcfCommand{ - private final String _tenantId; - private final String _networkId; - private final String _cidr; - private final String _gateway; - private final String _networkName; - - public CreateBcfRouterInterfaceCommand(final String tenantId, final String networkId, - final String cidr, final String gateway, final String networkName){ - this._tenantId = tenantId; - this._networkId = networkId; - this._networkName = networkName; - this._cidr = cidr; - this._gateway = gateway; - } - - public String getTenantId() { - return _tenantId; - } - - public String getNetworkId() { - return _networkId; - } - - public String getNetworkName() { - return _networkName; - } - - public String getCidr() { - return _cidr; - } - - public String getGateway() { - return _gateway; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfSegmentCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfSegmentCommand.java deleted file mode 100644 index 9bb75fe016c4..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfSegmentCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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.api; - -public class CreateBcfSegmentCommand extends BcfCommand { - private final String _tenantId; - private final String _tenantName; - private final String _networkId; - private final String _networkName; - private final Integer _vlan; - - public CreateBcfSegmentCommand(final String tenantId, final String tenantName, - final String networkId, final String networkName, final Integer vlan) { - this._tenantId = tenantId; - this._tenantName = tenantName; - this._networkId = networkId; - this._networkName = networkName; - this._vlan = vlan; - } - - public String getNetworkId() { - return _networkId; - } - - public String getNetworkName() { - return _networkName; - } - - public String getTenantId() { - return _tenantId; - } - - public String getTenantName() { - return _tenantName; - } - - public Integer getVlan() { - return _vlan; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfStaticNatCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfStaticNatCommand.java deleted file mode 100644 index 3db96f114b71..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/CreateBcfStaticNatCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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.api; - -public class CreateBcfStaticNatCommand extends BcfCommand { - private final String _tenantId; - private final String _networkId; - private final String _privateIp; - private final String _publicIp; - private final String _mac; - - public CreateBcfStaticNatCommand(final String tenantId, final String networkId, - final String privateIp, final String publicIp, final String mac){ - this._tenantId = tenantId; - this._networkId = networkId; - this._privateIp = privateIp; - this._publicIp = publicIp; - this._mac = mac; - } - - public String getTenantId() { - return _tenantId; - } - - public String getNetworkId() { - return _networkId; - } - - public String getPrivateIp() { - return _privateIp; - } - - public String getPublicIp() { - return _publicIp; - } - - public String getMac() { - return _mac; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfAttachmentCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfAttachmentCommand.java deleted file mode 100644 index fc9f05f573e3..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfAttachmentCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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.api; - -public class DeleteBcfAttachmentCommand extends BcfCommand { - private final String _tenantId; - private final String _networkId; - private final String _attachmentId; - - public DeleteBcfAttachmentCommand(final String tenantId, - final String networkId, final String attachmentId) { - this._tenantId = tenantId; - this._networkId = networkId; - this._attachmentId = attachmentId; - } - - public String getTenantId() { - return _tenantId; - } - - public String getNetworkId() { - return _networkId; - } - - public String getAttachmentId() { - return _attachmentId; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfSegmentCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfSegmentCommand.java deleted file mode 100644 index 6c133a356b8f..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfSegmentCommand.java +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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.api; - -public class DeleteBcfSegmentCommand extends BcfCommand { - - private final String _tenantUuid; - private final String _networkUuid; - - public DeleteBcfSegmentCommand(final String tenantUuid, final String networkUuid) { - this._tenantUuid = tenantUuid; - this._networkUuid = networkUuid; - } - - public String getTenantUuid() { - return _tenantUuid; - } - - public String getNetworkUuid() { - return _networkUuid; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfStaticNatCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfStaticNatCommand.java deleted file mode 100644 index e476565dd589..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/DeleteBcfStaticNatCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.api; - -public class DeleteBcfStaticNatCommand extends BcfCommand { - private final String _tenantId; - private final String _publicIp; - private final String _floatingIpId; - - public DeleteBcfStaticNatCommand(final String tenantId, final String publicIp){ - this._tenantId = tenantId; - this._publicIp = publicIp; - this._floatingIpId = publicIp.replace(".", "-"); - } - - public String getTenantId() { - return _tenantId; - } - - public String getPublicIp() { - return _publicIp; - } - - public String getFloatingIpId() { - return _floatingIpId; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataAnswer.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataAnswer.java deleted file mode 100644 index 84dd6b346ad1..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataAnswer.java +++ /dev/null @@ -1,46 +0,0 @@ -// -// 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.api; - -public class GetControllerDataAnswer extends Answer { - private final String _ipAddress; - private final boolean _isPrimary; - - public GetControllerDataAnswer(final GetControllerDataCommand cmd, - final String ipAddress, final boolean isPrimary){ - super(cmd); - this._ipAddress = ipAddress; - this._isPrimary = isPrimary; - } - - public GetControllerDataAnswer(final Command command, final Exception e) { - super(command, e); - this._ipAddress = null; - this._isPrimary = false; - } - - public String getIpAddress() { - return _ipAddress; - } - - public boolean isPrimary() { - return _isPrimary; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataCommand.java deleted file mode 100644 index 96ad1193a080..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerDataCommand.java +++ /dev/null @@ -1,23 +0,0 @@ -// -// 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.api; - -public class GetControllerDataCommand extends BcfCommand { -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsAnswer.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsAnswer.java deleted file mode 100644 index f9a49c8bb57a..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsAnswer.java +++ /dev/null @@ -1,40 +0,0 @@ -// -// 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.api; - -import com.cloud.host.HostVO; - -public class GetControllerHostsAnswer { - private HostVO primary; - private HostVO secondary; - - public HostVO getPrimary() { - return primary; - } - public void setPrimary(final HostVO primary) { - this.primary = primary; - } - public HostVO getSecondary() { - return secondary; - } - public void setSecondary(final HostVO secondary) { - this.secondary = secondary; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsCommand.java deleted file mode 100644 index c984b289aadc..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/GetControllerHostsCommand.java +++ /dev/null @@ -1,23 +0,0 @@ -// -// 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.api; - -public class GetControllerHostsCommand extends BcfCommand { -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/StartupBigSwitchBcfCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/StartupBigSwitchBcfCommand.java deleted file mode 100644 index 6acb43dbcecf..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/StartupBigSwitchBcfCommand.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// 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.api; - -import com.cloud.host.Host; - -public class StartupBigSwitchBcfCommand extends StartupCommand { - - public StartupBigSwitchBcfCommand() { - super(Host.Type.L2Networking); - } - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/SyncBcfTopologyCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/SyncBcfTopologyCommand.java deleted file mode 100644 index 89c3e1c343e8..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/SyncBcfTopologyCommand.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class SyncBcfTopologyCommand extends BcfCommand { - private final boolean _networkIncluded; - private final boolean _routerIncluded; - - public SyncBcfTopologyCommand(final boolean networkIncluded, final boolean routerIncluded) { - this._networkIncluded = networkIncluded; - this._routerIncluded = routerIncluded; - } - - public boolean isNetworkIncluded() { - return _networkIncluded; - } - - public boolean isRouterIncluded() { - return _routerIncluded; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfAttachmentCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfAttachmentCommand.java deleted file mode 100644 index 4e054f08733d..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfAttachmentCommand.java +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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.api; - -public class UpdateBcfAttachmentCommand extends BcfCommand { - private final String _networkId; - private final String _attachmentId; - private final String _tenantId; - private final String _attachmentName; - - public UpdateBcfAttachmentCommand(final String networkId, final String attachmentId, - final String tenantId, final String attachmentName) { - this._networkId = networkId; - this._attachmentId = attachmentId; - this._tenantId = tenantId; - this._attachmentName = attachmentName; - } - - public String getNetworkId() { - return _networkId; - } - - public String getAttachmentId() { - return _attachmentId; - } - - public String getTenantId() { - return _tenantId; - } - - public String getPortName() { - return _attachmentName; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfRouterCommand.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfRouterCommand.java deleted file mode 100644 index 47a9356b1c33..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/agent/api/UpdateBcfRouterCommand.java +++ /dev/null @@ -1,61 +0,0 @@ -// -// 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.api; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.network.bigswitch.AclData; - -public class UpdateBcfRouterCommand extends BcfCommand { - private String tenantId; - private String publicIp; - private final List acls; - - public UpdateBcfRouterCommand(final String tenantId){ - this.tenantId = tenantId; - this.publicIp = null; - this.acls = new ArrayList(); - } - - public String getTenantId() { - return tenantId; - } - - public void setTenantId(final String tenantId) { - this.tenantId = tenantId; - } - - public String getPublicIp() { - return publicIp; - } - - public void setPublicIp(final String publicIp) { - this.publicIp = publicIp; - } - - public List getAcls() { - return acls; - } - - public void addAcl(final AclData acl){ - this.acls.add(acl); - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/AddBigSwitchBcfDeviceCmd.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/AddBigSwitchBcfDeviceCmd.java deleted file mode 100644 index 43be31dd46dc..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/AddBigSwitchBcfDeviceCmd.java +++ /dev/null @@ -1,136 +0,0 @@ -// -// 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.api.commands; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.BigSwitchBcfDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.network.element.BigSwitchBcfElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addBigSwitchBcfDevice", responseObject = BigSwitchBcfDeviceResponse.class, description = "Adds a BigSwitch BCF Controller device", since = "4.6.0", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddBigSwitchBcfDeviceCmd extends BaseAsyncCmd { - @Inject - private BigSwitchBcfElementService bcfElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - required = true, - description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname of ip address of the BigSwitch BCF Controller.") - private String host; - - @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, - description = "Username of the BigSwitch BCF Controller.") - private String username; - - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, - description = "Password of the BigSwitch BCF Controller.") - private String password; - - @Parameter(name=BcfConstants.BIGSWITCH_BCF_DEVICE_NAT, type=CommandType.BOOLEAN, required=true, - description = "NAT support of the BigSwitch BCF Controller.") - private Boolean nat; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getHost() { - return host; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public Boolean getNat() { - return nat; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - final BigSwitchBcfDeviceVO bigswitchBcfDeviceVO = bcfElementService.addBigSwitchBcfDevice(this); - if (bigswitchBcfDeviceVO == null) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add BigSwitch BCF Controller device due to internal error."); - } - final BigSwitchBcfDeviceResponse response = bcfElementService.createBigSwitchBcfDeviceResponse(bigswitchBcfDeviceVO); - response.setObjectName("bigswitchbcfdevice"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage(), invalidParamExcp); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage(), runtimeExcp); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public String getEventType() { - return BcfConstants.EVENT_BCF_CONTROLLER_ADD; - } - - @Override - public String getEventDescription() { - return "Adding a BigSwitch BCF Controller to physical network with ID: " + getResourceUuid(ApiConstants.PHYSICAL_NETWORK_ID); - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/BcfConstants.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/BcfConstants.java deleted file mode 100644 index 157d9a316160..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/BcfConstants.java +++ /dev/null @@ -1,37 +0,0 @@ -// -// 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.api.commands; - -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; - -import com.cloud.network.Network.Provider; - -public class BcfConstants { - public static final String BIGSWITCH_BCF_DEVICE_ID = "bcfdeviceid"; - public static final String BIGSWITCH_BCF_DEVICE_NAME = "bigswitchdevicename"; - public static final String BIGSWITCH_BCF_DEVICE_NAT = "nat"; - public static final String EVENT_BCF_CONTROLLER_ADD = "PHYSICAL.BCFCONTROLLER.ADD"; - public static final String EVENT_BCF_CONTROLLER_DELETE = "PHYSICAL.BCFCONTROLLER.DELETE"; - - public static final Provider BIG_SWITCH_BCF = new Provider("BigSwitchBcf", true); - - public static final NetworkDevice BIG_SWITCH_BCF_DEVICE = new NetworkDevice("BigSwitchBcf", BIG_SWITCH_BCF.getName()); - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/DeleteBigSwitchBcfDeviceCmd.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/DeleteBigSwitchBcfDeviceCmd.java deleted file mode 100644 index b86adac1b75e..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/DeleteBigSwitchBcfDeviceCmd.java +++ /dev/null @@ -1,105 +0,0 @@ -// -// 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.api.commands; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.BigSwitchBcfDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.element.BigSwitchBcfElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteBigSwitchBcfDevice", responseObject = SuccessResponse.class, description = " delete a BigSwitch BCF Controller device", since = "4.6.0", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteBigSwitchBcfDeviceCmd extends BaseAsyncCmd { - @Inject - private BigSwitchBcfElementService bigswitchBcfElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = BcfConstants.BIGSWITCH_BCF_DEVICE_ID, - type = CommandType.UUID, - entityType = BigSwitchBcfDeviceResponse.class, - required = true, - description = "BigSwitch device ID") - private Long bigswitchBcfDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getBigSwitchBcfDeviceId() { - return bigswitchBcfDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - final boolean result = bigswitchBcfElementService.deleteBigSwitchBcfDevice(this); - if (result) { - final SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete BigSwitch device."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage(), invalidParamExcp); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage(), runtimeExcp); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public String getEventType() { - return BcfConstants.EVENT_BCF_CONTROLLER_DELETE; - } - - @Override - public String getEventDescription() { - return "Deleting BigSwitch BCF Controller with ID: " + getResourceUuid(ApiConstants.ID); - } - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/ListBigSwitchBcfDevicesCmd.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/ListBigSwitchBcfDevicesCmd.java deleted file mode 100644 index e7b3f325f742..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/commands/ListBigSwitchBcfDevicesCmd.java +++ /dev/null @@ -1,112 +0,0 @@ -// -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.BigSwitchBcfDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.network.element.BigSwitchBcfElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listBigSwitchBcfDevices", responseObject = BigSwitchBcfDeviceResponse.class, description = "Lists BigSwitch BCF Controller devices", since = "4.6.0", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListBigSwitchBcfDevicesCmd extends BaseListCmd { - private static final String S_NAME = "listbigswitchbcfdeviceresponse"; - @Inject - private BigSwitchBcfElementService bigswitchBcfElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = BcfConstants.BIGSWITCH_BCF_DEVICE_ID, - type = CommandType.UUID, - entityType = BigSwitchBcfDeviceResponse.class, - description = "Bigswitch BCF controller device ID") - private Long bigswitchBcfDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getBigSwitchBcfDeviceId() { - return bigswitchBcfDeviceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - final List bigswitchDevices = bigswitchBcfElementService.listBigSwitchBcfDevices(this); - final ListResponse response = new ListResponse(); - final List bigswitchDevicesResponse = new ArrayList(); - - if (bigswitchDevices != null && !bigswitchDevices.isEmpty()) { - for (final BigSwitchBcfDeviceVO bigswitchDeviceVO : bigswitchDevices) { - final BigSwitchBcfDeviceResponse bigswitchDeviceResponse = bigswitchBcfElementService.createBigSwitchBcfDeviceResponse(bigswitchDeviceVO); - bigswitchDevicesResponse.add(bigswitchDeviceResponse); - } - } - - response.setResponses(bigswitchDevicesResponse); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage(), invalidParamExcp); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage(), runtimeExcp); - } - } - - @Override - public String getCommandName() { - return S_NAME; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/response/BigSwitchBcfDeviceResponse.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/response/BigSwitchBcfDeviceResponse.java deleted file mode 100644 index ee5e72c2f82c..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/api/response/BigSwitchBcfDeviceResponse.java +++ /dev/null @@ -1,99 +0,0 @@ -// -// 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.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.api.commands.BcfConstants; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.serializer.Param; - -@EntityReference(value = BigSwitchBcfDeviceVO.class) -public class BigSwitchBcfDeviceResponse extends BaseResponse { - @SerializedName(BcfConstants.BIGSWITCH_BCF_DEVICE_ID) - @Param(description = "Device ID of the BigSwitch BCF Controller") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Param(description = "The physical Network to which this BigSwitch BCF segment belongs to") - private String physicalNetworkId; - - @SerializedName(ApiConstants.PROVIDER) - @Param(description = "Name of the provider") - private String providerName; - - @SerializedName(BcfConstants.BIGSWITCH_BCF_DEVICE_NAME) - @Param(description = "Device name") - private String deviceName; - - @SerializedName(ApiConstants.HOST_NAME) - @Param(description = "The controller IP address") - private String hostName; - - @SerializedName(ApiConstants.USERNAME) @Param(description = "The controller username") - private String username; - - @SerializedName(ApiConstants.PASSWORD) @Param(description = "The controller password", isSensitive = true) - private String password; - - @SerializedName(BcfConstants.BIGSWITCH_BCF_DEVICE_NAT) - @Param(description = "NAT support") - private Boolean nat; - - public String getId() { - return this.id; - } - - public void setId(final String bcfDeviceId) { - this.id = bcfDeviceId; - } - - public void setPhysicalNetworkId(final String physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public void setProviderName(final String providerName) { - this.providerName = providerName; - } - - public void setDeviceName(final String deviceName) { - this.deviceName = deviceName; - } - - public void setHostName(final String hostName) { - this.hostName = hostName; - } - - public void setUserName(final String username) { - this.username = username; - } - - public void setPassword(final String password) { - this.password = password; - } - - public void setNat(final Boolean nat) { - this.nat = nat; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/BigSwitchBcfDeviceVO.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/BigSwitchBcfDeviceVO.java deleted file mode 100644 index 7fec1e2c093d..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/BigSwitchBcfDeviceVO.java +++ /dev/null @@ -1,153 +0,0 @@ -// -// 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.network; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; -import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; - -@Entity -@Table(name = "external_bigswitch_bcf_devices") -public class BigSwitchBcfDeviceVO implements InternalIdentity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "host_id") - private long hostId; - - @Column(name = "physical_network_id") - private long physicalNetworkId; - - @Column(name = "provider_name") - private String providerName; - - @Column(name = "device_name") - private String deviceName; - - @Column(name = "hostname") - private String hostName; - - @Column(name = "username") - private String userName; - - @Column(name = "password") - private String password; - - @Column(name = "nat") - private Boolean nat; - - @Column(name = "hash") - private String hash; - - public BigSwitchBcfDeviceVO() { - this.uuid = UUID.randomUUID().toString(); - } - - public BigSwitchBcfDeviceVO(final long hostId, final long physicalNetworkId, - final String providerName, final String deviceName,final String hostName, - final String username, final String password, final Boolean nat, - final String hash) { - super(); - this.hostId = hostId; - this.physicalNetworkId = physicalNetworkId; - this.providerName = providerName; - this.deviceName = deviceName; - this.uuid = UUID.randomUUID().toString(); - this.hostName = hostName; - this.userName = username; - this.password = password; - this.nat = nat; - this.hash = hash; - } - - @Override - public String toString() { - return String.format("BigSwitchBcfDevice %s.", - ReflectionToStringBuilderUtils.reflectOnlySelectedFields( - this, "id", "uuid", "name")); - } - - @Override - public long getId() { - return id; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(final String uuid) { - this.uuid = uuid; - } - - public long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public long getHostId() { - return hostId; - } - - public String getProviderName() { - return providerName; - } - - public String getDeviceName() { - return deviceName; - } - - public String getHash() { - return hash; - } - - public void setHash(final String h) { - hash = h; - } - - public String getHostName() { - return hostName; - } - - public String getUserName() { - return userName; - } - - public String getPassword() { - return password; - } - - public Boolean getNat() { - return nat; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AclData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AclData.java deleted file mode 100644 index 150bc61cff52..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AclData.java +++ /dev/null @@ -1,118 +0,0 @@ -// -// 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.network.bigswitch; - -import java.util.Locale; - -import com.cloud.network.vpc.NetworkACLItem; -import com.google.gson.annotations.SerializedName; - -/** - * AclData contains information expected by Big Switch Controller - * in ApplyBcfAclCommand - */ - -public class AclData { - @SerializedName("id") private String id; - @SerializedName("priority") private int priority; - @SerializedName("action") private String action; - @SerializedName("ipproto") private String ipProto; - @SerializedName("source") private AclNetwork source; - @SerializedName("destination") private AclNetwork destination; - - public AclData(){ - this.id = null; - this.priority = 0; - this.action = null; - this.ipProto = null; - this.source = new AclNetwork(); - this.destination = new AclNetwork(); - } - - public class AclNetwork{ - @SerializedName("cidr") final private String cidr; - @SerializedName("port") final private Integer port; - - public AclNetwork(){ - this.cidr = null; - this.port = null; - } - - public AclNetwork(final String cidr, final Integer port){ - this.cidr = cidr; - this.port = port; - } - } - - public String getId() { - return id; - } - public void setId(final String id) { - this.id = id; - } - public int getPriority() { - return priority; - } - public void setPriority(final int priority) { - this.priority = priority; - } - public String getAction() { - return action; - } - public void setAction(final String action) { - if(action.equalsIgnoreCase(NetworkACLItem.Action.Allow.name())){ - this.action = "permit"; - } else { - this.action = "deny"; - } - } - public String getIpProto() { - return ipProto; - } - public void setIpProto(final String ipProto) { - if (ipProto != null && !ipProto.equalsIgnoreCase("all")){ - switch(ipProto.toLowerCase(Locale.ENGLISH)){ - case "tcp": - this.ipProto = "6"; - break; - case "udp": - this.ipProto = "17"; - break; - case "icmp": - this.ipProto = "1"; - break; - default: - throw new IllegalArgumentException("Protocol in ACL rule not supported"); - } - } - } - public AclNetwork getSource() { - return source; - } - public void setSource(final AclNetwork source) { - this.source = source; - } - public AclNetwork getDestination() { - return destination; - } - public void setDestination(final AclNetwork destination) { - this.destination = destination; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AttachmentData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AttachmentData.java deleted file mode 100644 index 40d99e3204e3..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AttachmentData.java +++ /dev/null @@ -1,143 +0,0 @@ -// -// 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.network.bigswitch; - -import java.util.ArrayList; -import java.util.List; - -import com.google.gson.annotations.SerializedName; - -/** - * AttachmentData contains information expected by Big Switch Controller - * in CreateBcfAttachmentCommand - */ -public class AttachmentData { - @SerializedName("port") final private Attachment attachment; - - public Attachment getAttachment() { - return this.attachment; - } - - public AttachmentData() { - this.attachment = new Attachment(); - } - - public class Attachment { - @SerializedName("id") private String id; - @SerializedName("tenant_name") private String tenantName; - @SerializedName("vlan") private Integer vlan; - @SerializedName("fixed_ips") final private List fixedIps; - @SerializedName("mac_address") private String macAddress; - @SerializedName("bound_segment") final private BoundSegment boundSegment; - @SerializedName("binding:host_id") private String hostId; - - public Attachment(){ - this.boundSegment = new BoundSegment(); - this.fixedIps = new ArrayList(); - } - - public class BoundSegment { - @SerializedName("segmentation_id") private Integer segmentationId; - - public Integer getSegmentationId() { - return segmentationId; - } - - public void setSegmentationId(Integer segmentationId) { - this.segmentationId = segmentationId; - } - } - - public class IpAddress { - @SerializedName("ip_address") private String address; - - public IpAddress(final String ipAddr) { - this.address = ipAddr; - } - - public String getIpAddress(){ - return address; - } - } - - private String state; - - public String getTenantName() { - return tenantName; - } - - public void setTenantName(final String tenantName) { - this.tenantName = tenantName; - } - - public String getId() { - return id; - } - - public void setId(final String id) { - this.id = id; - } - - public String getHostId() { - return hostId; - } - - public void setHostId(final String hostId) { - this.hostId = hostId; - } - - public Integer getVlan() { - return vlan; - } - - public void setVlan(final Integer vlan) { - this.vlan = vlan; - this.boundSegment.setSegmentationId(vlan); - } - - public List getIpv4List() { - return fixedIps; - } - - public void addIpv4(final String ipv4) { - this.fixedIps.add(new IpAddress(ipv4)); - } - - public String getMac() { - return macAddress; - } - - public void setMac(final String mac) { - this.macAddress = mac; - } - - public BoundSegment getBoundSegment() { - return boundSegment; - } - - public String getState() { - return state; - } - - public void setState(final String state) { - this.state = state; - } - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApi.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApi.java deleted file mode 100644 index ba81b76022d8..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApi.java +++ /dev/null @@ -1,463 +0,0 @@ -// -// 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.network.bigswitch; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.httpclient.protocol.Protocol; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -public class BigSwitchBcfApi { - protected Logger logger = LogManager.getLogger(getClass()); - private final static String S_PROTOCOL = "https"; - private final static String S_NS_BASE_URL = "/networkService/v1.1"; - private final static String CONTENT_TYPE = "content-type"; - private final static String ACCEPT = "Accept"; - private final static String CONTENT_JSON = "application/json"; - private final static String HTTP_HEADER_INSTANCE_ID = "Instance-ID"; - private final static String CLOUDSTACK_INSTANCE_ID = "cloudstack"; - private final static String HASH_MATCH = "X-BSN-BVS-HASH-MATCH"; - private final static MultiThreadedHttpConnectionManager S_HTTP_CLIENT_MANAGER = new MultiThreadedHttpConnectionManager(); - - private String host; - private String username; - private String password; - private String hash; - private String zoneId; - private Boolean nat; - - private boolean isPrimary; - - private int _port = 8000; - - private HttpClient _client; - private Gson gson = new Gson(); - - public final static String HASH_CONFLICT = "HASH_CONFLICT"; - public final static String HASH_IGNORE = "HASH_IGNORE"; - - /* This factory method is protected so we can extend this - * in the unittests. - */ - protected HttpClient createHttpClient() { - return new HttpClient(S_HTTP_CLIENT_MANAGER); - } - - protected HttpMethod createMethod(final String type, final String uri, final int port) throws BigSwitchBcfApiException { - String url; - try { - url = new URL(S_PROTOCOL, host, port, uri).toString(); - } catch (MalformedURLException e) { - logger.error("Unable to build Big Switch API URL", e); - throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e); - } - - if ("post".equalsIgnoreCase(type)) { - return new PostMethod(url); - } else if ("get".equalsIgnoreCase(type)) { - return new GetMethod(url); - } else if ("delete".equalsIgnoreCase(type)) { - return new DeleteMethod(url); - } else if ("put".equalsIgnoreCase(type)) { - return new PutMethod(url); - } else { - throw new BigSwitchBcfApiException("Requesting unknown method type"); - } - } - - public BigSwitchBcfApi() { - _client = createHttpClient(); - _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - - try { - // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the SecureProtocolSocketFactory parameter - Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), _port)); - } catch (IOException e) { - logger.warn("Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory", e); - } - } - - /** - * Setter used by UI to set BSN controller address - * @param address - */ - public void setControllerAddress(final String address) { - this.host = address; - } - - /** - * Setter used by UI to set BSN controller user name - * @param username - */ - public void setControllerUsername(final String username) { - this.username = username; - } - - /** - * Setter used by UI to set BSN controller password - * @param password - */ - public void setControllerPassword(final String password) { - this.password = password; - } - - /** - * Setter used by UI to set BSN controller NAT mode - * @param nat - */ - public void setControllerNat(final Boolean nat) { - this.nat = nat; - } - - public boolean isNatEnabled() { - return this.nat; - } - - public void setZoneId(final String zoneId) { - this.zoneId = zoneId; - } - - public String createNetwork(final NetworkData network) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + network.getNetwork().getTenantId() + "/networks"; - return executeCreateObject(network, uri, Collections. emptyMap()); - } - - public String deleteNetwork(final String tenantId, final String networkId) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/networks/" + networkId; - return executeDeleteObject(uri); - } - - public String createAttachment(final String tenantId, final String networkId, - final AttachmentData attachment) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + attachment.getAttachment().getId() + "/attachment"; - return executeCreateObject(attachment, uri, Collections. emptyMap()); - } - - public String modifyAttachment(final String tenantId, final String networkId, - final AttachmentData attachment) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + attachment.getAttachment().getId() + "/attachment"; - return executeUpdateObject(attachment, uri, Collections. emptyMap()); - } - - public String deleteAttachment(final String tenantId, final String networkId, - final String attachmentId) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/networks/" + networkId + "/ports/" + attachmentId + "/attachment"; - return executeDeleteObject(uri); - } - - public String createRouter(final String tenantId, final RouterData router) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/routers"; - return executeCreateObject(router, uri, Collections. emptyMap()); - } - - public String modifyRouter(final String tenantId, final RouterData router) throws BigSwitchBcfApiException, - IllegalArgumentException{ - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/routers"; - return executeCreateObject(router, uri, Collections. emptyMap()); - } - - public String createRouterInterface(final String tenantId, final String routerId, - final RouterInterfaceData routerInterface) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/routers/" + routerId + "/interfaces"; - return executeCreateObject(routerInterface, uri, Collections. emptyMap()); - } - - public String createFloatingIp(final String tenantId, final FloatingIpData fip) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/floatingips"; - return executeCreateObject(fip, uri, Collections. emptyMap()); - } - - public String deleteFloatingIp(final String tenantId, final String fipId) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/tenants/" + tenantId + "/floatingips/" + fipId; - return executeDeleteObject(uri); - } - - public ControlClusterStatus getControlClusterStatus() throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/health"; - ControlClusterStatus ccs = executeRetrieveObject(new TypeToken() { - }.getType(), uri, null); - ccs.setStatus(true); - return ccs; - } - - public Capabilities getCapabilities() throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/capabilities"; - List capslist = executeRetrieveObject(new TypeToken>() { - }.getType(), uri, null); - Capabilities caps = new Capabilities(); - caps.setCapabilities(capslist); - return caps; - } - - public String syncTopology(final TopologyData topo) throws BigSwitchBcfApiException { - String uri = S_NS_BASE_URL + "/topology"; - return executeCreateObject(topo, uri, Collections. emptyMap()); - } - - public ControllerData getControllerData() { - return new ControllerData(host, isPrimary); - } - - private void checkInvariants() throws BigSwitchBcfApiException{ - if (host == null || host.isEmpty()) { - throw new BigSwitchBcfApiException("Hostname is null or empty"); - } - if (username == null || username.isEmpty()){ - throw new BigSwitchBcfApiException("Username is null or empty"); - } - if (password == null || password.isEmpty()){ - throw new BigSwitchBcfApiException("Password is null or empty"); - } - } - - private String checkResponse(final HttpMethodBase m, final String errorMessageBase) throws BigSwitchBcfApiException, - IllegalArgumentException{ - String customErrorMsg = null; - if (m.getStatusCode() == HttpStatus.SC_OK) { - String hash = ""; - if (m.getResponseHeader(HASH_MATCH) != null) { - hash = m.getResponseHeader(HASH_MATCH).getValue(); - set_hash(hash); - } - return hash; - } - if (m.getStatusCode() == HttpStatus.SC_CONFLICT) { - if(m instanceof GetMethod) { - return HASH_CONFLICT; - } - throw new BigSwitchBcfApiException("BCF topology sync required", true); - } - if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) { - isPrimary = false; - set_hash(HASH_IGNORE); - return HASH_IGNORE; - } - if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) { - if (m instanceof DeleteMethod){ - return ""; - } - } - if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) { - customErrorMsg = " Invalid data in BCF request"; - throw new IllegalArgumentException(customErrorMsg); - } - String errorMessage = responseToErrorMessage(m); - m.releaseConnection(); - logger.error(errorMessageBase + errorMessage); - throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg); - } - - private void setHttpHeader(final HttpMethodBase m) { - m.setRequestHeader(CONTENT_TYPE, CONTENT_JSON); - m.setRequestHeader(ACCEPT, CONTENT_JSON); - m.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID + "-" + zoneId); - if (StringUtils.isNotEmpty(hash)) { - m.setRequestHeader(HASH_MATCH, hash); - } - - String authString = username + ":" + password; - String encodedAuthString = "Basic " + Base64.encodeBase64String(authString.getBytes(Charset.forName("UTF-8"))); - m.setRequestHeader("Authorization", encodedAuthString); - } - - protected String executeUpdateObject(final T newObject, final String uri, - final Map parameters) throws BigSwitchBcfApiException, - IllegalArgumentException{ - checkInvariants(); - - PutMethod pm = (PutMethod)createMethod("put", uri, _port); - - setHttpHeader(pm); - - try { - pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null)); - } catch (UnsupportedEncodingException e) { - throw new BigSwitchBcfApiException("Failed to encode json request body", e); - } - - executeMethod(pm); - - String hash = checkResponse(pm, "BigSwitch HTTP update failed: "); - - pm.releaseConnection(); - - return hash; - } - - protected String executeCreateObject(final T newObject, final String uri, - final Map parameters) throws BigSwitchBcfApiException { - checkInvariants(); - - PostMethod pm = (PostMethod)createMethod("post", uri, _port); - - setHttpHeader(pm); - - try { - pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null)); - } catch (UnsupportedEncodingException e) { - throw new BigSwitchBcfApiException("Failed to encode json request body", e); - } - - executeMethod(pm); - - String hash = checkResponse(pm, "BigSwitch HTTP create failed: "); - - pm.releaseConnection(); - - return hash; - } - - protected String executeDeleteObject(final String uri) throws BigSwitchBcfApiException { - checkInvariants(); - - DeleteMethod dm = (DeleteMethod)createMethod("delete", uri, _port); - - setHttpHeader(dm); - - executeMethod(dm); - - String hash = checkResponse(dm, "BigSwitch HTTP delete failed: "); - - dm.releaseConnection(); - - return hash; - } - - @SuppressWarnings("unchecked") - protected T executeRetrieveObject(final Type returnObjectType, - final String uri, final Map parameters) throws BigSwitchBcfApiException { - checkInvariants(); - - GetMethod gm = (GetMethod)createMethod("get", uri, _port); - - setHttpHeader(gm); - - if (parameters != null && !parameters.isEmpty()) { - List nameValuePairs = new ArrayList(parameters.size()); - for (Entry e : parameters.entrySet()) { - nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue())); - } - gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0])); - } - - executeMethod(gm); - - String hash = checkResponse(gm, "BigSwitch HTTP get failed: "); - - T returnValue; - try { - // CAUTIOUS: Safety margin of 2048 characters - extend if needed. - returnValue = (T)gson.fromJson(gm.getResponseBodyAsString(2048), returnObjectType); - } catch (IOException e) { - logger.error("IOException while retrieving response body", e); - throw new BigSwitchBcfApiException(e); - } finally { - gm.releaseConnection(); - } - if(returnValue instanceof ControlClusterStatus) { - if(HASH_CONFLICT.equals(hash)) { - isPrimary = true; - ((ControlClusterStatus) returnValue).setTopologySyncRequested(true); - } else if (!HASH_IGNORE.equals(hash) && !isPrimary) { - isPrimary = true; - ((ControlClusterStatus) returnValue).setTopologySyncRequested(true); - } - } - return returnValue; - } - - protected void executeMethod(final HttpMethodBase method) throws BigSwitchBcfApiException { - try { - _client.executeMethod(method); - if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - method.releaseConnection(); - } - } catch (HttpException e) { - logger.error("HttpException caught while trying to connect to the BigSwitch Controller", e); - method.releaseConnection(); - throw new BigSwitchBcfApiException("API call to BigSwitch Controller Failed", e); - } catch (IOException e) { - logger.error("IOException caught while trying to connect to the BigSwitch Controller", e); - method.releaseConnection(); - throw new BigSwitchBcfApiException("API call to BigSwitch Controller Failed", e); - } - } - - private String responseToErrorMessage(final HttpMethodBase method) { - assert method.isRequestSent() : "no use getting an error message unless the request is sent"; - - if ("text/html".equals(method.getResponseHeader(CONTENT_TYPE).getValue())) { - // The error message is the response content - // Safety margin of 2048 characters, anything longer is probably useless - // and will clutter the logs - try { - return method.getResponseBodyAsString(2048); - } catch (IOException e) { - logger.debug("Error while loading response body", e); - } - } - - // The default - return method.getStatusText(); - } - - public static String getCloudstackInstanceId() { - return CLOUDSTACK_INSTANCE_ID; - } - - public String get_hash() { - return hash; - } - - public void set_hash(final String hash) { - this.hash = hash; - } - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApiException.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApiException.java deleted file mode 100644 index feed707519a0..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfApiException.java +++ /dev/null @@ -1,55 +0,0 @@ -// -// 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.network.bigswitch; - -public class BigSwitchBcfApiException extends Exception { - - private static final long serialVersionUID = -5864952230870945604L; - private boolean topologySyncRequested = false; - - public BigSwitchBcfApiException() { - } - - public BigSwitchBcfApiException(String message) { - super(message); - } - - public BigSwitchBcfApiException(Throwable cause) { - super(cause); - } - - public BigSwitchBcfApiException(String message, Throwable cause) { - super(message, cause); - } - - public BigSwitchBcfApiException(String message, boolean syncRequest) { - super(message); - this.set_topologySyncRequested(syncRequest); - } - - public boolean is_topologySyncRequested() { - return topologySyncRequested; - } - - public void set_topologySyncRequested(boolean requested) { - this.topologySyncRequested = requested; - } - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfUtils.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfUtils.java deleted file mode 100644 index db2e1311b86c..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchBcfUtils.java +++ /dev/null @@ -1,572 +0,0 @@ -// -// 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.network.bigswitch; - -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.net.util.SubnetUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.bouncycastle.util.IPAddress; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.BcfAnswer; -import com.cloud.agent.api.BcfCommand; -import com.cloud.agent.api.CacheBcfTopologyCommand; -import com.cloud.agent.api.GetControllerDataAnswer; -import com.cloud.agent.api.GetControllerDataCommand; -import com.cloud.agent.api.SyncBcfTopologyCommand; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.VlanDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.network.Network; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.bigswitch.TopologyData.Port; -import com.cloud.network.dao.BigSwitchBcfDao; -import com.cloud.network.dao.FirewallRulesCidrsDao; -import com.cloud.network.dao.FirewallRulesCidrsVO; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.vpc.NetworkACLItem; -import com.cloud.network.vpc.NetworkACLItemCidrsDao; -import com.cloud.network.vpc.NetworkACLItemCidrsVO; -import com.cloud.network.vpc.NetworkACLItemDao; -import com.cloud.network.vpc.NetworkACLItemVO; -import com.cloud.network.vpc.Vpc; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.VMInstanceDao; - -public class BigSwitchBcfUtils { - protected Logger logger = LogManager.getLogger(getClass()); - - private final NetworkDao _networkDao; - private final NicDao _nicDao; - private final VMInstanceDao _vmDao; - private final HostDao _hostDao; - private final VpcDao _vpcDao; - private final BigSwitchBcfDao _bigswitchBcfDao; - private final AgentManager _agentMgr; - private final VlanDao _vlanDao; - private final IPAddressDao _ipAddressDao; - private final FirewallRulesDao _fwRulesDao; - private final FirewallRulesCidrsDao _fwCidrsDao; - private final NetworkACLItemDao _aclItemDao; - private final NetworkACLItemCidrsDao _aclItemCidrsDao; - private final NetworkModel _networkModel; - - public BigSwitchBcfUtils(NetworkDao networkDao, - NicDao nicDao, VMInstanceDao vmDao, HostDao hostDao, - VpcDao vpcDao, BigSwitchBcfDao bigswitchBcfDao, - AgentManager agentMgr, VlanDao vlanDao, IPAddressDao ipAddressDao, - FirewallRulesDao fwRulesDao, FirewallRulesCidrsDao fwCidrsDao, - NetworkACLItemDao aclItemDao, NetworkACLItemCidrsDao aclItemCidrsDao, - NetworkModel networkModel){ - _networkDao = networkDao; - _nicDao = nicDao; - _vmDao = vmDao; - _hostDao = hostDao; - _vpcDao = vpcDao; - _bigswitchBcfDao = bigswitchBcfDao; - _agentMgr = agentMgr; - _vlanDao = vlanDao; - _ipAddressDao = ipAddressDao; - _fwRulesDao = fwRulesDao; - _fwCidrsDao = fwCidrsDao; - _aclItemDao = aclItemDao; - _aclItemCidrsDao = aclItemCidrsDao; - _networkModel = networkModel; - } - - public ControlClusterData getControlClusterData(long physicalNetworkId){ - ControlClusterData cluster = new ControlClusterData(); - - // reusable command to query all devices - GetControllerDataCommand cmd = new GetControllerDataCommand(); - - // retrieve all registered BCF devices - List devices = _bigswitchBcfDao.listByPhysicalNetwork(physicalNetworkId); - for (BigSwitchBcfDeviceVO d: devices){ - HostVO bigswitchBcfHost = _hostDao.findById(d.getHostId()); - if (bigswitchBcfHost == null){ - continue; - } - - _hostDao.loadDetails(bigswitchBcfHost); - GetControllerDataAnswer answer = (GetControllerDataAnswer) _agentMgr.easySend(bigswitchBcfHost.getId(), cmd); - if (answer != null){ - if (answer.isPrimary()) { - cluster.setPrimary(bigswitchBcfHost); - } else { - cluster.setSecondary(bigswitchBcfHost); - } - } - } - return cluster; - } - - public TopologyData getTopology(){ - long physicalNetworkId; - List devices = _bigswitchBcfDao.listAll(); - if(!devices.isEmpty()){ - physicalNetworkId = devices.get(0).getPhysicalNetworkId(); - return getTopology(physicalNetworkId); - } else { - return null; - } - } - - public NetworkVO getPublicNetwork(long physicalNetworkId){ - List pubNets = _networkDao.listByPhysicalNetworkTrafficType(physicalNetworkId, TrafficType.Public); - return pubNets.get(0); - } - - public TopologyData getTopology(long physicalNetworkId){ - List networks; - List nics; - - networks = _networkDao.listByPhysicalNetworkTrafficType(physicalNetworkId, TrafficType.Guest); - - TopologyData topo = new TopologyData(); - - // networks: - // - all user created networks (VPC or non-VPC) - // - one external network - // routers: - // - per VPC (handle in network loop) - // - per stand-alone network (handle in network loop) - // - one external router - - // handle external network first, only if NAT service is enabled - if(networks != null) { - if(!(networks.isEmpty()) && isNatEnabled()){ - // get public net info - needed to set up source nat gateway - NetworkVO pubNet = getPublicNetwork(physicalNetworkId); - - // locate subnet info - SearchCriteria sc = _vlanDao.createSearchCriteria(); - sc.setParameters("network_id", pubNet.getId()); - VlanVO vlanVO = _vlanDao.findOneBy(sc); - - // add tenant external network external - TopologyData.Network network = topo.new Network(); - network.setId("external"); - network.setName("external"); - network.setTenantId("external"); - network.setTenantName("external"); - - String pubVlan = null; - try { - pubVlan = BroadcastDomainType.getValue(vlanVO.getVlanTag()); - if(StringUtils.isNumeric(pubVlan)){ - network.setVlan(Integer.valueOf(pubVlan)); - } else { - // untagged - pubVlan = "0"; - } - } catch (URISyntaxException e) { - e.printStackTrace(); - } - - topo.addNetwork(network); - } - } - - // routerMap used internally for multiple updates to same tenant's router - // add back to topo.routers after loop - HashMap routerMap = new HashMap(); - - for (NetworkVO netVO: networks){ - TopologyData.Network network = topo.new Network(); - network.setId(netVO.getUuid()); - network.setName(netVO.getName()); - - Integer vlan = null; - if (netVO.getBroadcastUri() != null) { - String vlanStr = BroadcastDomainType.getValue(netVO.getBroadcastUri()); - if(StringUtils.isNumeric(vlanStr)){ - vlan = Integer.valueOf(vlanStr); - } else { - // untagged - vlan = 0; - } - } - network.setVlan(vlan); - network.setState(netVO.getState().name()); - - nics = _nicDao.listByNetworkId(netVO.getId()); - List ports = new ArrayList(); - String tenantId = null; - String tenantName = null; - - // if VPC network, assign BCF tenant id with vpc uuid - Vpc vpc = null; - if(netVO.getVpcId()!=null){ - vpc = _vpcDao.acquireInLockTable(netVO.getVpcId()); - } - - if (vpc != null) { - tenantId = vpc.getUuid(); - tenantName = vpc.getName(); - } else { - tenantId = netVO.getUuid(); - tenantName = netVO.getName(); - } - - for(NicVO nic: nics){ - NetworkData netData = new NetworkData(); - TopologyData.Port p = topo.new Port(); - - p.setAttachmentInfo(netData.new AttachmentInfo(nic.getUuid(),nic.getMacAddress())); - - VMInstanceVO vm = _vmDao.findById(nic.getInstanceId()); - HostVO host = _hostDao.findById(vm.getHostId()); - - // if host not found, ignore this nic - if (host == null) { - continue; - } - - String hostname = host.getName(); - long zoneId = netVO.getDataCenterId(); - String vmwareVswitchLabel = _networkModel.getDefaultGuestTrafficLabel(zoneId, HypervisorType.VMware); - String[] labelArray = null; - String vswitchName = null; - if(vmwareVswitchLabel!=null){ - labelArray=vmwareVswitchLabel.split(","); - vswitchName = labelArray[0]; - } - - // hypervisor type: - // kvm: ivs port name - // vmware: specific portgroup naming convention - String pgName = ""; - if (host.getHypervisorType() == HypervisorType.KVM){ - pgName = hostname; - } else if (host.getHypervisorType() == HypervisorType.VMware){ - pgName = hostname + "-" + vswitchName; - } - - p.setHostId(pgName); - - p.setSegmentInfo(netData.new SegmentInfo(BroadcastDomainType.Vlan.name(), vlan)); - - p.setOwner(BigSwitchBcfApi.getCloudstackInstanceId()); - - List ipList = new ArrayList(); - ipList.add(new AttachmentData().getAttachment().new IpAddress(nic.getIPv4Address())); - p.setIpAddresses(ipList); - - p.setId(nic.getUuid()); - - p.setMac(nic.getMacAddress()); - - netData.getNetwork().setId(network.getId()); - netData.getNetwork().setName(network.getName()); - netData.getNetwork().setTenantId(tenantId); - netData.getNetwork().setTenantName(tenantName); - netData.getNetwork().setState(netVO.getState().name()); - - p.setNetwork(netData.getNetwork()); - ports.add(p); - } - network.setTenantId(tenantId); - network.setTenantName(tenantName); - network.setPorts(ports); - topo.addNetwork(network); - - // add router for network - RouterData routerData; - if(tenantId != null){ - if(!routerMap.containsKey(tenantId)){ - routerData = new RouterData(tenantId); - routerMap.put(tenantId, routerData); - } else { - routerData = routerMap.get(tenantId); - } - - routerData.getRouter().getAcls().addAll(listACLbyNetwork(netVO)); - if(vpc != null){ - routerData.getRouter().addExternalGateway(getPublicIpByVpc(vpc)); - } else { - routerData.getRouter().addExternalGateway(getPublicIpByNetwork(netVO)); - } - - RouterInterfaceData intf = new RouterInterfaceData(tenantId, netVO.getGateway(), netVO.getCidr(), - netVO.getUuid(), netVO.getName()); - routerData.getRouter().addInterface(intf); - } - } - - for(RouterData rd: routerMap.values()) { - topo.addRouter(rd.getRouter()); - } - - return topo; - } - - public String getPublicIpByNetwork(Network network){ - List allocatedIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), true); - for (IPAddressVO ip: allocatedIps){ - if(ip.isSourceNat()){ - return ip.getAddress().addr(); - } - } - return null; - } - - public String getPublicIpByVpc(Vpc vpc){ - List allocatedIps = _ipAddressDao.listByAssociatedVpc(vpc.getId(), true); - for (IPAddressVO ip: allocatedIps){ - if(ip.isSourceNat()){ - return ip.getAddress().addr(); - } - } - return null; - } - - public List listACLbyNetwork(Network network){ - List aclList = new ArrayList(); - - List fwRules; - fwRules = _fwRulesDao.listByNetworkAndPurposeAndNotRevoked(network.getId(), Purpose.Firewall); - List fwCidrList = null; - SubnetUtils utils; - - for(FirewallRuleVO rule: fwRules){ - AclData acl = new AclData(); - acl.setId(rule.getUuid()); - acl.setPriority((int)rule.getId()); // CloudStack Firewall interface does not have priority - acl.setIpProto(rule.getProtocol()); - String cidr = null; - Integer port = rule.getSourcePortStart(); - fwCidrList = _fwCidrsDao.listByFirewallRuleId(rule.getId()); - if(fwCidrList != null){ - if(fwCidrList.size()>1 || !rule.getSourcePortEnd().equals(port)){ - continue; - } else { - cidr = fwCidrList.get(0).getCidr(); - } - } - if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) { - cidr = ""; - } else { - utils = new SubnetUtils(cidr); - if(!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())){ - continue; - } - } - acl.setSource(acl.new AclNetwork(cidr, port)); - acl.setAction("permit"); - - aclList.add(acl); - } - - List aclItems; - List aclCidrList; - - if (network.getNetworkACLId() != null){ - aclItems = _aclItemDao.listByACL(network.getNetworkACLId()); - for(NetworkACLItem item: aclItems){ - AclData acl = new AclData(); - acl.setId(item.getUuid()); - acl.setPriority(item.getNumber()); - acl.setIpProto(item.getProtocol()); - String cidr = null; // currently BCF supports single cidr policy - Integer port = item.getSourcePortStart(); // currently BCF supports single port policy - aclCidrList = _aclItemCidrsDao.listByNetworkACLItemId(item.getId()); - if(aclCidrList != null){ - if(aclCidrList.size()>1 || !item.getSourcePortEnd().equals(port)){ - continue; - } else { - cidr = aclCidrList.get(0).getCidr(); - } - } - if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) { - cidr = ""; - } else { - utils = new SubnetUtils(cidr); - if(!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())){ - continue; - } - } - acl.setSource(acl.new AclNetwork(cidr, port)); - acl.setAction(item.getAction().name()); - - aclList.add(acl); - } - } - - return aclList; - } - - public String syncTopologyToBcfHost(HostVO bigswitchBcfHost){ - SyncBcfTopologyCommand syncCmd; - if(isNatEnabled()){ - syncCmd = new SyncBcfTopologyCommand(true, true); - } else { - syncCmd = new SyncBcfTopologyCommand(true, false); - } - BcfAnswer syncAnswer = (BcfAnswer) _agentMgr.easySend(bigswitchBcfHost.getId(), syncCmd); - if (syncAnswer == null || !syncAnswer.getResult()) { - logger.error("SyncBcfTopologyCommand failed"); - return null; - } - return syncAnswer.getHash(); - } - - public String syncTopologyToBcfHost(HostVO bigswitchBcfHost, boolean natEnabled){ - SyncBcfTopologyCommand syncCmd; - if(natEnabled){ - syncCmd = new SyncBcfTopologyCommand(true, true); - } else { - syncCmd = new SyncBcfTopologyCommand(true, false); - } - BcfAnswer syncAnswer = (BcfAnswer) _agentMgr.easySend(bigswitchBcfHost.getId(), syncCmd); - if (syncAnswer == null || !syncAnswer.getResult()) { - logger.error("SyncBcfTopologyCommand failed"); - return null; - } - return syncAnswer.getHash(); - } - - public BcfAnswer sendBcfCommandWithNetworkSyncCheck(BcfCommand cmd, Network network)throws IllegalArgumentException{ - // get registered Big Switch controller - ControlClusterData cluster = getControlClusterData(network.getPhysicalNetworkId()); - if(cluster.getPrimary()==null){ - return new BcfAnswer(cmd, new CloudRuntimeException("Big Switch Network controller temporarily unavailable")); - } - - TopologyData topo = getTopology(network.getPhysicalNetworkId()); - - cmd.setTopology(topo); - BcfAnswer answer = (BcfAnswer) _agentMgr.easySend(cluster.getPrimary().getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error ("BCF API Command failed"); - throw new IllegalArgumentException("Failed API call to Big Switch Network plugin"); - } - - String newHash = answer.getHash(); - if (cmd.isTopologySyncRequested()) { - newHash = syncTopologyToBcfHost(cluster.getPrimary()); - } - if(newHash != null){ - commitTopologyHash(network.getPhysicalNetworkId(), newHash); - } - - HostVO secondary = cluster.getSecondary(); - if(secondary != null){ - TopologyData newTopo = getTopology(network.getPhysicalNetworkId()); - CacheBcfTopologyCommand cacheCmd = new CacheBcfTopologyCommand(newTopo); - _agentMgr.easySend(cluster.getSecondary().getId(), cacheCmd); - } - - return answer; - } - - @DB - public Boolean commitTopologyHash(long physicalNetworkId, final String hash) { - final List devices = _bigswitchBcfDao.listByPhysicalNetwork(physicalNetworkId); - - return Transaction.execute(new TransactionCallback() { - @Override - public Boolean doInTransaction(TransactionStatus status) { - for (BigSwitchBcfDeviceVO d: devices){ - d.setHash(hash); - _bigswitchBcfDao.update(d.getId(), d); - } - return true; - } - }); - } - - public Boolean isNatEnabled(){ - List devices = _bigswitchBcfDao.listAll(); - if(devices != null && !devices.isEmpty()){ - return devices.get(0).getNat(); - } else { - return false; - } - } - - public Integer getSubnetMaskLength(String maskString){ - if(!IPAddress.isValidIPv4(maskString)){ - return null; - } - String[] octets = maskString.split("\\."); - Integer bits = 0; - for (String o: octets){ - switch(o){ - case "255": - bits += 8; - continue; - case "254": - bits += 7; - return bits; - case "252": - bits += 6; - return bits; - case "248": - bits += 5; - return bits; - case "240": - bits += 4; - return bits; - case "224": - bits += 3; - return bits; - case "192": - bits += 2; - return bits; - case "128": - bits += 1; - return bits; - case "0": - return bits; - default: - throw new NumberFormatException("non-contiguous subnet mask not supported"); - } - } - return bits; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchStatus.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchStatus.java deleted file mode 100644 index 0b3a895b2c2d..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/BigSwitchStatus.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.network.bigswitch; - -public class BigSwitchStatus { - private boolean topologySyncRequested = false; - - public boolean isTopologySyncRequested() { - return topologySyncRequested; - } - - public void setTopologySyncRequested(boolean topologySyncRequested) { - this.topologySyncRequested = topologySyncRequested; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/Capabilities.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/Capabilities.java deleted file mode 100644 index b033a8467c63..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/Capabilities.java +++ /dev/null @@ -1,34 +0,0 @@ -// -// 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.network.bigswitch; - -import java.util.List; - -public class Capabilities extends BigSwitchStatus { - private List capabilities; - - public List getCapabilities() { - return capabilities; - } - - public void setCapabilities(List caps) { - capabilities = caps; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterData.java deleted file mode 100644 index 05edbc4f5531..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterData.java +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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.network.bigswitch; - -import com.cloud.host.HostVO; - -public class ControlClusterData { - private HostVO primary; - private HostVO secondary; - - public HostVO getPrimary() { - return primary; - } - - public void setPrimary(HostVO primary) { - this.primary = primary; - } - - public HostVO getSecondary() { - return secondary; - } - - public void setSecondary(HostVO secondary) { - this.secondary = secondary; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterStatus.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterStatus.java deleted file mode 100644 index 8a17bea37949..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControlClusterStatus.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.network.bigswitch; - -public class ControlClusterStatus extends BigSwitchStatus { - private boolean healthy; - - public boolean getStatus() { - return healthy; - } - - public void setStatus(boolean status) { - this.healthy = status; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControllerData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControllerData.java deleted file mode 100644 index ee16a3ce88f8..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/ControllerData.java +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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.network.bigswitch; - -public class ControllerData { - private final String ipAddress; - private final boolean isPrimary; - - public ControllerData(String ipAddress, boolean isPrimary) { - this.ipAddress = ipAddress; - this.isPrimary = isPrimary; - } - - public String getIpAddress() { - return ipAddress; - } - - public boolean isPrimary() { - return isPrimary; - } - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/FloatingIpData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/FloatingIpData.java deleted file mode 100644 index 6e2c422b3680..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/FloatingIpData.java +++ /dev/null @@ -1,93 +0,0 @@ -// -// 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.network.bigswitch; - -import com.google.gson.annotations.SerializedName; - -public class FloatingIpData { - @SerializedName("router_id") private String routerId; - @SerializedName("tenant_id") private String tenantId; - @SerializedName("floating_network_id") private String networkId; - @SerializedName("fixed_ip_address") private String fixedIp; - @SerializedName("floating_ip_address") private String floatingIp; - @SerializedName("floating_mac_address") private String mac; - @SerializedName("id") private String id; - - public FloatingIpData(){ - this.mac = null; - } - - public String getRouterId() { - return routerId; - } - - public void setRouterId(String routerId) { - this.routerId = routerId; - } - - public String getTenantId() { - return tenantId; - } - - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - - public String getNetworkId() { - return networkId; - } - - public void setNetworkId(String networkId) { - this.networkId = networkId; - } - - public String getFixedIp() { - return fixedIp; - } - - public void setFixedIp(String fixedIp) { - this.fixedIp = fixedIp; - } - - public String getFloatingIp() { - return floatingIp; - } - - /*** - * current implementation auto-generates id using public ip - * replacing "." with "-" - ***/ - public void setFloatingIpAndId(String floatingIp) { - this.floatingIp = floatingIp; - this.id = floatingIp.replace(".", "-"); - } - - public String getMac() { - return mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - - public String getId() { - return id; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/NetworkData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/NetworkData.java deleted file mode 100644 index cafbc90135d1..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/NetworkData.java +++ /dev/null @@ -1,217 +0,0 @@ -// -// 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.network.bigswitch; - -import java.util.List; - -import com.google.gson.annotations.SerializedName; - -/** - * NetworkData contains information expected by Big Switch Controller - * in CreateBcfSegmentCommand - */ -public class NetworkData { - private final Network network; - - public Network getNetwork() { - return network; - } - - public NetworkData() { - network = new Network(); - } - - public class Network { - @SerializedName("id") private String id; - @SerializedName("name") private String name = null; - @SerializedName("tenant_id") private String tenantId = null; - @SerializedName("tenant_name") private String tenantName = null; - @SerializedName("state") private String state = null; - @SerializedName("subnets") private List segments = null; - @SerializedName("provider:segmentation_id") private Integer vlan = null; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTenantId() { - return tenantId; - } - - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - - public String getTenantName() { - return tenantName; - } - - public void setTenantName(String tenantName) { - this.tenantName = tenantName; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public List getSegments() { - return segments; - } - - public void setSegments(List segments) { - this.segments = segments; - } - - public Integer getVlan() { - return vlan; - } - - public void setVlan(Integer vlan) { - this.vlan = vlan; - } - } - - public class Segment { - @SerializedName("cidr") private String cidr; - @SerializedName("gateway_ip") private String gatewayIp; - @SerializedName("id") private String id; - @SerializedName("name") private String name; - @SerializedName("state") private String state; - @SerializedName("tenant_id") private String tenantId; - - public String getCidr() { - return cidr; - } - - public void setCidr(String cidr) { - this.cidr = cidr; - } - - public String getGatewayIp() { - return gatewayIp; - } - - public void setGatewayIp(String gatewayIp) { - this.gatewayIp = gatewayIp; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getTenantId() { - return tenantId; - } - - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - } - - - - public class AttachmentInfo { - @SerializedName("id") private String id = null; - @SerializedName("mac") private String mac = null; - - public AttachmentInfo(String id, String mac){ - this.id = id; - this.mac = mac; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMac() { - return mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - } - - public class SegmentInfo { - @SerializedName("network_type") private String networkType = null; - @SerializedName("segmentation_id") private Integer segmentationId = 0; - - public SegmentInfo(String networkType, Integer segmentationId){ - this.networkType = networkType; - this.segmentationId = segmentationId; - } - - public String getNetworkType() { - return networkType; - } - - public void setNetworkType(String networkType) { - this.networkType = networkType; - } - - public Integer getSegmentationId() { - return segmentationId; - } - - public void setSegmentationId(Integer segmentationId) { - this.segmentationId = segmentationId; - } - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterData.java deleted file mode 100644 index 2d616533cc58..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterData.java +++ /dev/null @@ -1,131 +0,0 @@ -// -// 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.network.bigswitch; - -import java.util.ArrayList; -import java.util.List; - -import com.google.gson.annotations.SerializedName; - -public class RouterData { - @SerializedName("router") private Router router; - - public RouterData(String tenantId){ - router = new Router(tenantId); - } - - public class Router { - @SerializedName("tenant_id") private String tenantId; - @SerializedName("id") private String id; - @SerializedName("external_gateway_info") private ExternalGateway externalGateway; - @SerializedName("router_rules") private List acls; - @SerializedName("interfaces") private List interfaces; - - public Router(String tenantId){ - this.tenantId = tenantId; - this.id = tenantId; - this.externalGateway = null; - this.acls = new ArrayList(); - this.interfaces = null; - } - - public List getAcls() { - return acls; - } - - public class ExternalGateway{ - @SerializedName("tenant_id") private String tenantId; - @SerializedName("network_id") private String networkId; - @SerializedName("external_fixed_ips") private List externalIps; - - public ExternalGateway(String gatewayIp){ - this.tenantId = "external"; - this.networkId = "external"; - this.externalIps = new ArrayList(); - if(gatewayIp!=null){ - this.externalIps.add(new ExternalIp(gatewayIp)); - } - } - - public class ExternalIp{ - @SerializedName("subnet_id") private String subnetId; //assume don't care for now - @SerializedName("ip_address") private String ipAddress; - - public ExternalIp(String ipAddress){ - this.subnetId = ""; - this.ipAddress = ipAddress; - } - - public String getSubnetId() { - return subnetId; - } - - public String getIpAddress() { - return ipAddress; - } - } - - public String getNetworkId() { - return networkId; - } - - public List getExternalIps() { - return externalIps; - } - } - - public void addExternalGateway(String gatewayIp){ - if(gatewayIp != null){ - this.externalGateway = new ExternalGateway(gatewayIp); - } - } - - public String getTenantId() { - return tenantId; - } - - public String getId() { - return id; - } - - public ExternalGateway getExternalGateway() { - return externalGateway; - } - - public List getInterfaces() { - return interfaces; - } - - public void addInterface(RouterInterfaceData intf){ - if(this.interfaces == null){ - this.interfaces = new ArrayList(); - } - this.interfaces.add(intf.getRouterInterface()); - } - - public void setInterfaces(List interfaces) { - this.interfaces = interfaces; - } - } - - public Router getRouter() { - return router; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterInterfaceData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterInterfaceData.java deleted file mode 100644 index a00535e7c98b..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/RouterInterfaceData.java +++ /dev/null @@ -1,67 +0,0 @@ -// -// 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.network.bigswitch; - -import com.google.gson.annotations.SerializedName; - -public class RouterInterfaceData { - @SerializedName("interface") private RouterInterface routerInterface; - - public RouterInterfaceData(String tenantId, String gatewayIp, String cidr, String id, String name){ - routerInterface = new RouterInterface(tenantId, gatewayIp, cidr, id, name); - } - - public class RouterInterface { - @SerializedName("subnet") private NetworkData.Segment subnet; - @SerializedName("id") private String id; - @SerializedName("network") private NetworkData.Network network; - - public RouterInterface(String tenantId, String gatewayIp, String cidr, String id, String name){ - NetworkData data = new NetworkData(); - this.subnet = data.new Segment(); - this.subnet.setTenantId(tenantId); - this.subnet.setGatewayIp(gatewayIp); - this.subnet.setCidr(cidr); - - this.id = id; - - this.network = data.getNetwork(); - this.network.setTenantId(tenantId); - this.network.setId(id); - this.network.setName(name); - } - - public NetworkData.Segment getSubnet() { - return subnet; - } - - public String getId() { - return id; - } - - public NetworkData.Network getNetwork() { - return network; - } - } - - public RouterInterface getRouterInterface() { - return routerInterface; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TopologyData.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TopologyData.java deleted file mode 100644 index cbaeefffc649..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TopologyData.java +++ /dev/null @@ -1,249 +0,0 @@ -// -// 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.network.bigswitch; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.network.bigswitch.AttachmentData.Attachment.IpAddress; -import com.cloud.network.bigswitch.NetworkData.AttachmentInfo; -import com.cloud.network.bigswitch.NetworkData.Segment; -import com.cloud.network.bigswitch.NetworkData.SegmentInfo; -import com.cloud.network.bigswitch.RouterData.Router; -import com.google.gson.annotations.SerializedName; - -public class TopologyData { - @SerializedName("networks") private final List networks; - @SerializedName("routers") private final List routers; - - public void addNetwork(Network network) { - networks.add(network); - } - - public void setNetworks(List networks) { - this.networks.clear(); - this.networks.addAll(networks); - } - - public void clearNetworks() { - this.networks.clear(); - } - - public void addRouter(Router router) { - routers.add(router); - } - - public void setRouters(List routers) { - this.routers.clear(); - this.routers.addAll(routers); - } - - public void clearRouters() { - this.routers.clear(); - } - - public TopologyData() { - networks = new ArrayList(); - routers = new ArrayList(); - } - - public class Network { - @SerializedName("id") private String id; - @SerializedName("name") private String name; - @SerializedName("tenant_id") private String tenantId; - @SerializedName("tenant_name") private String tenantName; - @SerializedName("provider:segmentation_id") private Integer vlan = null; - @SerializedName("state") private String state; - @SerializedName("ports") private List ports; - @SerializedName("subnets") private List segments; - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getTenantId() { - return tenantId; - } - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - public String getTenantName() { - return tenantName; - } - public void setTenantName(String tenantName) { - this.tenantName = tenantName; - } - public Integer getVlan() { - return vlan; - } - public void setVlan(Integer vlan) { - this.vlan = vlan; - } - public String getState() { - return state; - } - public void setState(String state) { - this.state = state; - } - public List getPorts() { - return ports; - } - public void setPorts(List ports) { - this.ports = ports; - } - public List getSegments() { - return segments; - } - public void setSegments(List segments) { - this.segments = segments; - } - @Override - public String toString() { - return "Network [id=" + id + ", name=" + name + ", tenantId=" - + tenantId + ", tenantName=" + tenantName + ", vlan=" - + vlan + ", state=" + state + ", ports=" + ports - + ", segments=" + segments + "]"; - } - } - - public class Port { - @SerializedName("attachment") private AttachmentInfo attachment; - @SerializedName("binding:host_id") private String hostId; - @SerializedName("bound_segment") private SegmentInfo segmentInfo; - @SerializedName("device_owner") private String owner; - @SerializedName("fixed_ips") private List ipAddresses; - @SerializedName("id") private String id; - @SerializedName("mac_address") private String mac; - @SerializedName("network") private NetworkData.Network network; - @SerializedName("state") private String state; - @SerializedName("tenant_id") private String tenantId; - @SerializedName("tenant_name") private String tenantName; - - public AttachmentInfo getAttachment() { - return attachment; - } - - public void setAttachmentInfo(AttachmentInfo attachment) { - this.attachment = attachment; - } - - public String getHostId() { - return hostId; - } - - public void setHostId(String hostId) { - this.hostId = hostId; - } - - public SegmentInfo getSegmentInfo() { - return segmentInfo; - } - - public void setSegmentInfo(SegmentInfo segmentInfo) { - this.segmentInfo = segmentInfo; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public List getIpAddresses() { - return ipAddresses; - } - - public void setIpAddresses(List ipAddresses) { - this.ipAddresses = ipAddresses; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMac() { - return mac; - } - - public void setMac(String mac) { - this.mac = mac; - } - - public NetworkData.Network getNetwork() { - return network; - } - - public void setNetwork(NetworkData.Network network) { - this.network = network; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getTenantId() { - return tenantId; - } - - public void setTenantId(String tenantId) { - this.tenantId = tenantId; - } - - public String getTenantName() { - return tenantName; - } - - public void setTenantName(String tenantName) { - this.tenantName = tenantName; - } - } - - public List getNetworks() { - return networks; - } - - public List getRouters() { - return routers; - } - - @Override - public String toString() { - return "TopologyData [networks=" + networks + ", routers=" + routers - + "]"; - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TrustingProtocolSocketFactory.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TrustingProtocolSocketFactory.java deleted file mode 100644 index 09c444b96576..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/TrustingProtocolSocketFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -// -// 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.network.bigswitch; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.params.HttpConnectionParams; -import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; - -/* - * The TrustingProtocolSocketFactory will accept any provided - * certificate, i.e., in a sticky mode certificate management scheme, - * when making an SSL connection to the Big Switch Controller - */ -public class TrustingProtocolSocketFactory implements SecureProtocolSocketFactory { - private SSLSocketFactory ssf; - - public TrustingProtocolSocketFactory() throws IOException { - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { - new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - - @Override - public void checkClientTrusted(X509Certificate[] certs, String authType) { - // Trust always - } - - @Override - public void checkServerTrusted(X509Certificate[] certs, String authType) { - // Trust always - } - } - }; - - try { - // Install the all-trusting trust manager - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - ssf = sc.getSocketFactory(); - } catch (KeyManagementException e) { - throw new IOException(e); - } catch (NoSuchAlgorithmException e) { - throw new IOException(e); - } - } - - @Override - public Socket createSocket(String host, int port) throws IOException, - UnknownHostException { - return ssf.createSocket(host, port); - } - - @Override - public Socket createSocket(String address, int port, InetAddress localAddress, - int localPort) throws IOException, UnknownHostException { - return ssf.createSocket(address, port, localAddress, localPort); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, - boolean autoClose) throws IOException, UnknownHostException { - return ssf.createSocket(socket, host, port, autoClose); - } - - @Override - public Socket createSocket(String host, int port, InetAddress localAddress, - int localPort, HttpConnectionParams params) throws IOException, - UnknownHostException, ConnectTimeoutException { - int timeout = params.getConnectionTimeout(); - if (timeout == 0) { - return createSocket(host, port, localAddress, localPort); - } - else { - Socket s = ssf.createSocket(); - s.bind(new InetSocketAddress(localAddress, localPort)); - s.connect(new InetSocketAddress(host, port), timeout); - return s; - } - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDao.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDao.java deleted file mode 100644 index 8cf84e4a7776..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDao.java +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.utils.db.GenericDao; - -public interface BigSwitchBcfDao extends GenericDao { - /** - * list all the BigSwitch BCF Controller devices added in to this physical network - * @param physicalNetworkId physical Network Id - * @return list of BigSwitchBcfDeviceVO for this physical network. - */ - List listByPhysicalNetwork(long physicalNetworkId); - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDaoImpl.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDaoImpl.java deleted file mode 100644 index 67a83e129ddc..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/dao/BigSwitchBcfDaoImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class BigSwitchBcfDaoImpl extends GenericDaoBase implements BigSwitchBcfDao { - - protected final SearchBuilder physicalNetworkIdSearch; - - public BigSwitchBcfDaoImpl() { - physicalNetworkIdSearch = createSearchBuilder(); - physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); - physicalNetworkIdSearch.done(); - } - - @Override - public List listByPhysicalNetwork(long physicalNetworkId) { - SearchCriteria sc = physicalNetworkIdSearch.create(); - sc.setParameters("physicalNetworkId", physicalNetworkId); - return search(sc, null); - } - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElement.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElement.java deleted file mode 100644 index db0efd71b1d5..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElement.java +++ /dev/null @@ -1,783 +0,0 @@ -// -// 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.network.element; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.springframework.stereotype.Component; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; -import org.apache.commons.net.util.SubnetUtils; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.BcfAnswer; -import com.cloud.agent.api.UpdateBcfRouterCommand; -import com.cloud.agent.api.CreateBcfAttachmentCommand; -import com.cloud.agent.api.CreateBcfStaticNatCommand; -import com.cloud.agent.api.DeleteBcfAttachmentCommand; -import com.cloud.agent.api.DeleteBcfStaticNatCommand; -import com.cloud.agent.api.StartupBigSwitchBcfCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddBigSwitchBcfDeviceCmd; -import com.cloud.api.commands.DeleteBigSwitchBcfDeviceCmd; -import com.cloud.api.commands.ListBigSwitchBcfDevicesCmd; -import com.cloud.api.commands.BcfConstants; -import com.cloud.api.response.BigSwitchBcfDeviceResponse; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.DetailVO; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.bigswitch.AclData; -import com.cloud.network.bigswitch.BigSwitchBcfApi; -import com.cloud.network.bigswitch.BigSwitchBcfUtils; -import com.cloud.network.bigswitch.TopologyData; -import com.cloud.network.dao.BigSwitchBcfDao; -import com.cloud.network.dao.FirewallRulesCidrsDao; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.resource.BigSwitchBcfResource; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.StaticNat; -import com.cloud.network.vpc.NetworkACLItem; -import com.cloud.network.vpc.NetworkACLItemCidrsDao; -import com.cloud.network.vpc.NetworkACLItemDao; -import com.cloud.network.vpc.Vpc; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceState; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.DomainRouterDao; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.VMInstanceDao; - -/** - * BigSwitchBcfElement is responsible for creating and plugging a nic into a BCF Segment network. - * When a VM is created and needs to be plugged into a BCF Segment network, BigSwitchBcfElement is - * called by NetworkOrchestrator to create a "port" and an "attachment" for each nic, and - * register them with the controller to be plugged into the corresponding network. It also - * removes them when the VM is destroyed. - */ -@Component -public class BigSwitchBcfElement extends AdapterBase implements BigSwitchBcfElementService, -ConnectivityProvider, IpDeployer, SourceNatServiceProvider, StaticNatServiceProvider, -NetworkACLServiceProvider, FirewallServiceProvider, ResourceStateAdapter { - - private static final Map> capabilities = setCapabilities(); - - @Inject - ResourceManager _resourceMgr; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - @Inject - BigSwitchBcfDao _bigswitchBcfDao; - @Inject - HostDetailsDao _hostDetailsDao; - @Inject - HostDao _hostDao; - @Inject - AgentManager _agentMgr; - @Inject - NetworkDao _networkDao; - @Inject - DomainRouterDao _routerDao; - @Inject - NicDao _nicDao; - @Inject - VMInstanceDao _vmDao; - @Inject - AccountDao _accountDao; - @Inject - VpcDao _vpcDao; - @Inject - NetworkModel _networkModel; - @Inject - ConfigurationManager _configMgr; - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - DataCenterDao _zoneDao; - @Inject - IPAddressDao _ipAddressDao; - @Inject - IpAddressManager _ipAddrMgr; - @Inject - VlanDao _vlanDao; - @Inject - FirewallRulesDao _fwRulesDao; - @Inject - FirewallRulesCidrsDao _fwCidrsDao; - @Inject - NetworkACLItemDao _aclItemDao; - @Inject - NetworkACLItemCidrsDao _aclItemCidrsDao; - - private BigSwitchBcfUtils _bcfUtils = null; - - @Override - public Map> getCapabilities() { - return capabilities; - } - - @Override - public Provider getProvider() { - return Provider.BigSwitchBcf; - } - - private boolean canHandle(Network network, Service service) { - logger.debug(String.format("Checking if BigSwitchBcfElement can handle service %s on network %s", service.getName(), network)); - if (network.getBroadcastDomainType() != BroadcastDomainType.Vlan) { - return false; - } - - if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) { - logger.debug(String.format("BigSwitchBcfElement is not a provider for network %s", network)); - return false; - } - - if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, BcfConstants.BIG_SWITCH_BCF)) { - logger.debug(String.format("BigSwitchBcfElement can't provide the %s service on network %s", service.getName(), network)); - return false; - } - - return true; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); - return true; - } - - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - updateBcfRouter(network); - return true; - } - - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - bcfUtilsInit(); - - // get arguments for CreateBcfAttachmentCommand - // determine whether this is VPC network or stand-alone network - Vpc vpc = null; - if (network.getVpcId() != null) { - vpc = _vpcDao.acquireInLockTable(network.getVpcId()); - } - - String tenantId; - String tenantName; - if (vpc != null) { - tenantId = vpc.getUuid(); - tenantName = vpc.getName(); - _vpcDao.releaseFromLockTable(vpc.getId()); - } else { - // use account in CS as tenant in BSN - // use network id/name as tenant id/name for non-VPC networks - tenantId = network.getUuid(); - tenantName = network.getName(); - } - - String networkId = network.getUuid(); - String hostname = dest.getHost().getName(); - String nicId = nic.getUuid(); - Integer vlan = Integer.valueOf(BroadcastDomainType.getValue(nic.getIsolationUri())); - String ipv4 = nic.getIPv4Address(); - String mac = nic.getMacAddress(); - long zoneId = network.getDataCenterId(); - String vmwareVswitchLabel = _networkModel.getDefaultGuestTrafficLabel(zoneId, HypervisorType.VMware); - String[] labelArray = null; - String vswitchName = null; - if (vmwareVswitchLabel != null) { - labelArray=vmwareVswitchLabel.split(","); - vswitchName = labelArray[0]; - } - - // hypervisor type: - // kvm: ivs port name - // vmware: specific portgroup naming convention - String pgName = ""; - if (dest.getHost().getHypervisorType() == HypervisorType.KVM) { - pgName = hostname; - } else if (dest.getHost().getHypervisorType() == HypervisorType.VMware) { - pgName = hostname + "-" + vswitchName; - } - - CreateBcfAttachmentCommand cmd = new CreateBcfAttachmentCommand(tenantId, - tenantName, networkId, pgName, nicId, vlan, ipv4, mac); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, network); - - return true; - } - - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - if (network.getBroadcastUri() == null) { - logger.error("Nic has no broadcast Uri"); - return false; - } - - bcfUtilsInit(); - - String networkId = network.getUuid(); - String nicId = nic.getUuid(); - - String tenantId; - if (network.getVpcId() != null) { - tenantId = network.getNetworkDomain(); - } else { - tenantId = networkId; - } - - DeleteBcfAttachmentCommand cmd = new DeleteBcfAttachmentCommand(tenantId, networkId, nicId); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, network); - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - return true; - } - - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - if (!services.contains(Service.Connectivity)) { - logger.warn("Unable to provide services without Connectivity service enabled for this element"); - return false; - } - return true; - } - - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); - - // L2 Support - capabilities.put(Service.Connectivity, null); - - // L3 Support - capabilities.put(Service.Gateway, null); - - // L3 Support : SourceNat - Map sourceNatCapabilities = new HashMap(); - sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "peraccount"); - sourceNatCapabilities.put(Capability.RedundantRouter, "false"); - capabilities.put(Service.SourceNat, sourceNatCapabilities); - - // L3 support : StaticNat - capabilities.put(Service.StaticNat, null); - - //add network ACL capability - Map networkACLCapabilities = new HashMap(); - networkACLCapabilities.put(Network.Capability.SupportedProtocols, "tcp,udp,icmp"); - capabilities.put(Network.Service.NetworkACL, networkACLCapabilities); - - // Set capabilities for Firewall service - Map firewallCapabilities = new HashMap(); - firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); - firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); - firewallCapabilities.put(Capability.SupportedEgressProtocols, "tcp,udp,icmp, all"); - firewallCapabilities.put(Capability.SupportedTrafficDirection, "ingress, egress"); - firewallCapabilities.put(Capability.MultipleIps, "true"); - capabilities.put(Service.Firewall, firewallCapabilities); - - return capabilities; - } - - @Override - @DB - public BigSwitchBcfDeviceVO addBigSwitchBcfDevice(AddBigSwitchBcfDeviceCmd cmd) { - BigSwitchBcfDeviceVO newBcfDevice; - - bcfUtilsInit(); - - ServerResource resource = new BigSwitchBcfResource(); - - final String deviceName = BcfConstants.BIG_SWITCH_BCF.getName(); - NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName); - final Long physicalNetworkId = cmd.getPhysicalNetworkId(); - final String hostname = cmd.getHost(); - final String username = cmd.getUsername(); - final String password = cmd.getPassword(); - final Boolean nat = cmd.getNat(); - - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); - } - long zoneId = physicalNetwork.getDataCenterId(); - - final PhysicalNetworkServiceProviderVO ntwkSvcProvider = - _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder()); - if (ntwkSvcProvider == null) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is not enabled in the physical network: %s to add this device", - networkDevice.getNetworkServiceProvder(), physicalNetwork)); - } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is in shutdown state in the physical network: %s to add this device", - ntwkSvcProvider.getProviderName(), physicalNetwork)); - } - ntwkSvcProvider.setFirewallServiceProvided(true); - ntwkSvcProvider.setGatewayServiceProvided(true); - ntwkSvcProvider.setNetworkAclServiceProvided(true); - ntwkSvcProvider.setSourcenatServiceProvided(true); - ntwkSvcProvider.setStaticnatServiceProvided(true); - - if (_bigswitchBcfDao.listByPhysicalNetwork(physicalNetworkId).size() > 1) { - throw new CloudRuntimeException("At most two BCF controllers can be configured"); - } - - DataCenterVO zone = _zoneDao.findById(physicalNetwork.getDataCenterId()); - String zoneName; - if (zone != null) { - zoneName = zone.getName(); - } else { - zoneName = String.valueOf(zoneId); - } - - Boolean natNow = _bcfUtils.isNatEnabled(); - if (!nat && natNow) { - throw new CloudRuntimeException("NAT is enabled in existing controller. Enable NAT for new controller or remove existing controller first."); - } else if (nat && !natNow) { - throw new CloudRuntimeException("NAT is disabled in existing controller. Disable NAT for new controller or remove existing controller first."); - } - - Map params = new HashMap(); - params.put("guid", UUID.randomUUID().toString()); - params.put("zoneId", zoneName); - params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); - params.put("name", "BigSwitch Controller - " + cmd.getHost()); - params.put("hostname", cmd.getHost()); - params.put("username", username); - params.put("password", password); - params.put("nat", nat.toString()); - - // FIXME What to do with multiple isolation types - params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase()); - Map hostdetails = new HashMap(); - hostdetails.putAll(params); - - try { - resource.configure(cmd.getHost(), hostdetails); - - // store current topology in bcf resource - TopologyData topo = _bcfUtils.getTopology(physicalNetwork.getId()); - ((BigSwitchBcfResource) resource).setTopology(topo); - - final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params); - if (host != null) { - newBcfDevice = Transaction.execute(new TransactionCallback() { - @Override - public BigSwitchBcfDeviceVO doInTransaction(TransactionStatus status) { - BigSwitchBcfDeviceVO bigswitchBcfDevice = - new BigSwitchBcfDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), - deviceName, hostname, username, password, nat, BigSwitchBcfApi.HASH_IGNORE); - _bigswitchBcfDao.persist(bigswitchBcfDevice); - - DetailVO detail = new DetailVO(host.getId(), "bigswitchbcfdeviceid", String.valueOf(bigswitchBcfDevice.getId())); - _hostDetailsDao.persist(detail); - - return bigswitchBcfDevice; - } - }); - } else { - throw new CloudRuntimeException("Failed to add BigSwitch BCF Controller Device due to internal error."); - } - } catch (ConfigurationException e) { - throw new CloudRuntimeException(e.getMessage()); - } - - // initial topology sync to newly added BCF controller - HostVO bigswitchBcfHost = _hostDao.findById(newBcfDevice.getHostId()); - _bcfUtils.syncTopologyToBcfHost(bigswitchBcfHost, nat); - - return newBcfDevice; - } - - @Override - public BigSwitchBcfDeviceResponse createBigSwitchBcfDeviceResponse(BigSwitchBcfDeviceVO bigswitchBcfDeviceVO) { - HostVO bigswitchBcfHost = _hostDao.findById(bigswitchBcfDeviceVO.getHostId()); - _hostDao.loadDetails(bigswitchBcfHost); - - BigSwitchBcfDeviceResponse response = new BigSwitchBcfDeviceResponse(); - response.setDeviceName(bigswitchBcfDeviceVO.getDeviceName()); - PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(bigswitchBcfDeviceVO.getPhysicalNetworkId()); - if (pnw != null) { - response.setPhysicalNetworkId(pnw.getUuid()); - } - response.setId(bigswitchBcfDeviceVO.getUuid()); - response.setProviderName(bigswitchBcfDeviceVO.getProviderName()); - response.setHostName(bigswitchBcfHost.getDetail("hostname")); - response.setObjectName("bigswitchbcfdevice"); - return response; - } - - @Override - public boolean deleteBigSwitchBcfDevice(DeleteBigSwitchBcfDeviceCmd cmd) { - Long bigswitchBcfDeviceId = cmd.getBigSwitchBcfDeviceId(); - BigSwitchBcfDeviceVO bigswitchBcfDevice = _bigswitchBcfDao.findById(bigswitchBcfDeviceId); - if (bigswitchBcfDevice == null) { - throw new InvalidParameterValueException(String.format("Could not find a BigSwitch Controller with id %d", bigswitchBcfDeviceId)); - } - - HostVO bigswitchHost = _hostDao.findById(bigswitchBcfDevice.getHostId()); - Long hostId = bigswitchHost.getId(); - - bigswitchHost.setResourceState(ResourceState.Maintenance); - _hostDao.update(hostId, bigswitchHost); - _resourceMgr.deleteHost(hostId, false, false); - - _bigswitchBcfDao.remove(bigswitchBcfDeviceId); - return true; - } - - @Override - public List listBigSwitchBcfDevices(ListBigSwitchBcfDevicesCmd cmd) { - Long physicalNetworkId = cmd.getPhysicalNetworkId(); - Long bigswitchBcfDeviceId = cmd.getBigSwitchBcfDeviceId(); - List responseList = new ArrayList(); - - if (physicalNetworkId == null && bigswitchBcfDeviceId == null) { - throw new InvalidParameterValueException("Either physical network Id or bigswitch device Id must be specified"); - } - - if (bigswitchBcfDeviceId != null) { - BigSwitchBcfDeviceVO bigswitchBcfDevice = _bigswitchBcfDao.findById(bigswitchBcfDeviceId); - if (bigswitchBcfDevice == null) { - throw new InvalidParameterValueException(String.format("Could not find BigSwitch controller with id: %d", bigswitchBcfDeviceId)); - } - responseList.add(bigswitchBcfDevice); - } else { - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); - } - responseList = _bigswitchBcfDao.listByPhysicalNetwork(physicalNetworkId); - } - - return responseList; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - return null; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - if (!(startup[0] instanceof StartupBigSwitchBcfCommand)) { - return null; - } - - BigSwitchBcfResource bcfResource = (BigSwitchBcfResource) resource; - bcfUtilsInit(); - - if (_bcfUtils.getTopology() != null) { - bcfResource.setTopology(_bcfUtils.getTopology()); - } - - host.setType(Host.Type.L2Networking); - return host; - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (!(host.getType() == Host.Type.L2Networking)) { - return null; - } - return new DeleteHostAnswer(true); - } - - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddBigSwitchBcfDeviceCmd.class); - cmdList.add(DeleteBigSwitchBcfDeviceCmd.class); - cmdList.add(ListBigSwitchBcfDevicesCmd.class); - return cmdList; - } - - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } - - @Override - public boolean applyStaticNats(Network network, - List rules) - throws ResourceUnavailableException { - bcfUtilsInit(); - - _bcfUtils.listACLbyNetwork(network); - - Vpc vpc = null; - if (network.getVpcId() != null) { - vpc = _vpcDao.acquireInLockTable(network.getVpcId()); - } - - String tenantId; - if (vpc != null) { - tenantId = vpc.getUuid(); - _vpcDao.releaseFromLockTable(vpc.getId()); - } else { - // use account in CS as tenant in BSN - // use network uuid as tenantId for non-VPC networks - tenantId = network.getUuid(); - } - - for (StaticNat rule: rules) { - String srcIp = _ipAddressDao.findById(rule.getSourceIpAddressId()).getAddress().addr(); - String dstIp = rule.getDestIpAddress(); - String mac = rule.getSourceMacAddress(); - if (!rule.isForRevoke()) { - logger.debug("BCF enables static NAT for public IP: " + srcIp + " private IP " + dstIp - + " mac " + mac); - CreateBcfStaticNatCommand cmd = new CreateBcfStaticNatCommand( - tenantId, network.getUuid(), dstIp, srcIp, mac); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, network); - } else { - logger.debug("BCF removes static NAT for public IP: " + srcIp + " private IP " + dstIp - + " mac " + mac); - DeleteBcfStaticNatCommand cmd = new DeleteBcfStaticNatCommand(tenantId, srcIp); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, network); - } - } - return true; - } - - @Override - public boolean applyIps(Network network, - List ipAddress, Set services) - throws ResourceUnavailableException { - return false; - } - - @Override - public boolean applyNetworkACLs(Network network, - List rules) - throws ResourceUnavailableException { - SubnetUtils utils; - String cidr = null; - List cidrList; - for (NetworkACLItem r: rules) { - if (r.getState() == NetworkACLItem.State.Revoke) { - continue; - } - cidrList = r.getSourceCidrList(); - if (cidrList != null) { - if (cidrList.size() > 1 || !r.getSourcePortEnd().equals(r.getSourcePortStart())) { - throw new ResourceUnavailableException("One CIDR and one port only please.", - Network.class, network.getId()); - } else { - cidr = cidrList.get(0); - } - } - if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) { - cidr = ""; - } else { - utils = new SubnetUtils(cidr); - if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) { - throw new ResourceUnavailableException("Invalid CIDR in Network ACL rule.", - Network.class, network.getId()); - } - } - } - updateBcfRouter(network); - return true; - } - - @Override - public boolean reorderAclRules(Vpc vpc, List networks, List networkACLItems) { - return true; - } - - @Override - public boolean applyFWRules(Network network, - List rules) - throws ResourceUnavailableException { - SubnetUtils utils; - String cidr = null; - List cidrList; - for (FirewallRule r: rules) { - if (r.getState() == FirewallRule.State.Revoke) { - continue; - } - cidrList = r.getSourceCidrList(); - if (cidrList != null) { - if (cidrList.size()>1 || !r.getSourcePortEnd().equals(r.getSourcePortStart())) { - throw new ResourceUnavailableException("One CIDR and one port only please.", - Network.class, network.getId()); - } else { - cidr = cidrList.get(0); - } - } - if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) { - cidr = ""; - } else { - utils = new SubnetUtils(cidr); - if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) { - throw new ResourceUnavailableException("Invalid CIDR in Firewall rule.", - Network.class, network.getId()); - } - } - } - updateBcfRouter(network); - return true; - } - - private void updateBcfRouter(Network network) throws IllegalArgumentException{ - bcfUtilsInit(); - - Vpc vpc = null; - if (network.getVpcId() != null) { - vpc = _vpcDao.acquireInLockTable(network.getVpcId()); - } - - String tenantId; - if (vpc != null) { - tenantId = vpc.getUuid(); - _vpcDao.releaseFromLockTable(vpc.getId()); - } else { - tenantId = network.getUuid(); - } - - UpdateBcfRouterCommand cmd = new UpdateBcfRouterCommand(tenantId); - - List aclList = _bcfUtils.listACLbyNetwork(network); - for (AclData acl: aclList) { - cmd.addAcl(acl); - } - - if (vpc != null) { - cmd.setPublicIp(_bcfUtils.getPublicIpByVpc(vpc)); - } else { - cmd.setPublicIp(_bcfUtils.getPublicIpByNetwork(network)); - } - - BcfAnswer answer = _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, network); - if (answer != null && !answer.getResult()) { - throw new IllegalArgumentException("Illegal router update arguments"); - } - } - - private void bcfUtilsInit() { - if (_bcfUtils == null) { - _bcfUtils = new BigSwitchBcfUtils(_networkDao, _nicDao, - _vmDao, _hostDao, _vpcDao, _bigswitchBcfDao, - _agentMgr, _vlanDao, _ipAddressDao, _fwRulesDao, - _fwCidrsDao, _aclItemDao, _aclItemCidrsDao, _networkModel); - } - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElementService.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElementService.java deleted file mode 100644 index 3a6447257999..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/element/BigSwitchBcfElementService.java +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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.network.element; - -import java.util.List; - -import com.cloud.api.commands.AddBigSwitchBcfDeviceCmd; -import com.cloud.api.commands.DeleteBigSwitchBcfDeviceCmd; -import com.cloud.api.commands.ListBigSwitchBcfDevicesCmd; -import com.cloud.api.response.BigSwitchBcfDeviceResponse; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.utils.component.PluggableService; - -public interface BigSwitchBcfElementService extends PluggableService { - - public BigSwitchBcfDeviceVO addBigSwitchBcfDevice(AddBigSwitchBcfDeviceCmd cmd); - - public BigSwitchBcfDeviceResponse createBigSwitchBcfDeviceResponse(BigSwitchBcfDeviceVO bigswitchDeviceVO); - - public boolean deleteBigSwitchBcfDevice(DeleteBigSwitchBcfDeviceCmd cmd); - - public List listBigSwitchBcfDevices(ListBigSwitchBcfDevicesCmd cmd); - -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/guru/BigSwitchBcfGuestNetworkGuru.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/guru/BigSwitchBcfGuestNetworkGuru.java deleted file mode 100644 index 5b764ba129b6..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/guru/BigSwitchBcfGuestNetworkGuru.java +++ /dev/null @@ -1,418 +0,0 @@ -// -// 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.network.guru; - -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.cloudstack.context.CallContext; -import org.apache.commons.lang3.StringUtils; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.CreateBcfAttachmentCommand; -import com.cloud.agent.api.CreateBcfRouterCommand; -import com.cloud.agent.api.CreateBcfRouterInterfaceCommand; -import com.cloud.agent.api.CreateBcfSegmentCommand; -import com.cloud.agent.api.DeleteBcfSegmentCommand; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.event.ActionEventUtils; -import com.cloud.event.EventTypes; -import com.cloud.event.EventVO; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.BigSwitchBcfDeviceVO; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkMigrationResponder; -import com.cloud.network.NetworkProfile; -import com.cloud.network.NetworkService; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetwork.IsolationMethod; -import com.cloud.network.bigswitch.BigSwitchBcfUtils; -import com.cloud.network.dao.BigSwitchBcfDao; -import com.cloud.network.dao.FirewallRulesCidrsDao; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.vpc.NetworkACLItemCidrsDao; -import com.cloud.network.vpc.NetworkACLItemDao; -import com.cloud.network.vpc.Vpc; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.offering.NetworkOffering; -import com.cloud.user.Account; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.DomainRouterDao; -import com.cloud.vm.dao.VMInstanceDao; - -/** - * BigSwitchBcfGuestNetworkGuru is responsible for creating and removing virtual networks. - * Current implementation leverages GuestNetworkGuru to create VLAN based virtual networks - * and map it to a Big Switch Big Cloud Fabric (BCF) Segment. It is called by the NetworkOrchestrator. - * - * When a VM is created and needs to be plugged into a BCF segment network, BigSwitchBcfElement is - * called by NetworkOrchestrator to create a "port" and an "attachment" for each nic, and - * register them with the controller to be plugged into the corresponding network. It also - * removes them when the VM is destroyed. - */ -public class BigSwitchBcfGuestNetworkGuru extends GuestNetworkGuru implements NetworkMigrationResponder { - - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - BigSwitchBcfDao _bigswitchBcfDao; - @Inject - HostDao _hostDao; - @Inject - AgentManager _agentMgr; - @Inject - DomainRouterDao _routerDao; - @Inject - VMInstanceDao _vmDao; - @Inject - AccountDao _accountDao; - @Inject - VpcDao _vpcDao; - @Inject - IPAddressDao _ipAddressDao; - @Inject - HostPodDao _podDao; - @Inject - NetworkService _netService; - @Inject - VlanDao _vlanDao; - @Inject - FirewallRulesDao _fwRulesDao; - @Inject - FirewallRulesCidrsDao _fwCidrsDao; - @Inject - NetworkACLItemDao _aclItemDao; - @Inject - NetworkACLItemCidrsDao _aclItemCidrsDao; - - private BigSwitchBcfUtils _bcfUtils = null; - - public BigSwitchBcfGuestNetworkGuru() { - super(); - _isolationMethods = new IsolationMethod[] {new IsolationMethod("BCF_SEGMENT")}; - } - - @Override - protected boolean canHandle(NetworkOffering offering, NetworkType networkType, PhysicalNetwork physicalNetwork) { - if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated && - isMyIsolationMethod(physicalNetwork)) { - return true; - } else { - logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced); - return false; - } - } - - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, String name, Long vpcId, Account owner) { - // Check if the isolation type of the physical network is BCF_SEGMENT, then delegate GuestNetworkGuru to design - PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); - if (physnet == null || physnet.getIsolationMethods() == null || !physnet.getIsolationMethods().contains("BCF_SEGMENT")) { - logger.debug("Refusing to design this network, the physical isolation type is not BCF_SEGMENT"); - return null; - } - - List devices = _bigswitchBcfDao.listByPhysicalNetwork(physnet.getId()); - if (devices.isEmpty()) { - logger.error(String.format("No BigSwitch Controller on physical network %s", physnet)); - return null; - } - for (BigSwitchBcfDeviceVO d: devices){ - logger.debug(String.format("BigSwitch Controller %s found on physical network %s", d, physnet)); - } - - logger.debug("Physical isolation type is BCF_SEGMENT, asking GuestNetworkGuru to design this network"); - NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, name, vpcId, owner); - if (networkObject == null) { - return null; - } - // Override the broadcast domain type - networkObject.setBroadcastDomainType(BroadcastDomainType.Vlan); - - return networkObject; - } - - @Override - public Network implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException { - assert (network.getState() == State.Implementing) : "Why are we implementing " + network; - - bcfUtilsInit(); - - long dcId = dest.getDataCenter().getId(); - - long physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType()); - - NetworkVO implemented = - new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), State.Allocated, - network.getDataCenterId(), physicalNetworkId, false); - - if (network.getGateway() != null) { - implemented.setGateway(network.getGateway()); - } - - if (network.getCidr() != null) { - implemented.setCidr(network.getCidr()); - } - - String vnetId = ""; - if (network.getBroadcastUri() == null) { - vnetId = _dcDao.allocateVnet(dcId, physicalNetworkId, network.getAccountId(), context.getReservationId(), UseSystemGuestVlans.valueIn(network.getAccountId())); - if (vnetId == null) { - throw new InsufficientVirtualNetworkCapacityException("Unable to allocate vnet as a " + - "part of network " + network + " implement ", DataCenter.class, dcId); - } - implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vnetId)); - ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), network.getAccountId(), - EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone VLAN: " + vnetId + " Network ID: " + network.getUuid(), network.getId(), ApiCommandResourceType.Network.toString(), 0); - } else { - implemented.setBroadcastUri(network.getBroadcastUri()); - } - - // Name is either the given name or the uuid - String name = network.getName(); - if (name == null || name.isEmpty()) { - name = ((NetworkVO)network).getUuid(); - } - if (name.length() > 64) { - name = name.substring(0, 63); // max length 64 - } - - // update fields in network object - NetworkVO networkObject = (NetworkVO) network; - - // determine whether this is VPC network or stand-alone network - Vpc vpc = null; - if(network.getVpcId()!=null){ - vpc = _vpcDao.acquireInLockTable(network.getVpcId()); - } - - // use uuid of networkVO as network id in BSN - String networkId = networkObject.getUuid(); - - String tenantId; - String tenantName; - if (vpc != null) { - tenantId = vpc.getUuid(); - tenantName = vpc.getName(); - _vpcDao.releaseFromLockTable(vpc.getId()); - } else { - // use network in CS as tenant in BSN - // for non-VPC networks, use network name and id as tenant name and id - tenantId = networkId; - tenantName = name; - } - - // store tenantId in networkObject for NetworkOrchestrator implementNetwork use - networkObject.setNetworkDomain(tenantId); - // store tenant Id in implemented object for future actions (e.g., shutdown) - implemented.setNetworkDomain(tenantId); - String vlanStr = BroadcastDomainType.getValue(implemented.getBroadcastUri()); - - // get public net info - needed to set up source nat gateway - NetworkVO pubNet = _bcfUtils.getPublicNetwork(physicalNetworkId); - - // locate subnet info - SearchCriteria sc = _vlanDao.createSearchCriteria(); - sc.setParameters("network_id", pubNet.getId()); - VlanVO pubVlanVO = _vlanDao.findOneBy(sc); - String pubVlanStr = pubVlanVO.getVlanTag(); - - Integer vlan; - if(StringUtils.isNumeric(vlanStr)){ - vlan = Integer.valueOf(vlanStr); - } else { - vlan = 0; - } - CreateBcfSegmentCommand cmd1 = new CreateBcfSegmentCommand(tenantId, tenantName, networkId, name, vlan); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd1, networkObject); - - if(_bcfUtils.isNatEnabled()){ - Integer pvlan; - if(StringUtils.isNumeric(pubVlanStr)){ - pvlan = Integer.valueOf(pubVlanStr); - } else { - pvlan = 0; - } - CreateBcfSegmentCommand cmd2 = new CreateBcfSegmentCommand("external", "external", "external", "external", pvlan); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd2, networkObject); - - CreateBcfRouterCommand cmd3 = new CreateBcfRouterCommand(tenantId); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd3, network); - - CreateBcfRouterInterfaceCommand cmd5 = new CreateBcfRouterInterfaceCommand(tenantId, network.getUuid(), network.getCidr(), - network.getGateway(), network.getName()); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd5, network); - } - return implemented; - } - - - - @Override - public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { - // Have GuestNetworkGuru reserve for us - super.reserve(nic, network, vm, dest, context); - } - - @Override - public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { - return super.release(nic, vm, reservationId); - } - - @Override - public void shutdown(NetworkProfile profile, NetworkOffering offering) { - NetworkVO networkObject = _networkDao.findById(profile.getId()); - if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Vlan || networkObject.getBroadcastUri() == null) { - logger.warn(String.format("BroadcastUri is empty or incorrect for guest network %s", networkObject)); - return; - } - - bcfUtilsInit(); - - // tenantId stored in network domain field at creation - String tenantId = networkObject.getNetworkDomain(); - - String networkId = networkObject.getUuid(); - - DeleteBcfSegmentCommand cmd = new DeleteBcfSegmentCommand(tenantId, networkId); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, networkObject); - - super.shutdown(profile, offering); - } - - @Override - public boolean trash(Network network, NetworkOffering offering) { - return super.trash(network, offering); - } - - @Override - public boolean prepareMigration(NicProfile nic, Network network, - VirtualMachineProfile vm, DeployDestination dest, - ReservationContext context) { - bcfUtilsInit(); - - // get arguments for CreateBcfAttachmentCommand - // determine whether this is VPC network or stand-alone network - Vpc vpc = null; - if(network.getVpcId()!=null){ - vpc = _vpcDao.acquireInLockTable(network.getVpcId()); - } - - String networkId = network.getUuid(); - - String tenantId; - String tenantName; - if (vpc != null) { - tenantId = vpc.getUuid(); - tenantName = vpc.getName(); - boolean released = _vpcDao.releaseFromLockTable(vpc.getId()); - logger.debug(String.format("BCF guru release lock vpc: %s released? %s", vpc, released)); - } else { - // use network id in CS as tenant in BSN - // use network uuid as tenant id for non-VPC networks - tenantId = networkId; - tenantName = network.getName(); - } - - String hostname = dest.getHost().getName(); - long zoneId = network.getDataCenterId(); - String vmwareVswitchLabel = _networkModel.getDefaultGuestTrafficLabel(zoneId, HypervisorType.VMware); - String[] labelArray = null; - String vswitchName = null; - if(vmwareVswitchLabel!=null){ - labelArray=vmwareVswitchLabel.split(","); - vswitchName = labelArray[0]; - } - - // hypervisor type: - // kvm: ivs port name - // vmware: specific portgroup naming convention - String pgName = ""; - if (dest.getHost().getHypervisorType() == HypervisorType.KVM){ - pgName = hostname; - } else if (dest.getHost().getHypervisorType() == HypervisorType.VMware){ - pgName = hostname + "-" + vswitchName; - } - - String nicId = nic.getUuid(); - Integer vlan = Integer.valueOf(BroadcastDomainType.getValue(nic.getIsolationUri())); - String ipv4 = nic.getIPv4Address(); - String mac = nic.getMacAddress(); - - CreateBcfAttachmentCommand cmd = new CreateBcfAttachmentCommand(tenantId, - tenantName, networkId, pgName, nicId, vlan, ipv4, mac); - - _bcfUtils.sendBcfCommandWithNetworkSyncCheck(cmd, network); - - return true; - } - - @Override - public void rollbackMigration(NicProfile nic, Network network, - VirtualMachineProfile vm, ReservationContext src, - ReservationContext dst) { - logger.debug("BCF guru rollback migration"); - } - - @Override - public void commitMigration(NicProfile nic, Network network, - VirtualMachineProfile vm, ReservationContext src, - ReservationContext dst) { - logger.debug("BCF guru commit migration"); - } - - private void bcfUtilsInit(){ - if (_bcfUtils == null) { - _bcfUtils = new BigSwitchBcfUtils(_networkDao, _nicDao, - _vmDao, _hostDao, _vpcDao, _bigswitchBcfDao, - _agentMgr, _vlanDao, _ipAddressDao, _fwRulesDao, - _fwCidrsDao, _aclItemDao, _aclItemCidrsDao, _networkModel); - } - } -} diff --git a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/resource/BigSwitchBcfResource.java b/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/resource/BigSwitchBcfResource.java deleted file mode 100644 index 63e8206ec824..000000000000 --- a/plugins/network-elements/bigswitch/src/main/java/com/cloud/network/resource/BigSwitchBcfResource.java +++ /dev/null @@ -1,587 +0,0 @@ -// -// 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.network.resource; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.UpdateBcfRouterCommand; -import com.cloud.agent.api.BcfAnswer; -import com.cloud.agent.api.CacheBcfTopologyCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreateBcfRouterCommand; -import com.cloud.agent.api.CreateBcfRouterInterfaceCommand; -import com.cloud.agent.api.CreateBcfSegmentCommand; -import com.cloud.agent.api.CreateBcfAttachmentCommand; -import com.cloud.agent.api.CreateBcfStaticNatCommand; -import com.cloud.agent.api.DeleteBcfSegmentCommand; -import com.cloud.agent.api.DeleteBcfAttachmentCommand; -import com.cloud.agent.api.DeleteBcfStaticNatCommand; -import com.cloud.agent.api.GetControllerDataAnswer; -import com.cloud.agent.api.GetControllerDataCommand; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupBigSwitchBcfCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.SyncBcfTopologyCommand; -import com.cloud.agent.api.UpdateBcfAttachmentCommand; -import com.cloud.host.Host; -import com.cloud.host.Host.Type; -import com.cloud.network.bigswitch.AclData; -import com.cloud.network.bigswitch.BigSwitchBcfApi; -import com.cloud.network.bigswitch.BigSwitchBcfApiException; -import com.cloud.network.bigswitch.Capabilities; -import com.cloud.network.bigswitch.ControlClusterStatus; -import com.cloud.network.bigswitch.ControllerData; -import com.cloud.network.bigswitch.FloatingIpData; -import com.cloud.network.bigswitch.NetworkData; -import com.cloud.network.bigswitch.AttachmentData; -import com.cloud.network.bigswitch.RouterData; -import com.cloud.network.bigswitch.RouterInterfaceData; -import com.cloud.network.bigswitch.TopologyData; -import com.cloud.resource.ServerResource; -import com.cloud.utils.component.ManagerBase; - -public class BigSwitchBcfResource extends ManagerBase implements ServerResource { - - private String _name; - private String _guid; - private String _zoneId; - private int _numRetries; - - private BigSwitchBcfApi _bigswitchBcfApi; - private TopologyData _latestTopology = null; - private boolean initTopologySyncDone = false; - - protected BigSwitchBcfApi createBigSwitchBcfApi() { - return new BigSwitchBcfApi(); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - - _name = (String)params.get("name"); - if (_name == null) { - throw new ConfigurationException("Unable to find name"); - } - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - _zoneId = (String)params.get("zoneId"); - if (_zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - _numRetries = 2; - - String hostname = (String)params.get("hostname"); - if (hostname == null) { - throw new ConfigurationException("Missing host name from params: " + params); - } - - String username = (String) params.get("username"); - if (username == null) { - throw new ConfigurationException("Missing user name from params: " + params); - } - - String password = (String) params.get("password"); - if (password == null) { - throw new ConfigurationException("Missing password from params: " + params); - } - - Boolean nat = Boolean.parseBoolean((String) params.get("nat")); - if (nat == null) { - throw new ConfigurationException("Missing password from params: " + params); - } - - _bigswitchBcfApi = createBigSwitchBcfApi(); - _bigswitchBcfApi.setControllerAddress(hostname); - _bigswitchBcfApi.setControllerUsername(username); - _bigswitchBcfApi.setControllerPassword(password); - _bigswitchBcfApi.setControllerNat(nat); - _bigswitchBcfApi.setZoneId(_zoneId); - - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public Type getType() { - return Host.Type.L2Networking; - } - - @Override - public StartupCommand[] initialize() { - StartupBigSwitchBcfCommand sc = new StartupBigSwitchBcfCommand(); - sc.setGuid(_guid); - sc.setName(_name); - sc.setDataCenter(_zoneId); - sc.setPod(""); - sc.setPrivateIpAddress(""); - sc.setStorageIpAddress(""); - sc.setVersion(""); - return new StartupCommand[] {sc}; - } - - @Override - public PingCommand getCurrentStatus(long id) { - if(!initTopologySyncDone && _latestTopology != null){ - initTopologySyncDone = true; - if(_bigswitchBcfApi.isNatEnabled()){ - try{ - executeRequest(new SyncBcfTopologyCommand(true, true), _numRetries); - } catch(Exception e){ - logger.error("BigSwitch BCF sync error", e); - } - } else { - try{ - executeRequest(new SyncBcfTopologyCommand(true, false), _numRetries); - } catch (Exception e){ - logger.error("BigSwitch BCF sync error", e); - } - } - } - try { - ControlClusterStatus ccs = _bigswitchBcfApi.getControlClusterStatus(); - if (!ccs.getStatus()) { - logger.error("ControlCluster state is not ready: " + ccs.getStatus()); - return null; - } - if (ccs.isTopologySyncRequested()) { - if(_latestTopology != null) { - if(_bigswitchBcfApi.isNatEnabled()){ - executeRequest(new SyncBcfTopologyCommand(true, true), _numRetries); - } else { - executeRequest(new SyncBcfTopologyCommand(true, false), _numRetries); - } - } else { - logger.debug("topology sync needed but no topology history"); - } - } - } catch (BigSwitchBcfApiException e) { - logger.error("getControlClusterStatus failed", e); - return null; - } - try { - Capabilities cap = _bigswitchBcfApi.getCapabilities(); - - // TODO: update controller status display, enable/disable service accordingly - if (cap.isTopologySyncRequested()) { - if(_latestTopology != null) { - if(_bigswitchBcfApi.isNatEnabled()){ - executeRequest(new SyncBcfTopologyCommand(true, true), _numRetries); - } else { - executeRequest(new SyncBcfTopologyCommand(true, false), _numRetries); - } - } - } - - } catch (BigSwitchBcfApiException e) { - logger.error("getCapabilities failed", e); - } - return new PingCommand(Host.Type.L2Networking, id); - } - - @Override - public Answer executeRequest(Command cmd) { - return executeRequest(cmd, _numRetries); - } - - public Answer executeRequest(Command cmd, int numRetries) { - if (cmd instanceof ReadyCommand) { - return executeRequest((ReadyCommand)cmd); - } else if (cmd instanceof MaintainCommand) { - return executeRequest((MaintainCommand)cmd); - } else if (cmd instanceof CreateBcfSegmentCommand) { - _latestTopology = ((CreateBcfSegmentCommand) cmd).getTopology(); - return executeRequest((CreateBcfSegmentCommand)cmd, numRetries); - } else if (cmd instanceof DeleteBcfSegmentCommand) { - _latestTopology = ((DeleteBcfSegmentCommand) cmd).getTopology(); - return executeRequest((DeleteBcfSegmentCommand)cmd, numRetries); - } else if (cmd instanceof CreateBcfAttachmentCommand) { - _latestTopology = ((CreateBcfAttachmentCommand) cmd).getTopology(); - return executeRequest((CreateBcfAttachmentCommand)cmd, numRetries); - } else if (cmd instanceof DeleteBcfAttachmentCommand) { - _latestTopology = ((DeleteBcfAttachmentCommand) cmd).getTopology(); - return executeRequest((DeleteBcfAttachmentCommand)cmd, numRetries); - } else if (cmd instanceof UpdateBcfAttachmentCommand) { - _latestTopology = ((UpdateBcfAttachmentCommand) cmd).getTopology(); - return executeRequest((UpdateBcfAttachmentCommand)cmd, numRetries); - } else if (cmd instanceof CreateBcfRouterCommand) { - _latestTopology = ((CreateBcfRouterCommand) cmd).getTopology(); - return executeRequest((CreateBcfRouterCommand)cmd, numRetries); - } else if (cmd instanceof CreateBcfRouterInterfaceCommand) { - _latestTopology = ((CreateBcfRouterInterfaceCommand) cmd).getTopology(); - return executeRequest((CreateBcfRouterInterfaceCommand)cmd, numRetries); - } else if (cmd instanceof CreateBcfStaticNatCommand) { - _latestTopology = ((CreateBcfStaticNatCommand) cmd).getTopology(); - return executeRequest((CreateBcfStaticNatCommand)cmd, numRetries); - } else if (cmd instanceof DeleteBcfStaticNatCommand) { - _latestTopology = ((DeleteBcfStaticNatCommand) cmd).getTopology(); - return executeRequest((DeleteBcfStaticNatCommand)cmd, numRetries); - } else if (cmd instanceof UpdateBcfRouterCommand) { - _latestTopology = ((UpdateBcfRouterCommand) cmd).getTopology(); - return executeRequest((UpdateBcfRouterCommand)cmd, numRetries); - } else if (cmd instanceof SyncBcfTopologyCommand) { - return executeRequest((SyncBcfTopologyCommand)cmd, numRetries); - } else if (cmd instanceof CacheBcfTopologyCommand) { - return executeRequest((CacheBcfTopologyCommand)cmd, numRetries); - } else if (cmd instanceof GetControllerDataCommand) { - return executeRequest((GetControllerDataCommand)cmd, numRetries); - } - logger.debug("Received unsupported command " + cmd.toString()); - return Answer.createUnsupportedCommandAnswer(cmd); - } - - @Override - public void disconnected() { - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - } - - public void setTopology(TopologyData topology){ - _latestTopology = topology; - } - - public TopologyData getTopology(){ - return _latestTopology; - } - - private Answer executeRequest(CreateBcfSegmentCommand cmd, int numRetries) { - NetworkData network = new NetworkData(); - network.getNetwork().setTenantId(cmd.getTenantId()); - network.getNetwork().setTenantName(cmd.getTenantName()); - network.getNetwork().setId(cmd.getNetworkId()); - network.getNetwork().setName(truncate("segment-cloudstack-" + cmd.getNetworkName(), 64)); - network.getNetwork().setVlan(cmd.getVlan()); - - try { - String hash =_bigswitchBcfApi.createNetwork(network); - return new BcfAnswer(cmd, true, "Segment " + network.getNetwork().getId() + " created", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "Segment " + network.getNetwork().getId() + " created; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - - } - - private Answer executeRequest(DeleteBcfSegmentCommand cmd, int numRetries) { - try { - String hash = _bigswitchBcfApi.deleteNetwork(cmd.getTenantUuid(), cmd.getNetworkUuid()); - return new BcfAnswer(cmd, true, "Segment " + cmd.getNetworkUuid() + " deleted", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "Segment " + cmd.getNetworkUuid() + " deleted; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(CreateBcfAttachmentCommand cmd, int numRetries) { - AttachmentData attachment = new AttachmentData(); - attachment.getAttachment().setId(cmd.getNicId()); - attachment.getAttachment().setHostId(cmd.getPortId()); - attachment.getAttachment().setTenantName(cmd.getTenantName()); - attachment.getAttachment().setVlan(cmd.getVlan()); - attachment.getAttachment().addIpv4(cmd.getIpv4()); - attachment.getAttachment().setMac(cmd.getMac()); - - try { - String hash = _bigswitchBcfApi.createAttachment(cmd.getTenantId(), cmd.getNetworkId(), attachment); - return new BcfAnswer(cmd, true, "network attachment " + cmd.getPortId() + " created", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "network attachment " + cmd.getPortId() + " created; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(DeleteBcfAttachmentCommand cmd, int numRetries) { - String nicName = cmd.getAttachmentId(); - try { - String hash = _bigswitchBcfApi.deleteAttachment(cmd.getTenantId(), cmd.getNetworkId(), nicName); - return new BcfAnswer(cmd, true, "network attachment " + nicName + " deleted", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "network attachment " + nicName + " deleted; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(UpdateBcfAttachmentCommand cmd, int numRetries) { - AttachmentData attachment = new AttachmentData(); - attachment.getAttachment().setId(cmd.getAttachmentId()); - attachment.getAttachment().setTenantName(cmd.getTenantId()); - - try { - String hash = _bigswitchBcfApi.modifyAttachment(cmd.getTenantId(), cmd.getNetworkId(), attachment); - return new BcfAnswer(cmd, true, "Network attachment " + cmd.getAttachmentId() + " updated", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "Network attachment " + cmd.getAttachmentId() + " updated; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(CreateBcfStaticNatCommand cmd, int numRetries) { - FloatingIpData fip = new FloatingIpData(); - fip.setTenantId(cmd.getTenantId()); - fip.setNetworkId(cmd.getNetworkId()); - fip.setFixedIp(cmd.getPrivateIp()); - fip.setFloatingIpAndId(cmd.getPublicIp()); - fip.setMac(cmd.getMac()); - - try { - String hash = _bigswitchBcfApi.createFloatingIp(cmd.getTenantId(), fip); - return new BcfAnswer(cmd, true, "floating ip " + cmd.getPublicIp() + ":" + - cmd.getPrivateIp() + " created", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "floating ip " + cmd.getPublicIp() + ":" + - cmd.getPrivateIp() + " created; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(DeleteBcfStaticNatCommand cmd, int numRetries) { - try { - String hash = _bigswitchBcfApi.deleteFloatingIp(cmd.getTenantId(), cmd.getFloatingIpId()); - return new BcfAnswer(cmd, true, "floating ip " + cmd.getPublicIp() + " deleted", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "floating ip " + cmd.getPublicIp() + " deleted; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(CreateBcfRouterCommand cmd, int numRetries) { - RouterData router = new RouterData(cmd.getTenantId()); - try { - String hash; - hash = _bigswitchBcfApi.createRouter(cmd.getTenantId(), router); - - return new BcfAnswer(cmd, true, "router " + cmd.getTenantId() + - " created.", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, " created; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(CreateBcfRouterInterfaceCommand cmd, int numRetries) { - RouterInterfaceData routerInterface = new RouterInterfaceData(cmd.getTenantId(), - cmd.getGateway(), cmd.getCidr(), cmd.getNetworkId(), cmd.getNetworkName()); - try { - String hash; - hash = _bigswitchBcfApi.createRouterInterface(cmd.getTenantId(), - cmd.getTenantId(), routerInterface); - - return new BcfAnswer(cmd, true, "router " + cmd.getTenantId() + - " created.", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, " created; topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } - } - - private Answer executeRequest(UpdateBcfRouterCommand cmd, int numRetries){ - RouterData routerData = new RouterData(cmd.getTenantId()); - - List acls = new ArrayList(); - acls.addAll(cmd.getAcls()); - routerData.getRouter().getAcls().addAll(acls); - - routerData.getRouter().addExternalGateway(cmd.getPublicIp()); - - try { - String hash = _bigswitchBcfApi.modifyRouter(cmd.getTenantId(), routerData); - return new BcfAnswer(cmd, true, "tenant " + cmd.getTenantId() + " router updated", hash); - } catch (BigSwitchBcfApiException e) { - if (e.is_topologySyncRequested()) { - cmd.setTopologySyncRequested(true); - return new BcfAnswer(cmd, true, "tenant " + cmd.getTenantId() + " router updated but topology sync required."); - } else { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } - } catch (IllegalArgumentException e1){ - return new BcfAnswer(cmd, false, "Illegal argument in BCF router update"); - } - } - - private Answer executeRequest(SyncBcfTopologyCommand cmd, int numRetries) { - try { - TopologyData topo = _latestTopology; - if (!cmd.isNetworkIncluded()) { - topo.clearNetworks(); - } - if(!cmd.isRouterIncluded()) { - topo.clearRouters(); - } - String hash = _bigswitchBcfApi.syncTopology(topo); - if(!initTopologySyncDone){ - initTopologySyncDone=true; - } - return new BcfAnswer(cmd, true, "BCF topology synced", hash); - } catch (BigSwitchBcfApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new BcfAnswer(cmd, e); - } - } catch (IllegalArgumentException e1){ - return new BcfAnswer(cmd, false, "Illegal argument in BCF topology sync"); - } - } - - private Answer executeRequest(CacheBcfTopologyCommand cmd, int numRetries) { - _latestTopology = cmd.getTopology(); - return new Answer(cmd, true, "BCF topology cached"); - } - - private Answer executeRequest(GetControllerDataCommand cmd, int numRetries) { - ControllerData controller = _bigswitchBcfApi.getControllerData(); - return new GetControllerDataAnswer(cmd, - controller.getIpAddress(), - controller.isPrimary()); - } - - private Answer executeRequest(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - private Answer executeRequest(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - private Answer retry(Command cmd, int numRetries) { - logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries); - return executeRequest(cmd, numRetries); - } - - private String truncate(String string, int length) { - if (string.length() <= length) { - return string; - } else { - return string.substring(0, length); - } - } -} diff --git a/plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/module.properties b/plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/module.properties deleted file mode 100644 index 22bc7d8a2dac..000000000000 --- a/plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/module.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# 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. -# - -name=bigswitch -parent=network diff --git a/plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/spring-bigswitch-context.xml b/plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/spring-bigswitch-context.xml deleted file mode 100644 index 81452dc836d3..000000000000 --- a/plugins/network-elements/bigswitch/src/main/resources/META-INF/cloudstack/bigswitch/spring-bigswitch-context.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - diff --git a/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchApiTest.java b/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchApiTest.java deleted file mode 100644 index 0a36058b6c19..000000000000 --- a/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchApiTest.java +++ /dev/null @@ -1,433 +0,0 @@ -// -// 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.network.bigswitch; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.Collections; -import java.util.UUID; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.params.HttpClientParams; -import org.apache.http.HttpStatus; -import org.junit.Before; -import org.junit.Test; - -import com.google.gson.reflect.TypeToken; - -public class BigSwitchApiTest { - BigSwitchBcfApi _api; - HttpClient _client = mock(HttpClient.class); - HttpMethod _method; - - @Before - public void setUp() { - HttpClientParams hmp = mock(HttpClientParams.class); - when(_client.getParams()).thenReturn(hmp); - _api = new BigSwitchBcfApi(){ - @Override - protected HttpClient createHttpClient() { - return _client; - } - - @Override - protected HttpMethod createMethod(String type, String uri, int port) { - return _method; - } - }; - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectWithoutHostname() throws BigSwitchBcfApiException { - _api.setControllerAddress(null); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectWithEmptyHostname() throws BigSwitchBcfApiException { - _api.setControllerAddress(""); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectWithoutUsername() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername(null); - _api.setControllerPassword("mypassword"); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectWithEmptyUsername() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername(""); - _api.setControllerPassword("mypassword"); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectWithoutPassword() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword(null); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectWithEmptyPassword() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword(""); - _api.executeUpdateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectWithoutHostname() throws BigSwitchBcfApiException { - _api.setControllerAddress(null); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - _api.executeCreateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectWithEmptyHostname() throws BigSwitchBcfApiException { - _api.setControllerAddress(""); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - _api.executeCreateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectWithoutUsername() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername(null); - _api.setControllerPassword("mypassword"); - _api.executeCreateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectWithEmptyUsername() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername(""); - _api.setControllerPassword("mypassword"); - _api.executeCreateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectWithoutPassword() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword(null); - _api.executeCreateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectWithEmptyPassword() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword(""); - _api.executeCreateObject(new String(), "/", Collections. emptyMap()); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectWithoutHostname() throws BigSwitchBcfApiException { - _api.setControllerAddress(null); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - _api.executeDeleteObject("/"); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectWithEmptyHostname() throws BigSwitchBcfApiException { - _api.setControllerAddress(""); - _api.setControllerUsername("myname"); - _api.setControllerPassword("mypassword"); - _api.executeDeleteObject("/"); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectWithoutUsername() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername(null); - _api.setControllerPassword("mypassword"); - _api.executeDeleteObject("/"); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectWithEmptyUsername() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername(""); - _api.setControllerPassword("mypassword"); - _api.executeDeleteObject("/"); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectWithoutPassword() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword(null); - _api.executeDeleteObject("/"); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectWithEmptyPassword() throws BigSwitchBcfApiException { - _api.setControllerAddress("10.10.0.10"); - _api.setControllerUsername("myname"); - _api.setControllerPassword(""); - _api.executeDeleteObject("/"); - } - - @Test - public void executeMethodTestOK() throws BigSwitchBcfApiException, HttpException, IOException { - GetMethod gm = mock(GetMethod.class); - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); - _api.executeMethod(gm); - verify(gm, times(1)).getStatusCode(); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void executeMethodTestUnauthorized() throws BigSwitchBcfApiException, IOException { - GetMethod gm = mock(GetMethod.class); - when(_client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); - when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED); - _api.executeMethod(gm); - } - - @Test - public void testExecuteCreateObjectOK() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PostMethod.class); - when(_method.getResponseHeader("X-BSN-BVS-HASH-MATCH")).thenReturn(new Header("X-BSN-BVS-HASH-MATCH", UUID.randomUUID().toString())); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - String hash = _api.executeCreateObject(network, "/", Collections. emptyMap()); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method);assertNotEquals(hash, ""); - assertNotEquals(hash, BigSwitchBcfApi.HASH_CONFLICT); - assertNotEquals(hash, BigSwitchBcfApi.HASH_IGNORE); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectConflict() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CONFLICT); - _api.executeCreateObject(network, "/", Collections. emptyMap()); - } - - @Test - public void testExecuteCreateObjectSecondary() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_SEE_OTHER); - String hash = _api.executeCreateObject(network, "/", Collections. emptyMap()); - assertEquals(hash, BigSwitchBcfApi.HASH_IGNORE); - assertEquals(_api.getControllerData().isPrimary(), false); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectFailure() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("content-type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - _api.executeCreateObject(network, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteCreateObjectException() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - when(_client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); - _method = mock(PostMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("content-type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - try { - _api.executeCreateObject(network, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - - @Test - public void testExecuteUpdateObjectOK() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PutMethod.class); - when(_method.getResponseHeader("X-BSN-BVS-HASH-MATCH")).thenReturn(new Header("X-BSN-BVS-HASH-MATCH", UUID.randomUUID().toString())); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - String hash = _api.executeUpdateObject(network, "/", Collections. emptyMap()); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - assertNotEquals(hash, ""); - assertNotEquals(hash, BigSwitchBcfApi.HASH_CONFLICT); - assertNotEquals(hash, BigSwitchBcfApi.HASH_IGNORE); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectConflict() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CONFLICT); - _api.executeUpdateObject(network, "/", Collections. emptyMap()); - } - - @Test - public void testExecuteUpdateObjectSecondary() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_SEE_OTHER); - String hash = _api.executeUpdateObject(network, "/", Collections. emptyMap()); - assertEquals(hash, BigSwitchBcfApi.HASH_IGNORE); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectFailure() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("content-type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - _api.executeUpdateObject(network, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteUpdateObjectException() throws BigSwitchBcfApiException, IOException { - NetworkData network = new NetworkData(); - _method = mock(PutMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(_client.executeMethod((HttpMethod)any())).thenThrow(new IOException()); - try { - _api.executeUpdateObject(network, "/", Collections. emptyMap()); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - - @Test - public void testExecuteDeleteObject() throws BigSwitchBcfApiException, IOException { - _method = mock(DeleteMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - _api.executeDeleteObject("/"); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectFailure() throws BigSwitchBcfApiException, IOException { - _method = mock(DeleteMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); - Header header = mock(Header.class); - when(header.getValue()).thenReturn("text/html"); - when(_method.getResponseHeader("content-type")).thenReturn(header); - when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); - when(_method.isRequestSent()).thenReturn(true); - try { - _api.executeDeleteObject("/"); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - - @Test(expected = BigSwitchBcfApiException.class) - public void testExecuteDeleteObjectException() throws BigSwitchBcfApiException, IOException { - _method = mock(DeleteMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(_client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); - try { - _api.executeDeleteObject("/"); - } finally { - verify(_method, times(1)).releaseConnection(); - } - } - - @Test - public void testExecuteRetrieveControllerPrimaryStatus() throws BigSwitchBcfApiException, IOException { - _method = mock(GetMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(((HttpMethodBase)_method).getResponseBodyAsString(2048)).thenReturn("{'healthy': true, 'topologySyncRequested': false}"); - _api.executeRetrieveObject(new TypeToken() { - }.getType(), "/", null); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - assertEquals(_api.getControllerData().isPrimary(), true); - } - - @Test - public void testExecuteRetrieveControllerPrimaryStatusWithTopoConflict() throws BigSwitchBcfApiException, IOException { - _method = mock(GetMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_CONFLICT); - when(((HttpMethodBase)_method).getResponseBodyAsString(2048)).thenReturn("{'healthy': true, 'topologySyncRequested': true}"); - _api.executeRetrieveObject(new TypeToken() { - }.getType(), "/", null); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - assertEquals(_api.getControllerData().isPrimary(), true); - } - - @Test - public void testExecuteRetrieveControllerSecondaryStatus() throws BigSwitchBcfApiException, IOException { - _method = mock(GetMethod.class); - when(_method.getStatusCode()).thenReturn(HttpStatus.SC_SEE_OTHER); - when(((HttpMethodBase)_method).getResponseBodyAsString(1024)).thenReturn("{'healthy': true, 'topologySyncRequested': false}"); - _api.executeRetrieveObject(new TypeToken() { - }.getType(), "/", null); - verify(_method, times(1)).releaseConnection(); - verify(_client, times(1)).executeMethod(_method); - assertEquals(_api.getControllerData().isPrimary(), false); - } -} diff --git a/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchBcfUtilsTest.java b/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchBcfUtilsTest.java deleted file mode 100644 index a488888e5d0b..000000000000 --- a/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/bigswitch/BigSwitchBcfUtilsTest.java +++ /dev/null @@ -1,100 +0,0 @@ -// -// 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.network.bigswitch; - -import static org.junit.Assert.assertEquals; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import com.cloud.agent.AgentManager; -import com.cloud.dc.dao.VlanDao; -import com.cloud.host.dao.HostDao; -import com.cloud.network.NetworkModel; -import com.cloud.network.dao.BigSwitchBcfDao; -import com.cloud.network.dao.FirewallRulesCidrsDao; -import com.cloud.network.dao.FirewallRulesDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.vpc.NetworkACLItemCidrsDao; -import com.cloud.network.vpc.NetworkACLItemDao; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.VMInstanceDao; - -public class BigSwitchBcfUtilsTest { - - @Mock - NetworkDao networkDao; - @Mock - NicDao nicDao; - @Mock - VMInstanceDao vmDao; - @Mock - HostDao hostDao; - @Mock - VpcDao vpcDao; - @Mock - BigSwitchBcfDao bigswitchBcfDao; - @Mock - AgentManager agentMgr; - @Mock - VlanDao vlanDao; - @Mock - IPAddressDao ipAddressDao; - @Mock - FirewallRulesDao fwRulesDao; - @Mock - FirewallRulesCidrsDao fwCidrsDao; - @Mock - NetworkACLItemDao aclItemDao; - @Mock - NetworkACLItemCidrsDao aclItemCidrsDao; - @Mock - NetworkModel networkModel; - @Mock - BigSwitchBcfUtils bsUtil; - private AutoCloseable closeable; - - @Before - public void setUp() { - closeable = MockitoAnnotations.openMocks(this); - bsUtil = new BigSwitchBcfUtils(networkDao, nicDao, vmDao, hostDao, - vpcDao, bigswitchBcfDao, agentMgr, vlanDao, ipAddressDao, - fwRulesDao, fwCidrsDao, aclItemDao, aclItemCidrsDao, - networkModel); - } - - @After - public void tearDown() throws Exception { - closeable.close(); - } - - @Test - public void getSubnetMaskLengthTest() { - Integer rc = bsUtil.getSubnetMaskLength("255.255.255.254"); - assertEquals("failed", new Integer(31), rc); - rc = bsUtil.getSubnetMaskLength("128.255.255.254"); - assertEquals("failed", new Integer(1), rc); - } -} diff --git a/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/resource/BigSwitchBcfResourceTest.java b/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/resource/BigSwitchBcfResourceTest.java deleted file mode 100644 index 16b244418020..000000000000 --- a/plugins/network-elements/bigswitch/src/test/java/com/cloud/network/resource/BigSwitchBcfResourceTest.java +++ /dev/null @@ -1,431 +0,0 @@ -// -// 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.network.resource; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.naming.ConfigurationException; - -import org.junit.Before; -import org.junit.Test; - -import com.cloud.agent.api.BcfAnswer; -import com.cloud.agent.api.CreateBcfRouterCommand; -import com.cloud.agent.api.CreateBcfSegmentCommand; -import com.cloud.agent.api.CreateBcfAttachmentCommand; -import com.cloud.agent.api.CreateBcfStaticNatCommand; -import com.cloud.agent.api.DeleteBcfSegmentCommand; -import com.cloud.agent.api.DeleteBcfAttachmentCommand; -import com.cloud.agent.api.DeleteBcfStaticNatCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.SyncBcfTopologyCommand; -import com.cloud.agent.api.UpdateBcfAttachmentCommand; -import com.cloud.agent.api.UpdateBcfRouterCommand; -import com.cloud.host.Host; -import com.cloud.network.bigswitch.BigSwitchBcfApi; -import com.cloud.network.bigswitch.BigSwitchBcfApiException; -import com.cloud.network.bigswitch.Capabilities; -import com.cloud.network.bigswitch.ControlClusterStatus; -import com.cloud.network.bigswitch.FloatingIpData; -import com.cloud.network.bigswitch.NetworkData; -import com.cloud.network.bigswitch.AttachmentData; -import com.cloud.network.bigswitch.RouterData; -import com.cloud.network.bigswitch.TopologyData; - -public class BigSwitchBcfResourceTest { - BigSwitchBcfApi _bigswitchBcfApi = mock(BigSwitchBcfApi.class); - BigSwitchBcfResource _resource; - Map _parameters; - - String bcfAddress = "127.0.0.1"; - String bcfUserName = "myname"; - String bcfPassword = "mypassword"; - - @Before - public void setUp() throws ConfigurationException { - _resource = new BigSwitchBcfResource() { - @Override - protected BigSwitchBcfApi createBigSwitchBcfApi() { - return _bigswitchBcfApi; - } - }; - - _parameters = new HashMap(); - _parameters.put("name", "bigswitchbcftestdevice"); - _parameters.put("hostname", bcfAddress); - _parameters.put("guid", "aaaaa-bbbbb-ccccc"); - _parameters.put("zoneId", "blublub"); - _parameters.put("username", bcfUserName); - _parameters.put("password", bcfPassword); - } - - @Test(expected = ConfigurationException.class) - public void resourceConfigureFailure() throws ConfigurationException { - _resource.configure("BigSwitchBcfResource", Collections. emptyMap()); - } - - @Test - public void resourceConfigure() throws ConfigurationException { - _resource.configure("BigSwitchBcfResource", _parameters); - - verify(_bigswitchBcfApi).setControllerAddress(bcfAddress); - verify(_bigswitchBcfApi).setControllerUsername(bcfUserName); - verify(_bigswitchBcfApi).setControllerPassword(bcfPassword); - - assertTrue("bigswitchbcftestdevice".equals(_resource.getName())); - - /* Pretty lame test, but here to assure this plugin fails - * if the type name ever changes from L2Networking - */ - assertTrue(_resource.getType() == Host.Type.L2Networking); - } - - @Test - public void testInitialization() throws ConfigurationException { - _resource.configure("BigSwitchBcfResource", _parameters); - - StartupCommand[] sc = _resource.initialize(); - assertTrue(sc.length == 1); - assertTrue("aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); - assertTrue("bigswitchbcftestdevice".equals(sc[0].getName())); - assertTrue("blublub".equals(sc[0].getDataCenter())); - } - - @Test - public void testPingCommandStatusOk() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getStatus()).thenReturn(true); - when(_bigswitchBcfApi.getControlClusterStatus()).thenReturn(ccs); - - Capabilities cap = mock(Capabilities.class); - when(_bigswitchBcfApi.getCapabilities()).thenReturn(cap); - - PingCommand ping = _resource.getCurrentStatus(42); - assertTrue(ping != null); - assertTrue(ping.getHostId() == 42); - assertTrue(ping.getHostType() == Host.Type.L2Networking); - } - - @Test - public void testPingCommandStatusFail() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getStatus()).thenReturn(false); - when(_bigswitchBcfApi.getControlClusterStatus()).thenReturn(ccs); - - PingCommand ping = _resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testPingCommandStatusApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getStatus()).thenReturn(false); - when(_bigswitchBcfApi.getControlClusterStatus()).thenThrow(new BigSwitchBcfApiException()); - - PingCommand ping = _resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testCreateNetworkRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - NetworkData networkdata = mock(NetworkData.class); - NetworkData.Network network = mock(NetworkData.Network.class); - when(networkdata.getNetwork()).thenReturn(network); - when(network.getId()).thenReturn("cccc"); - when(_bigswitchBcfApi.createNetwork((NetworkData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - CreateBcfSegmentCommand cmd = new CreateBcfSegmentCommand("tenantid", "tenantname", - (String)_parameters.get("guid"), "networkName", 0); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testCreateNetworkApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - NetworkData networkdata = mock(NetworkData.class); - NetworkData.Network network = mock(NetworkData.Network.class); - when(networkdata.getNetwork()).thenReturn(network); - when(network.getId()).thenReturn("cccc"); - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).createNetwork((NetworkData)any()); - - CreateBcfSegmentCommand cmd = new CreateBcfSegmentCommand("tenantid", "tenantname", - (String)_parameters.get("guid"), "networkName", 0); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).createNetwork((NetworkData)any()); - } - - @Test - public void testDeleteNetworkRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - when(_bigswitchBcfApi.deleteNetwork((String)any(), (String)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - DeleteBcfSegmentCommand cmd = new DeleteBcfSegmentCommand("tenantid", "networkid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testDeleteNetworkApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).deleteNetwork((String)any(), (String)any()); - - DeleteBcfSegmentCommand cmd = new DeleteBcfSegmentCommand("tenantid", "networkid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).deleteNetwork((String)any(), (String)any()); - } - - @Test - public void testCreateAttachmentRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - AttachmentData attachmentData = mock(AttachmentData.class); - AttachmentData.Attachment attachment = mock(AttachmentData.Attachment.class); - when(attachmentData.getAttachment()).thenReturn(attachment); - when(attachment.getId()).thenReturn("eeee"); - when(_bigswitchBcfApi.createAttachment((String)any(), (String)any(), (AttachmentData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - CreateBcfAttachmentCommand cmd = new CreateBcfAttachmentCommand("tenantid", "tenantname", - "networkid", "portid", "nicId", 100, "1.2.3.4", "aa:bb:cc:dd:ee:ff"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testCreateAttachmentApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - AttachmentData attachmentData = mock(AttachmentData.class); - AttachmentData.Attachment attachment = mock(AttachmentData.Attachment.class); - when(attachmentData.getAttachment()).thenReturn(attachment); - when(attachment.getId()).thenReturn("eeee"); - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).createAttachment((String)any(), (String)any(), (AttachmentData)any()); - - CreateBcfAttachmentCommand cmd = new CreateBcfAttachmentCommand("tenantid", "tenantname", - "networkid", "portid", "nicId", 100, "1.2.3.4", "aa:bb:cc:dd:ee:ff"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).createAttachment((String)any(), (String)any(), (AttachmentData)any()); - } - - @Test - public void testDeleteAttachmentRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.deleteAttachment((String)any(), (String)any(), (String)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(new DeleteBcfAttachmentCommand("networkId", "portid", "tenantid")); - assertTrue(ans.getResult()); - } - - @Test - public void testDeleteAttachmentException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).deleteAttachment((String)any(), (String)any(), (String)any()); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(new DeleteBcfAttachmentCommand("networkId", "portid", "tenantid")); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).deleteAttachment((String)any(), (String)any(), (String)any()); - } - - @Test - public void testUpdateAttachmentRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.modifyAttachment((String)any(), (String)any(), (AttachmentData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(new UpdateBcfAttachmentCommand("networkId", "portId", "tenantId", "portname")); - assertTrue(ans.getResult()); - } - - @Test - public void testUpdateAttachmentException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).modifyAttachment((String)any(), (String)any(), (AttachmentData)any()); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(new UpdateBcfAttachmentCommand("networkId", "portId", "tenantId", "portname")); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).modifyAttachment((String)any(), (String)any(), (AttachmentData)any()); - } - - @Test - public void testCreateStaticNatRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.createFloatingIp((String)any(), (FloatingIpData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - CreateBcfStaticNatCommand cmd = new CreateBcfStaticNatCommand("tenantid", - "networkid", "192.168.0.10", "10.4.4.100", "90:b1:1c:49:d8:56"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testCreateStaticNatApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).createFloatingIp((String)any(), (FloatingIpData)any()); - - CreateBcfStaticNatCommand cmd = new CreateBcfStaticNatCommand("tenantid", - "networkid", "192.168.0.10", "10.4.4.100", "90:b1:1c:49:d8:56"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).createFloatingIp((String)any(), (FloatingIpData)any()); - } - - @Test - public void testDeleteStaticNatRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.deleteFloatingIp((String)any(), (String)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - DeleteBcfStaticNatCommand cmd = new DeleteBcfStaticNatCommand("tenantid", - "10.4.4.100"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testDeleteStaticNatApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).deleteFloatingIp((String)any(), (String)any()); - - DeleteBcfStaticNatCommand cmd = new DeleteBcfStaticNatCommand("tenantid", - "10.4.4.100"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).deleteFloatingIp((String)any(), (String)any()); - } - - @Test - public void testCreateRouterRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.createRouter((String)any(), (RouterData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - CreateBcfRouterCommand cmd = new CreateBcfRouterCommand("tenantid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testCreateRouterApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).createRouter((String)any(), (RouterData)any()); - - CreateBcfRouterCommand cmd = new CreateBcfRouterCommand("tenantid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).createRouter((String)any(), (RouterData)any()); - } - - @Test - public void testCreateSourceNatRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.modifyRouter((String)any(), (RouterData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - UpdateBcfRouterCommand cmd = new UpdateBcfRouterCommand("tenantid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testCreateSourceNatApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).modifyRouter((String)any(), (RouterData)any()); - - UpdateBcfRouterCommand cmd = new UpdateBcfRouterCommand("tenantid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).modifyRouter((String)any(), (RouterData)any()); - } - - @Test - public void testDeleteSourceNatRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - when(_bigswitchBcfApi.modifyRouter((String)any(), (RouterData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - - UpdateBcfRouterCommand cmd = new UpdateBcfRouterCommand("tenantid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertTrue(ans.getResult()); - } - - @Test - public void testDeleteSourceNatApiException() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - - doThrow(new BigSwitchBcfApiException()).when(_bigswitchBcfApi).modifyRouter((String)any(), (RouterData)any()); - - UpdateBcfRouterCommand cmd = new UpdateBcfRouterCommand("tenantid"); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(cmd); - assertFalse(ans.getResult()); - verify(_bigswitchBcfApi, times(3)).modifyRouter((String)any(), (RouterData)any()); - } - - @Test - public void testSyncTopologyRetryOnce() throws ConfigurationException, BigSwitchBcfApiException { - _resource.configure("BigSwitchBcfResource", _parameters); - _resource.setTopology(new TopologyData()); - - when(_bigswitchBcfApi.syncTopology((TopologyData)any())).thenThrow(new BigSwitchBcfApiException()) - .thenReturn(UUID.randomUUID().toString()); - BcfAnswer ans = (BcfAnswer)_resource.executeRequest(new SyncBcfTopologyCommand(true, false)); - assertTrue(ans.getResult()); - } - -} diff --git a/plugins/network-elements/brocade-vcs/pom.xml b/plugins/network-elements/brocade-vcs/pom.xml deleted file mode 100644 index 1eb716a6f9b0..000000000000 --- a/plugins/network-elements/brocade-vcs/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-vcs - Apache CloudStack Plugin - Network Brocade VCS - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - 0.15.3 - - - interface - - generate - - - ${project.build.directory}/generated-sources/xjc1 - ${project.build.resources[0].directory} - - BrocadeInterfaceSchema.xsd - - com.cloud.network.schema.interfacevlan - - - - portprofile - - generate - - - ${project.build.directory}/generated-sources/xjc2 - ${project.build.resources[0].directory} - - BrocadePortProfileSchema.xsd - - com.cloud.network.schema.portprofile - - - - show-vcs - - generate - - - ${project.build.directory}/generated-sources/xjc3 - ${project.build.resources[0].directory} - - BrocadeShowVcsSchema.xsd - - com.cloud.network.schema.showvcs - - - - - - - diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkAnswer.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkAnswer.java deleted file mode 100644 index f8541b51aa22..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkAnswer.java +++ /dev/null @@ -1,30 +0,0 @@ -// 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.api; - -public class AssociateMacToNetworkAnswer extends Answer { - - public AssociateMacToNetworkAnswer(Command command, boolean success, String details) { - super(command, success, details); - - } - - public AssociateMacToNetworkAnswer(Command command, Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkCommand.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkCommand.java deleted file mode 100644 index 91b714a86464..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/AssociateMacToNetworkCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -// 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.api; - -public class AssociateMacToNetworkCommand extends Command { - - private String _interfaceMac; - private long _networkId; - private String _ownerName; - - public AssociateMacToNetworkCommand(long networkId, String interfaceMac, String ownerName) { - _networkId = networkId; - _interfaceMac = interfaceMac; - _ownerName = ownerName; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getInterfaceMac() { - return _interfaceMac; - } - - public long getNetworkId() { - return _networkId; - } - - public String getOwnerName() { - return _ownerName; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkAnswer.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkAnswer.java deleted file mode 100644 index 7d02c6358eb0..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkAnswer.java +++ /dev/null @@ -1,30 +0,0 @@ -// 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.api; - -public class CreateNetworkAnswer extends Answer { - - public CreateNetworkAnswer(Command command, boolean success, String details) { - super(command, success, details); - - } - - public CreateNetworkAnswer(Command command, Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkCommand.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkCommand.java deleted file mode 100644 index 3516dc39f67a..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/CreateNetworkCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -// 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.api; - -public class CreateNetworkCommand extends Command { - - private int _vlanId; - private long _networkId; - private String _ownerName; - - public CreateNetworkCommand(int vlanId, long networkId, String ownerName) { - _vlanId = vlanId; - _networkId = networkId; - _ownerName = ownerName; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public int getVlanId() { - return _vlanId; - } - - public long getNetworkId() { - return _networkId; - } - - public String getOwnerName() { - return _ownerName; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkAnswer.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkAnswer.java deleted file mode 100644 index c12bd998ec38..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkAnswer.java +++ /dev/null @@ -1,30 +0,0 @@ -// 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.api; - -public class DeleteNetworkAnswer extends Answer { - - public DeleteNetworkAnswer(Command command, boolean success, String details) { - super(command, success, details); - - } - - public DeleteNetworkAnswer(Command command, Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkCommand.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkCommand.java deleted file mode 100644 index 93e3f966a9aa..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DeleteNetworkCommand.java +++ /dev/null @@ -1,43 +0,0 @@ -// 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.api; - -public class DeleteNetworkCommand extends Command { - - private int _vlanId; - private long _networkId; - - public DeleteNetworkCommand(int vlanId, long networkId) { - _vlanId = vlanId; - _networkId = networkId; - - } - - @Override - public boolean executeInSequence() { - return false; - } - - public int getVlanId() { - return _vlanId; - } - - public long getNetworkId() { - return _networkId; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkAnswer.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkAnswer.java deleted file mode 100644 index 0146fe2cf705..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkAnswer.java +++ /dev/null @@ -1,30 +0,0 @@ -// 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.api; - -public class DisassociateMacFromNetworkAnswer extends Answer { - - public DisassociateMacFromNetworkAnswer(Command command, boolean success, String details) { - super(command, success, details); - - } - - public DisassociateMacFromNetworkAnswer(Command command, Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkCommand.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkCommand.java deleted file mode 100644 index 86777ae5c7be..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/DisassociateMacFromNetworkCommand.java +++ /dev/null @@ -1,42 +0,0 @@ -// 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.api; - -public class DisassociateMacFromNetworkCommand extends Command { - - private String _interfaceMac; - private long _networkId; - - public DisassociateMacFromNetworkCommand(long networkId, String interfaceMac) { - _networkId = networkId; - _interfaceMac = interfaceMac; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getInterfaceMac() { - return _interfaceMac; - } - - public long getNetworkId() { - return _networkId; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/StartupBrocadeVcsCommand.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/StartupBrocadeVcsCommand.java deleted file mode 100644 index 43d32221693e..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/agent/api/StartupBrocadeVcsCommand.java +++ /dev/null @@ -1,27 +0,0 @@ -// 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.api; - -import com.cloud.host.Host; - -public class StartupBrocadeVcsCommand extends StartupCommand { - - public StartupBrocadeVcsCommand() { - super(Host.Type.L2Networking); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/AddBrocadeVcsDeviceCmd.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/AddBrocadeVcsDeviceCmd.java deleted file mode 100644 index 59245e07f36d..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/AddBrocadeVcsDeviceCmd.java +++ /dev/null @@ -1,122 +0,0 @@ -// -// 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.api.commands; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.BrocadeVcsDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.network.brocade.Constants; -import com.cloud.network.element.BrocadeVcsElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addBrocadeVcsDevice", responseObject = BrocadeVcsDeviceResponse.class, description = "Adds a Brocade VCS Switch", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddBrocadeVcsDeviceCmd extends BaseAsyncCmd { - @Inject - protected BrocadeVcsElementService brocadeVcsElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, required = true, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname of IP address of the Brocade VCS Switch.") - private String host; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to access the Brocade VCS Switch API") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to access the Brocade VCS Switch API") - private String password; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getHost() { - return host; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { - try { - BrocadeVcsDeviceVO brocadeVcsDeviceVO = brocadeVcsElementService.addBrocadeVcsDevice(this); - if (brocadeVcsDeviceVO != null) { - BrocadeVcsDeviceResponse response = brocadeVcsElementService.createBrocadeVcsDeviceResponse(brocadeVcsDeviceVO); - response.setObjectName("brocadevcsdevice"); - response.setResponseName(getCommandName()); - setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Brocade VCS Switch due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public String getEventType() { - return Constants.EVENT_EXTERNAL_VCS_CONTROLLER_ADD; - } - - @Override - public String getEventDescription() { - return "Adding a Brocade VCS Switch"; - } -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/DeleteBrocadeVcsDeviceCmd.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/DeleteBrocadeVcsDeviceCmd.java deleted file mode 100644 index f62236dc8e3a..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/DeleteBrocadeVcsDeviceCmd.java +++ /dev/null @@ -1,99 +0,0 @@ -// -// 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.api.commands; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.BrocadeVcsDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.brocade.Constants; -import com.cloud.network.element.BrocadeVcsElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteBrocadeVcsDevice", responseObject = SuccessResponse.class, description = " delete a Brocade VCS Switch", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteBrocadeVcsDeviceCmd extends BaseAsyncCmd { - @Inject - protected BrocadeVcsElementService brocadeVcsElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = Constants.BROCADE_VCS_DEVICE_ID, type = CommandType.UUID, entityType = BrocadeVcsDeviceResponse.class, required = true, description = "Brocade Switch ID") - private Long brocadeVcsDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getBrocadeVcsDeviceId() { - return brocadeVcsDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { - try { - boolean result = brocadeVcsElementService.deleteBrocadeVcsDevice(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Brocade VCS Switch."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public String getEventType() { - return Constants.EVENT_EXTERNAL_VCS_CONTROLLER_DELETE; - } - - @Override - public String getEventDescription() { - return "Deleting Brocade VCS Switch"; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDeviceNetworksCmd.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDeviceNetworksCmd.java deleted file mode 100644 index e9933be8a297..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDeviceNetworksCmd.java +++ /dev/null @@ -1,102 +0,0 @@ -// -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ResponseObject.ResponseView; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.NetworkResponse; - -import com.cloud.api.response.BrocadeVcsDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.brocade.Constants; -import com.cloud.network.element.BrocadeVcsElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listBrocadeVcsDeviceNetworks", responseObject = NetworkResponse.class, description = "Lists network that are using a brocade vcs switch", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListBrocadeVcsDeviceNetworksCmd extends BaseListCmd { - - private static final String s_name = "listbrocadevcsdevicenetworks"; - @Inject - protected BrocadeVcsElementService brocadeVcsElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = Constants.BROCADE_VCS_DEVICE_ID, type = CommandType.UUID, entityType = BrocadeVcsDeviceResponse.class, required = true, description = "Brocade vcs switch ID") - private Long brocadeVcsDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getBrocadeVcsDeviceId() { - return brocadeVcsDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { - try { - List networks = brocadeVcsElementService.listBrocadeVcsDeviceNetworks(this); - ListResponse response = new ListResponse(); - List networkResponses = new ArrayList(); - - if (networks != null && !networks.isEmpty()) { - for (Network network : networks) { - NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Full, network); - networkResponses.add(networkResponse); - } - } - - response.setResponses(networkResponses); - response.setResponseName(getCommandName()); - setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDevicesCmd.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDevicesCmd.java deleted file mode 100644 index 6a426e332901..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/commands/ListBrocadeVcsDevicesCmd.java +++ /dev/null @@ -1,108 +0,0 @@ -// -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.BrocadeVcsDeviceResponse; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.network.brocade.Constants; -import com.cloud.network.element.BrocadeVcsElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listBrocadeVcsDevices", responseObject = BrocadeVcsDeviceResponse.class, description = "Lists Brocade VCS Switches", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListBrocadeVcsDevicesCmd extends BaseListCmd { - private static final String s_name = "listbrocadevcsdeviceresponse"; - - @Inject - protected BrocadeVcsElementService brocadeVcsElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = Constants.BROCADE_VCS_DEVICE_ID, type = CommandType.UUID, entityType = BrocadeVcsDeviceResponse.class, description = "Brocade VCS switch ID") - private Long brocadeVcsDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getBrocadeVcsDeviceId() { - return brocadeVcsDeviceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - try { - List brocadeDevices = brocadeVcsElementService.listBrocadeVcsDevices(this); - ListResponse response = new ListResponse(); - List brocadeDevicesResponse = new ArrayList(); - - if (brocadeDevices != null && !brocadeDevices.isEmpty()) { - for (BrocadeVcsDeviceVO brocadeDeviceVO : brocadeDevices) { - BrocadeVcsDeviceResponse brocadeDeviceResponse = brocadeVcsElementService.createBrocadeVcsDeviceResponse(brocadeDeviceVO); - brocadeDevicesResponse.add(brocadeDeviceResponse); - } - } - - response.setResponses(brocadeDevicesResponse); - response.setResponseName(getCommandName()); - setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/response/BrocadeVcsDeviceResponse.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/response/BrocadeVcsDeviceResponse.java deleted file mode 100644 index bcc418e28ca5..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/api/response/BrocadeVcsDeviceResponse.java +++ /dev/null @@ -1,94 +0,0 @@ -// -// 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.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.network.brocade.Constants; -import com.cloud.serializer.Param; - -@EntityReference(value = BrocadeVcsDeviceVO.class) -public class BrocadeVcsDeviceResponse extends BaseResponse { - @SerializedName(Constants.BROCADE_VCS_DEVICE_ID) - @Param(description = "Device ID of the Brocade Vcs") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Param(description = "The physical Network to which this Brocade VCS belongs to") - private String physicalNetworkId; - - @SerializedName(ApiConstants.PROVIDER) - @Param(description = "Name of the provider") - private String providerName; - - @SerializedName(Constants.BROCADE_VCS_DEVICE_NAME) - @Param(description = "Device name") - private String deviceName; - - @SerializedName(ApiConstants.HOST_NAME) - @Param(description = "The principal switch IP address") - private String hostName; - - public String getId() { - return id; - } - - public String getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getProviderName() { - return providerName; - } - - public String getDeviceName() { - return deviceName; - } - - public String getHostName() { - return hostName; - } - - public void setId(String vcsDeviceId) { - this.id = vcsDeviceId; - } - - public void setPhysicalNetworkId(final String physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public void setProviderName(final String providerName) { - this.providerName = providerName; - } - - public void setDeviceName(final String deviceName) { - this.deviceName = deviceName; - } - - public void setHostName(final String hostName) { - this.hostName = hostName; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsDeviceVO.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsDeviceVO.java deleted file mode 100644 index e229e3c8b848..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsDeviceVO.java +++ /dev/null @@ -1,99 +0,0 @@ -// -// 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.network; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; - -@Entity -@Table(name = "external_brocade_vcs_devices") -public class BrocadeVcsDeviceVO implements InternalIdentity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "host_id") - private long hostId; - - @Column(name = "physical_network_id") - private long physicalNetworkId; - - @Column(name = "provider_name") - private String providerName; - - @Column(name = "device_name") - private String deviceName; - - public BrocadeVcsDeviceVO() { - uuid = UUID.randomUUID().toString(); - } - - public BrocadeVcsDeviceVO(final long hostId, long physicalNetworkId, final String providerName, final String deviceName) { - super(); - this.hostId = hostId; - this.physicalNetworkId = physicalNetworkId; - this.providerName = providerName; - this.deviceName = deviceName; - uuid = UUID.randomUUID().toString(); - } - - @Override - public long getId() { - return id; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public long getHostId() { - return hostId; - } - - public String getProviderName() { - return providerName; - } - - public String getDeviceName() { - return deviceName; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsNetworkVlanMappingVO.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsNetworkVlanMappingVO.java deleted file mode 100644 index fd3bc972168e..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/BrocadeVcsNetworkVlanMappingVO.java +++ /dev/null @@ -1,72 +0,0 @@ -// 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.network; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; - -@Entity -@Table(name = "brocade_network_vlan_map") -public class BrocadeVcsNetworkVlanMappingVO implements InternalIdentity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "network_id") - private long networkId; - - @Column(name = "vlan_id") - private int vlanId; - - public BrocadeVcsNetworkVlanMappingVO() { - } - - public BrocadeVcsNetworkVlanMappingVO(long networkId, int vlanId) { - this.networkId = networkId; - this.vlanId = vlanId; - } - - public long getNetworkId() { - return networkId; - } - - public void setNetworkId(long networkId) { - this.networkId = networkId; - } - - public int getVlanId() { - return vlanId; - } - - public void setVlanId(int vlanId) { - this.vlanId = vlanId; - } - - @Override - public long getId() { - return id; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java deleted file mode 100644 index cc7f99bb64e3..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApi.java +++ /dev/null @@ -1,543 +0,0 @@ -// 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.network.brocade; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.io.StringWriter; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.charset.Charset; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.network.schema.interfacevlan.InterfaceVlan; -import com.cloud.network.schema.interfacevlan.Interface; -import com.cloud.network.schema.interfacevlan.Vlan; -import com.cloud.network.schema.portprofile.PortProfile; -import com.cloud.network.schema.portprofile.PortProfile.Activate; -import com.cloud.network.schema.portprofile.PortProfile.Static; -import com.cloud.network.schema.portprofile.PortProfileGlobal; -import com.cloud.network.schema.portprofile.VlanProfile; -import com.cloud.network.schema.portprofile.VlanProfile.Switchport; -import com.cloud.network.schema.portprofile.VlanProfile.Switchport.Mode; -import com.cloud.network.schema.portprofile.VlanProfile.Switchport.Trunk; -import com.cloud.network.schema.portprofile.VlanProfile.Switchport.Trunk.Allowed; -import com.cloud.network.schema.portprofile.VlanProfile.SwitchportBasic; -import com.cloud.network.schema.portprofile.VlanProfile.SwitchportBasic.Basic; -import com.cloud.network.schema.showvcs.Output; - -public class BrocadeVcsApi { - protected Logger logger = LogManager.getLogger(getClass()); - - private final String _host; - private final String _adminuser; - private final String _adminpass; - - protected DefaultHttpClient _client; - - protected HttpRequestBase createMethod(String type, String uri) throws BrocadeVcsApiException { - String url; - try { - url = new URL(Constants.PROTOCOL, _host, Constants.PORT, uri).toString(); - } catch (final MalformedURLException e) { - logger.error("Unable to build Brocade Switch API URL", e); - throw new BrocadeVcsApiException("Unable to build Brocade Switch API URL", e); - } - - if ("post".equalsIgnoreCase(type)) { - return new HttpPost(url); - } else if ("get".equalsIgnoreCase(type)) { - return new HttpGet(url); - } else if ("delete".equalsIgnoreCase(type)) { - return new HttpDelete(url); - } else if ("patch".equalsIgnoreCase(type)) { - return new HttpPatch(url); - } else { - throw new BrocadeVcsApiException("Requesting unknown method type"); - } - } - - public BrocadeVcsApi(String address, String username, String password) { - _host = address; - _adminuser = username; - _adminpass = password; - _client = new DefaultHttpClient(); - _client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_adminuser, _adminpass)); - - } - - /* - * Get Operational Status - */ - public Output getSwitchStatus() throws BrocadeVcsApiException { - return executeRetreiveStatus(Constants.STATUS_URI); - - } - - /* - * Creates a new virtual network. - */ - public boolean createNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { - - if (createInterfaceVlan(vlanId)) { - - final PortProfile portProfile = createPortProfile(vlanId, networkId); - - if (portProfile != null) { - return activatePortProfile(portProfile); - } - } - return false; - } - - /* - * Activates a port-profile. - */ - private boolean activatePortProfile(PortProfile portProfile) throws BrocadeVcsApiException { - final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); - portProfile.setVlanProfile(null); - final Activate activate = new Activate(); - portProfile.setActivate(activate); - portProfileGlobal.setPortProfile(portProfile); - - //activate port-profile - return executeUpdateObject(portProfileGlobal, Constants.URI); - } - - /* - * Creates AMPP port-profile. - */ - private PortProfile createPortProfile(int vlanId, long networkId) throws BrocadeVcsApiException { - - final PortProfile portProfile = new PortProfile(); - portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); - if (executeCreateObject(portProfile, Constants.URI)) { - if (createVlanSubProfile(vlanId, portProfile)) { - return portProfile; - } - } - return null; - } - - /* - * Create vlan sub-profile for port-profile - */ - private boolean createVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { - final VlanProfile vlanProfile = new VlanProfile(); - portProfile.setVlanProfile(vlanProfile); - if (executeUpdateObject(portProfile, Constants.URI)) { - return configureVlanSubProfile(vlanId, portProfile); - } - return false; - } - - /* - * Configures vlan sub-profile for port-profile. - * - configure L2 mode for vlan sub-profile - * - configure trunk mode for vlan sub-profile - * - configure allowed VLANs for vlan sub-profile - */ - private boolean configureVlanSubProfile(int vlanId, PortProfile portProfile) throws BrocadeVcsApiException { - final SwitchportBasic switchPortBasic = new SwitchportBasic(); - final Basic basic = new Basic(); - switchPortBasic.setBasic(basic); - portProfile.getVlanProfile().setSwitchportBasic(switchPortBasic); - // configure L2 mode for vlan sub-profile - if (executeUpdateObject(portProfile, Constants.URI)) { - VlanProfile vlanProfile = new VlanProfile(); - Switchport switchPort = new Switchport(); - final Mode mode = new Mode(); - mode.setVlanMode("trunk"); - switchPort.setMode(mode); - vlanProfile.setSwitchport(switchPort); - portProfile.setVlanProfile(vlanProfile); - - // configure trunk mode for vlan sub-profile - if (executeUpdateObject(portProfile, Constants.URI)) { - vlanProfile = new VlanProfile(); - switchPort = new Switchport(); - final Trunk trunk = new Trunk(); - final Allowed allowed = new Allowed(); - final Allowed.Vlan allowedVlan = new Allowed.Vlan(); - allowedVlan.setAdd(vlanId); - allowed.setVlan(allowedVlan); - trunk.setAllowed(allowed); - switchPort.setTrunk(trunk); - vlanProfile.setSwitchport(switchPort); - portProfile.setVlanProfile(vlanProfile); - - //configure allowed VLANs for vlan sub-profile - return executeUpdateObject(portProfile, Constants.URI); - } - } - - return false; - - } - - /* - * Creates a vlan interface. - */ - private boolean createInterfaceVlan(int vlanId) throws BrocadeVcsApiException { - final InterfaceVlan interfaceVlan = new InterfaceVlan(); - final Interface interfaceObj = new Interface(); - final Vlan vlan = new Vlan(); - vlan.setName(vlanId); - interfaceObj.setVlan(vlan); - interfaceVlan.setInterface(interfaceObj); - - return executeUpdateObject(interfaceVlan, Constants.URI); - - } - - /* - * Associates a MAC address to virtual network. - */ - public boolean associateMacToNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { - - final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); - final PortProfile portProfile = new PortProfile(); - portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); - final Static staticObj = new Static(); - staticObj.setMacAddress(macAddress); - portProfile.setStatic(staticObj); - portProfileGlobal.setPortProfile(portProfile); - - //associates a mac address to a port-profile - return executeUpdateObject(portProfileGlobal, Constants.URI); - } - - /* - * Disassociates a MAC address from virtual network. - */ - public boolean disassociateMacFromNetwork(long networkId, String macAddress) throws BrocadeVcsApiException { - - final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); - final PortProfile portProfile = new PortProfile(); - portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); - final Static staticObj = new Static(); - staticObj.setOperation("delete"); - staticObj.setMacAddress(macAddress); - portProfile.setStatic(staticObj); - portProfileGlobal.setPortProfile(portProfile); - - //associates a mac address to a port-profile - return executeUpdateObject(portProfileGlobal, Constants.URI); - } - - /* - * Deletes a new virtual network. - */ - public boolean deleteNetwork(int vlanId, long networkId) throws BrocadeVcsApiException { - - if (deactivatePortProfile(networkId)) { - - if (deletePortProfile(networkId)) { - return deleteInterfaceVlan(vlanId); - } - } - return false; - } - - /* - * Deletes a vlan interface. - */ - private boolean deleteInterfaceVlan(int vlanId) throws BrocadeVcsApiException { - final InterfaceVlan interfaceVlan = new InterfaceVlan(); - final Interface interfaceObj = new Interface(); - final Vlan vlan = new Vlan(); - vlan.setOperation("delete"); - vlan.setName(vlanId); - interfaceObj.setVlan(vlan); - interfaceVlan.setInterface(interfaceObj); - - return executeUpdateObject(interfaceVlan, Constants.URI); - - } - - /* - * Deactivates a port-profile. - */ - private boolean deactivatePortProfile(long networkId) throws BrocadeVcsApiException { - final PortProfileGlobal portProfileGlobal = new PortProfileGlobal(); - final PortProfile portProfile = new PortProfile(); - portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); - final Activate activate = new Activate(); - activate.setOperation("delete"); - portProfile.setActivate(activate); - portProfileGlobal.setPortProfile(portProfile); - - //activate port-profile - return executeUpdateObject(portProfileGlobal, Constants.URI); - } - - /* - * Deletes AMPP port-profile. - */ - private boolean deletePortProfile(long networkId) throws BrocadeVcsApiException { - - final PortProfile portProfile = new PortProfile(); - portProfile.setName(Constants.PORT_PROFILE_NAME_PREFIX + networkId); - portProfile.setOperation("delete"); - //deletes port-profile - return executeUpdateObject(portProfile, Constants.URI); - } - - protected boolean executeUpdateObject(T newObject, String uri) throws BrocadeVcsApiException { - - final boolean result = true; - - if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { - throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); - } - - final HttpPatch pm = (HttpPatch)createMethod("patch", uri); - pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); - - pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); - - final HttpResponse response = executeMethod(pm); - - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { - - String errorMessage; - try { - errorMessage = responseToErrorMessage(response); - } catch (final IOException e) { - logger.error("Failed to update object : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to update object : " + e.getMessage()); - } - - pm.releaseConnection(); - logger.error("Failed to update object : " + errorMessage); - throw new BrocadeVcsApiException("Failed to update object : " + errorMessage); - } - - pm.releaseConnection(); - - return result; - } - - protected String convertToString(T object) throws BrocadeVcsApiException { - - final StringWriter stringWriter = new StringWriter(); - - try { - final JAXBContext context = JAXBContext.newInstance(object.getClass()); - final Marshaller marshaller = context.createMarshaller(); - - marshaller.marshal(object, stringWriter); - - } catch (final JAXBException e) { - logger.error("Failed to convert object to string : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to convert object to string : " + e.getMessage()); - } - - final String str = stringWriter.toString(); - logger.info(str); - - return str; - - } - - protected Output convertToXML(String object) throws BrocadeVcsApiException { - - Output output = null; - try { - final JAXBContext context = JAXBContext.newInstance(Output.class); - - final StringReader reader = new StringReader(object); - - final Unmarshaller unmarshaller = context.createUnmarshaller(); - final Object result = unmarshaller.unmarshal(reader); - - if (result instanceof Output) { - output = (Output)result; - logger.info(output); - } - - } catch (final JAXBException e) { - logger.error("Failed to convert string to object : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to convert string to object : " + e.getMessage()); - } - - return output; - - } - - protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { - if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { - throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); - } - - final boolean result = true; - final HttpPost pm = (HttpPost)createMethod("post", uri); - pm.setHeader("Accept", "application/vnd.configuration.resource+xml"); - pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML)); - - final HttpResponse response = executeMethod(pm); - - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { - - String errorMessage; - try { - errorMessage = responseToErrorMessage(response); - } catch (final IOException e) { - logger.error("Failed to create object : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage()); - } - - pm.releaseConnection(); - logger.error("Failed to create object : " + errorMessage); - throw new BrocadeVcsApiException("Failed to create object : " + errorMessage); - } - - pm.releaseConnection(); - - return result; - } - - protected Output executeRetreiveStatus(String uri) throws BrocadeVcsApiException { - if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { - throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); - } - - String readLine = null; - StringBuffer sb = null; - - final HttpPost pm = (HttpPost)createMethod("post", uri); - pm.setHeader("Accept", "application/vnd.operational-state.resource+xml"); - pm.setEntity(new StringEntity("", ContentType.APPLICATION_XML)); - - final HttpResponse response = executeMethod(pm); - - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { - - String errorMessage; - try { - errorMessage = responseToErrorMessage(response); - } catch (final IOException e) { - logger.error("Failed to retreive status : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); - } - - pm.releaseConnection(); - logger.error("Failed to retreive status : " + errorMessage); - throw new BrocadeVcsApiException("Failed to retreive status : " + errorMessage); - } - - try (BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { - sb = new StringBuffer(); - - while ((readLine = br.readLine()) != null) { - logger.debug(readLine); - sb.append(readLine); - - } - } catch (final Exception e) { - logger.error("Failed to retreive status : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to retreive status : " + e.getMessage()); - } - - pm.releaseConnection(); - - return convertToXML(sb.toString()); - } - - protected void executeDeleteObject(String uri) throws BrocadeVcsApiException { - if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) { - throw new BrocadeVcsApiException("Hostname/credentials are null or empty"); - } - - final HttpDelete dm = (HttpDelete)createMethod("delete", uri); - dm.setHeader("Accept", "application/vnd.configuration.resource+xml"); - - final HttpResponse response = executeMethod(dm); - - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) { - - String errorMessage; - try { - errorMessage = responseToErrorMessage(response); - } catch (final IOException e) { - logger.error("Failed to delete object : " + e.getMessage()); - throw new BrocadeVcsApiException("Failed to delete object : " + e.getMessage()); - } - - dm.releaseConnection(); - logger.error("Failed to delete object : " + errorMessage); - throw new BrocadeVcsApiException("Failed to delete object : " + errorMessage); - } - dm.releaseConnection(); - } - - protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { - HttpResponse response = null; - try { - response = _client.execute(method); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - method.releaseConnection(); - response = _client.execute(method); - } - } catch (final IOException e) { - logger.error("IOException caught while trying to connect to the Brocade Switch", e); - method.releaseConnection(); - throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e); - } - - return response; - } - - private String responseToErrorMessage(HttpResponse response) throws IOException { - - if ("text/html".equals(response.getEntity().getContentType().getValue())) { - - try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName("UTF-8")))) { - - final StringBuffer result = new StringBuffer(); - String line = ""; - while ((line = rd.readLine()) != null) { - result.append(line); - } - return result.toString(); - } - } - return null; - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApiException.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApiException.java deleted file mode 100644 index 76f30797388e..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/BrocadeVcsApiException.java +++ /dev/null @@ -1,36 +0,0 @@ -// 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.network.brocade; - -public class BrocadeVcsApiException extends Exception { - - public BrocadeVcsApiException() { - } - - public BrocadeVcsApiException(String message) { - super(message); - } - - public BrocadeVcsApiException(Throwable cause) { - super(cause); - } - - public BrocadeVcsApiException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/Constants.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/Constants.java deleted file mode 100644 index 5a9fa0afda93..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/brocade/Constants.java +++ /dev/null @@ -1,37 +0,0 @@ -// 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.network.brocade; - -public class Constants { - public static final String PROTOCOL = "http"; - - public static final String URI = "/rest/config/running"; - - public static final String STATUS_URI = "/rest/operational-state/show-vcs"; - - public static final int PORT = 80; - - public static final String PORT_PROFILE_NAME_PREFIX = "cloudstack-profile-"; - - public static final String BROCADE_VCS_DEVICE_ID = "vcsdeviceid"; - public static final String BROCADE_VCS_DEVICE_NAME = "brocadedevicename"; - - public static final String EVENT_EXTERNAL_VCS_CONTROLLER_ADD = "PHYSICAL.VCSCONTROLLER.ADD"; - public static final String EVENT_EXTERNAL_VCS_CONTROLLER_DELETE = "PHYSICAL.VCSCONTROLLER.DELETE"; - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDao.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDao.java deleted file mode 100644 index 76e36a18f5df..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDao.java +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.utils.db.GenericDao; - -public interface BrocadeVcsDao extends GenericDao { - /** - * list all the brocade vcs devices added in to this physical network - * @param physicalNetworkId physical network Id - * @return list of BrocadevcsDeviceVO for this zone and pod. - */ - List listByPhysicalNetwork(final long physicalNetworkId); - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDaoImpl.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDaoImpl.java deleted file mode 100644 index 80bc7dac224b..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsDaoImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class BrocadeVcsDaoImpl extends GenericDaoBase implements BrocadeVcsDao { - - protected final SearchBuilder physicalNetworkIdSearch; - - public BrocadeVcsDaoImpl() { - physicalNetworkIdSearch = createSearchBuilder(); - physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); - physicalNetworkIdSearch.done(); - } - - @Override - public List listByPhysicalNetwork(final long physicalNetworkId) { - SearchCriteria sc = physicalNetworkIdSearch.create(); - sc.setParameters("physicalNetworkId", physicalNetworkId); - return search(sc, null); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java deleted file mode 100644 index 16d29860c8e0..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDao.java +++ /dev/null @@ -1,32 +0,0 @@ -// 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.network.dao; - -import com.cloud.network.BrocadeVcsNetworkVlanMappingVO; -import com.cloud.utils.db.GenericDao; - -public interface BrocadeVcsNetworkVlanMappingDao extends GenericDao { - - /** - * find the mapping for a network - * @param networkId - * the network id - * @return BrocadeNetworkHostMapping for this network id or null if it does not - * exist - */ - public BrocadeVcsNetworkVlanMappingVO findByNetworkId(long networkId); -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java deleted file mode 100644 index 753fd278b298..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/dao/BrocadeVcsNetworkVlanMappingDaoImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -// 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.network.dao; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.BrocadeVcsNetworkVlanMappingVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class BrocadeVcsNetworkVlanMappingDaoImpl extends GenericDaoBase implements BrocadeVcsNetworkVlanMappingDao { - - protected final SearchBuilder networkSearch; - - public BrocadeVcsNetworkVlanMappingDaoImpl() { - networkSearch = createSearchBuilder(); - networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ); - networkSearch.done(); - - } - - @Override - public BrocadeVcsNetworkVlanMappingVO findByNetworkId(long networkId) { - SearchCriteria sc = networkSearch.create(); - sc.setParameters("network_id", networkId); - return findOneBy(sc); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElement.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElement.java deleted file mode 100644 index 326ea4948604..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElement.java +++ /dev/null @@ -1,461 +0,0 @@ -// 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.network.element; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; -import org.springframework.stereotype.Component; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.StartupBrocadeVcsCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddBrocadeVcsDeviceCmd; -import com.cloud.api.commands.DeleteBrocadeVcsDeviceCmd; -import com.cloud.api.commands.ListBrocadeVcsDeviceNetworksCmd; -import com.cloud.api.commands.ListBrocadeVcsDevicesCmd; -import com.cloud.api.response.BrocadeVcsDeviceResponse; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.DetailVO; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Networks; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.dao.BrocadeVcsDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.resource.BrocadeVcsResource; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceState; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.NicDao; - -@Component -public class BrocadeVcsElement extends AdapterBase implements NetworkElement, ResourceStateAdapter, BrocadeVcsElementService { - - private static final Map> capabilities = setCapabilities(); - - @Inject - NicDao _nicDao; - @Inject - ResourceManager _resourceMgr; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - @Inject - protected BrocadeVcsDao _brocadeVcsDao; - @Inject - HostDetailsDao _hostDetailsDao; - @Inject - HostDao _hostDao; - @Inject - AgentManager _agentMgr; - @Inject - NetworkDao _networkDao; - @Inject - NetworkOrchestrationService _networkManager; - @Inject - NetworkModel _networkModel; - @Inject - ConfigurationManager _configMgr; - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - VlanDao _vlanDao; - @Inject - IpAddressManager _ipAddrMgr; - - @Override - public Map> getCapabilities() { - return capabilities; - } - - @Override - public Provider getProvider() { - return Network.Provider.BrocadeVcs; - } - - protected boolean canHandle(Network network, Service service) { - logger.debug(String.format("Checking if BrocadeVcsElement can handle service %s on network %s", service.getName(), network)); - if (network.getBroadcastDomainType() != BroadcastDomainType.Vcs) { - return false; - } - - if (!_networkModel.isProviderForNetwork(getProvider(), network.getId())) { - logger.debug(String.format("BrocadeVcsElement is not a provider for network %s", network)); - return false; - } - - if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, Network.Provider.BrocadeVcs)) { - logger.debug(String.format("BrocadeVcsElement can't provide the %s service on network %s", service.getName(), network)); - return false; - } - - return true; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); - return true; - } - - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - logger.debug(String.format("entering BrocadeVcsElement implement function for network %s (state %s)", network, network.getState())); - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - // Nothing to do here. - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - - if (!services.contains(Service.Connectivity)) { - logger.warn("Unable to provide services without Connectivity service enabled for this element"); - return false; - } - return true; - } - - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); - - // L2 Support - capabilities.put(Service.Connectivity, null); - - return capabilities; - } - - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddBrocadeVcsDeviceCmd.class); - cmdList.add(DeleteBrocadeVcsDeviceCmd.class); - cmdList.add(ListBrocadeVcsDeviceNetworksCmd.class); - cmdList.add(ListBrocadeVcsDevicesCmd.class); - return cmdList; - } - - @Override - @DB - public BrocadeVcsDeviceVO addBrocadeVcsDevice(AddBrocadeVcsDeviceCmd cmd) { - ServerResource resource = new BrocadeVcsResource(); - final String deviceName = Network.Provider.BrocadeVcs.getName(); - NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName); - if (networkDevice == null) { - throw new CloudRuntimeException("No network device found for " + deviceName); - } - final Long physicalNetworkId = cmd.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); - } - long zoneId = physicalNetwork.getDataCenterId(); - - final PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), - networkDevice.getNetworkServiceProvder()); - if (ntwkSvcProvider == null) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is not enabled in the physical network: %s to add this device", networkDevice.getNetworkServiceProvder(), physicalNetwork)); - } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is in shutdown state in the physical network: %s to add this device", ntwkSvcProvider.getProviderName(), physicalNetwork)); - } - - Map params = new HashMap(); - params.put("guid", UUID.randomUUID().toString()); - params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); - params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); - params.put("name", "Brocade VCS - " + cmd.getHost()); - params.put("ip", cmd.getHost()); - params.put("adminuser", cmd.getUsername()); - params.put("adminpass", cmd.getPassword()); - - Map hostdetails = new HashMap(); - hostdetails.putAll(params); - - try { - resource.configure(cmd.getHost(), hostdetails); - - final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params); - if (host != null) { - return Transaction.execute(new TransactionCallback() { - @Override - public BrocadeVcsDeviceVO doInTransaction(TransactionStatus status) { - BrocadeVcsDeviceVO brocadeVcsDevice = new BrocadeVcsDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName); - _brocadeVcsDao.persist(brocadeVcsDevice); - - DetailVO detail = new DetailVO(host.getId(), "brocadevcsdeviceid", String.valueOf(brocadeVcsDevice.getId())); - _hostDetailsDao.persist(detail); - - return brocadeVcsDevice; - } - }); - } else { - throw new CloudRuntimeException("Failed to add Brocade VCS Switch due to internal error."); - } - } catch (ConfigurationException e) { - throw new CloudRuntimeException(e.getMessage()); - } - - } - - @Override - public BrocadeVcsDeviceResponse createBrocadeVcsDeviceResponse(BrocadeVcsDeviceVO brocadeVcsDeviceVO) { - HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDeviceVO.getHostId()); - _hostDao.loadDetails(brocadeVcsHost); - - BrocadeVcsDeviceResponse response = new BrocadeVcsDeviceResponse(); - response.setDeviceName(brocadeVcsDeviceVO.getDeviceName()); - PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(brocadeVcsDeviceVO.getPhysicalNetworkId()); - if (pnw != null) { - response.setPhysicalNetworkId(pnw.getUuid()); - } - response.setId(brocadeVcsDeviceVO.getUuid()); - response.setProviderName(brocadeVcsDeviceVO.getProviderName()); - response.setHostName(brocadeVcsHost.getDetail("ip")); - response.setObjectName("brocadevcsdevice"); - return response; - } - - @Override - public boolean deleteBrocadeVcsDevice(DeleteBrocadeVcsDeviceCmd cmd) { - Long brocadeDeviceId = cmd.getBrocadeVcsDeviceId(); - BrocadeVcsDeviceVO brocadeVcsDevice = _brocadeVcsDao.findById(brocadeDeviceId); - if (brocadeVcsDevice == null) { - throw new InvalidParameterValueException("Could not find a brocade vcs switch with id " + brocadeVcsDevice); - } - - // Find the physical network we work for - Long physicalNetworkId = brocadeVcsDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork != null) { - // Lets see if there are networks that use us - // Find the brocade networks on this physical network - List networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId); - if (networkList != null) { - // Networks with broadcast type vcs are ours - for (NetworkVO network : networkList) { - if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Vcs) { - if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) { - throw new CloudRuntimeException("This Brocade VCS Switch can not be deleted as there are one or more logical networks provisioned by cloudstack."); - } - } - } - } - } - - HostVO brocadeHost = _hostDao.findById(brocadeVcsDevice.getHostId()); - Long hostId = brocadeHost.getId(); - - brocadeHost.setResourceState(ResourceState.Maintenance); - _hostDao.update(hostId, brocadeHost); - _resourceMgr.deleteHost(hostId, false, false); - - _brocadeVcsDao.remove(brocadeDeviceId); - return true; - } - - @Override - public List listBrocadeVcsDevices(ListBrocadeVcsDevicesCmd cmd) { - Long physicalNetworkId = cmd.getPhysicalNetworkId(); - Long brocadeVcsDeviceId = cmd.getBrocadeVcsDeviceId(); - List responseList = new ArrayList(); - - if (physicalNetworkId == null && brocadeVcsDeviceId == null) { - throw new InvalidParameterValueException("Either physical network Id or brocade vcs switch Id must be specified"); - } - - if (brocadeVcsDeviceId != null) { - BrocadeVcsDeviceVO brocadeVcsDevice = _brocadeVcsDao.findById(brocadeVcsDeviceId); - if (brocadeVcsDevice == null) { - throw new InvalidParameterValueException("Could not find Brocade VCS Switch with id: " + brocadeVcsDeviceId); - } - responseList.add(brocadeVcsDevice); - } else { - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); - } - responseList = _brocadeVcsDao.listByPhysicalNetwork(physicalNetworkId); - } - - return responseList; - } - - @Override - public List listBrocadeVcsDeviceNetworks(ListBrocadeVcsDeviceNetworksCmd cmd) { - Long brocadeDeviceId = cmd.getBrocadeVcsDeviceId(); - BrocadeVcsDeviceVO brocadeVcsDevice = _brocadeVcsDao.findById(brocadeDeviceId); - if (brocadeVcsDevice == null) { - throw new InvalidParameterValueException("Could not find a Brocade VCS Switch with id " + brocadeDeviceId); - } - - // Find the physical network we work for - Long physicalNetworkId = brocadeVcsDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - // No such physical network, so no provisioned networks - return Collections.emptyList(); - } - - // Find the brocade networks on this physical network - List networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId); - if (networkList == null) { - return Collections.emptyList(); - } - - // Networks with broadcast type vcs are ours - List responseList = new ArrayList(); - for (NetworkVO network : networkList) { - if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Vcs) { - responseList.add(network); - } - } - - return responseList; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - if (!(startup[0] instanceof StartupBrocadeVcsCommand)) { - return null; - } - host.setType(Host.Type.L2Networking); - return host; - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (!(host.getType() == Host.Type.L2Networking)) { - return null; - } - return new DeleteHostAnswer(true); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElementService.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElementService.java deleted file mode 100644 index b8db60cc92ef..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/element/BrocadeVcsElementService.java +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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.network.element; - -import java.util.List; - -import com.cloud.api.commands.AddBrocadeVcsDeviceCmd; -import com.cloud.api.commands.DeleteBrocadeVcsDeviceCmd; -import com.cloud.api.commands.ListBrocadeVcsDeviceNetworksCmd; -import com.cloud.api.commands.ListBrocadeVcsDevicesCmd; -import com.cloud.api.response.BrocadeVcsDeviceResponse; -import com.cloud.network.Network; -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.utils.component.PluggableService; - -public interface BrocadeVcsElementService extends PluggableService { - - public BrocadeVcsDeviceVO addBrocadeVcsDevice(AddBrocadeVcsDeviceCmd cmd); - - public BrocadeVcsDeviceResponse createBrocadeVcsDeviceResponse(BrocadeVcsDeviceVO brocadeDeviceVO); - - boolean deleteBrocadeVcsDevice(DeleteBrocadeVcsDeviceCmd cmd); - - List listBrocadeVcsDeviceNetworks(ListBrocadeVcsDeviceNetworksCmd cmd); - - List listBrocadeVcsDevices(ListBrocadeVcsDevicesCmd cmd); - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java deleted file mode 100644 index 4fe75ba7519c..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuru.java +++ /dev/null @@ -1,263 +0,0 @@ -// 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.network.guru; - - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.AssociateMacToNetworkAnswer; -import com.cloud.agent.api.AssociateMacToNetworkCommand; -import com.cloud.agent.api.CreateNetworkAnswer; -import com.cloud.agent.api.CreateNetworkCommand; -import com.cloud.agent.api.DeleteNetworkAnswer; -import com.cloud.agent.api.DeleteNetworkCommand; -import com.cloud.agent.api.DisassociateMacFromNetworkAnswer; -import com.cloud.agent.api.DisassociateMacFromNetworkCommand; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.network.BrocadeVcsNetworkVlanMappingVO; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Service; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkProfile; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetwork.IsolationMethod; -import com.cloud.network.dao.BrocadeVcsDao; -import com.cloud.network.dao.BrocadeVcsNetworkVlanMappingDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; -import com.cloud.resource.ResourceManager; -import com.cloud.user.Account; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -import javax.inject.Inject; -import java.util.List; - -public class BrocadeVcsGuestNetworkGuru extends GuestNetworkGuru { - - @Inject - NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; - @Inject - ResourceManager _resourceMgr; - @Inject - AgentManager _agentMgr; - @Inject - protected BrocadeVcsDao _brocadeVcsDao; - @Inject - protected BrocadeVcsNetworkVlanMappingDao _brocadeVcsNetworkVlanDao; - @Inject - PhysicalNetworkServiceProviderDao _pNSPDao; - @Inject - HostDao _hostDao; - - public BrocadeVcsGuestNetworkGuru() { - super(); - _isolationMethods = new IsolationMethod[] {new IsolationMethod("VCS")}; - } - - @Override - protected boolean canHandle(NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) { - // This guru handles only Guest Isolated network that supports L2 connectivity service - if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && offering.getGuestType() == Network.GuestType.Isolated - && isMyIsolationMethod(physicalNetwork) && _ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) { - return true; - } else { - logger.trace("We only take care of Guest networks of type " + GuestType.Isolated + " in zone of type " + NetworkType.Advanced); - return false; - } - } - - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, String name, Long vpcId, Account owner) { - // Check of the isolation type of the related physical network is VLAN - PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); - DataCenter dc = _dcDao.findById(plan.getDataCenterId()); - if (!canHandle(offering, dc.getNetworkType(), physnet)) { - logger.debug("Refusing to design this network"); - return null; - } - - logger.debug("Physical isolation type is VCS, asking GuestNetworkGuru to design this network"); - NetworkVO networkObject = (NetworkVO)super.design(offering, plan, userSpecified, name, vpcId, owner); - if (networkObject == null) { - return null; - } - // Override the broadcast domain type - networkObject.setBroadcastDomainType(BroadcastDomainType.Vcs); - networkObject.setState(State.Allocated); - - return networkObject; - } - - @Override - public Network implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException { - assert (network.getState() == State.Implementing) : "Why are we implementing " + network; - - Network implemented = super.implement(network, offering, dest, context); - - int vlanTag = Integer.parseInt(BroadcastDomainType.getValue(implemented.getBroadcastUri())); - - //get physical network id - Long physicalNetworkId = network.getPhysicalNetworkId(); - - List devices = _brocadeVcsDao.listByPhysicalNetwork(physicalNetworkId); - if (devices.isEmpty()) { - logger.error("No Brocade VCS Switch on physical network " + physicalNetworkId); - return null; - } - - for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) { - HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId()); - - // create createNetworkCmd instance and agentMgr execute it. - CreateNetworkCommand cmd = new CreateNetworkCommand(vlanTag, network.getId(), context.getDomain().getName() + "-" + context.getAccount().getAccountName()); - CreateNetworkAnswer answer = (CreateNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("CreateNetworkCommand failed"); - logger.error(String.format("Unable to create network %s", network)); - return null; - } - - } - - // Persist the network-vlan mapping from db - BrocadeVcsNetworkVlanMappingVO brocadeVcsNetworkVlanMapping = new BrocadeVcsNetworkVlanMappingVO(network.getId(), vlanTag); - _brocadeVcsNetworkVlanDao.persist(brocadeVcsNetworkVlanMapping); - - return implemented; - } - - @Override - public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { - super.reserve(nic, network, vm, dest, context); - - DataCenter dc = _dcDao.findById(network.getDataCenterId()); - - String interfaceMac = nic.getMacAddress(); - - List devices = _brocadeVcsDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Brocade VCS Switch on physical network " + network.getPhysicalNetworkId()); - return; - } - for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) { - HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId()); - - // create AssociateMacToNetworkCmd instance and agentMgr execute it. - AssociateMacToNetworkCommand cmd = new AssociateMacToNetworkCommand(network.getId(), interfaceMac, context.getDomain().getName() + "-" - + context.getAccount().getAccountName()); - AssociateMacToNetworkAnswer answer = (AssociateMacToNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("AssociateMacToNetworkCommand failed"); - throw new InsufficientVirtualNetworkCapacityException(String.format("Unable to associate mac %s to network %s", interfaceMac, network), DataCenter.class, dc.getId()); - } - } - - } - - @Override - public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) { - - String interfaceMac = nic.getMacAddress(); - - List devices = _brocadeVcsDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Brocade VCS Switch on physical network " + network.getPhysicalNetworkId()); - return; - } - for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) { - HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId()); - - // create DisassociateMacFromNetworkCmd instance and agentMgr execute it. - DisassociateMacFromNetworkCommand cmd = new DisassociateMacFromNetworkCommand(network.getId(), interfaceMac); - DisassociateMacFromNetworkAnswer answer = (DisassociateMacFromNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("DisassociateMacFromNetworkCommand failed"); - logger.error(String.format("Unable to disassociate mac %s from network %s", interfaceMac, network)); - return; - } - } - super.deallocate(network, nic, vm); - } - - @Override - public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { - return super.release(nic, vm, reservationId); - } - - @Override - public void shutdown(NetworkProfile profile, NetworkOffering offering) { - - super.shutdown(profile, offering); - } - - @Override - public boolean trash(Network network, NetworkOffering offering) { - - int vlanTag = 0; - // Get the network-vlan mapping from db - BrocadeVcsNetworkVlanMappingVO brocadeVcsNetworkVlanMapping = _brocadeVcsNetworkVlanDao.findByNetworkId(network.getId()); - - if (brocadeVcsNetworkVlanMapping != null) { - vlanTag = brocadeVcsNetworkVlanMapping.getVlanId(); - } else { - logger.error(String.format("Not able to find vlanId for network %s", network)); - return false; - } - - List devices = _brocadeVcsDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Brocade VCS Switch on physical network " + network.getPhysicalNetworkId()); - return false; - } - for (BrocadeVcsDeviceVO brocadeVcsDevice : devices) { - HostVO brocadeVcsHost = _hostDao.findById(brocadeVcsDevice.getHostId()); - - // create deleteNetworkCmd instance and agentMgr execute it. - DeleteNetworkCommand cmd = new DeleteNetworkCommand(vlanTag, network.getId()); - DeleteNetworkAnswer answer = (DeleteNetworkAnswer)_agentMgr.easySend(brocadeVcsHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("DeleteNetworkCommand failed"); - logger.error(String.format("Unable to delete network %s", network)); - return false; - } - } - - // Remove the network-vlan mapping from db - _brocadeVcsNetworkVlanDao.remove(brocadeVcsNetworkVlanMapping.getId()); - return super.trash(network, offering); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/resource/BrocadeVcsResource.java b/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/resource/BrocadeVcsResource.java deleted file mode 100644 index 845580b11563..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/java/com/cloud/network/resource/BrocadeVcsResource.java +++ /dev/null @@ -1,311 +0,0 @@ -// 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.network.resource; - -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AssociateMacToNetworkAnswer; -import com.cloud.agent.api.AssociateMacToNetworkCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreateNetworkAnswer; -import com.cloud.agent.api.CreateNetworkCommand; -import com.cloud.agent.api.DeleteNetworkAnswer; -import com.cloud.agent.api.DeleteNetworkCommand; -import com.cloud.agent.api.DisassociateMacFromNetworkAnswer; -import com.cloud.agent.api.DisassociateMacFromNetworkCommand; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupBrocadeVcsCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.host.Host; -import com.cloud.host.Host.Type; -import com.cloud.network.brocade.BrocadeVcsApi; -import com.cloud.network.brocade.BrocadeVcsApiException; -import com.cloud.network.schema.showvcs.Output; -import com.cloud.network.schema.showvcs.VcsNodeInfo; -import com.cloud.resource.ServerResource; - -public class BrocadeVcsResource implements ServerResource { - protected Logger logger = LogManager.getLogger(getClass()); - - private String _name; - private String _guid; - private String _zoneId; - private int _numRetries; - - private BrocadeVcsApi _brocadeVcsApi; - - protected BrocadeVcsApi createBrocadeVcsApi(String ip, String username, String password) { - - return new BrocadeVcsApi(ip, username, password); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - - _name = (String)params.get("name"); - if (_name == null) { - throw new ConfigurationException("Unable to find name"); - } - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - _zoneId = (String)params.get("zoneId"); - if (_zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - _numRetries = 2; - - String ip = (String)params.get("ip"); - if (ip == null) { - throw new ConfigurationException("Unable to find IP"); - } - - String adminuser = (String)params.get("adminuser"); - if (adminuser == null) { - throw new ConfigurationException("Unable to find admin username"); - } - - String adminpass = (String)params.get("adminpass"); - if (adminpass == null) { - throw new ConfigurationException("Unable to find admin password"); - } - - _brocadeVcsApi = createBrocadeVcsApi(ip, adminuser, adminpass); - - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public Type getType() { - return Host.Type.L2Networking; - } - - @Override - public StartupCommand[] initialize() { - StartupBrocadeVcsCommand sc = new StartupBrocadeVcsCommand(); - sc.setGuid(_guid); - sc.setName(_name); - sc.setDataCenter(_zoneId); - sc.setPrivateIpAddress(""); - sc.setStorageIpAddress(""); - sc.setVersion(BrocadeVcsResource.class.getPackage().getImplementationVersion()); - return new StartupCommand[] {sc}; - } - - @Override - public PingCommand getCurrentStatus(long id) { - - Output output; - try { - output = _brocadeVcsApi.getSwitchStatus(); - } catch (BrocadeVcsApiException e) { - logger.error("getSwitchStatus failed", e); - return null; - } - - List vcsNodes = output.getVcsNodes().getVcsNodeInfo(); - if (vcsNodes != null && !vcsNodes.isEmpty()) { - for (VcsNodeInfo vcsNodeInfo : vcsNodes) { - if (!"Online".equals(vcsNodeInfo.getNodeState())) { - logger.error("Brocade Switch is not ready: " + id); - return null; - } - } - } - return new PingCommand(Host.Type.L2Networking, id); - - } - - @Override - public Answer executeRequest(Command cmd) { - return executeRequest(cmd, _numRetries); - } - - public Answer executeRequest(Command cmd, int numRetries) { - if (cmd instanceof ReadyCommand) { - return executeRequest((ReadyCommand)cmd); - } else if (cmd instanceof MaintainCommand) { - return executeRequest((MaintainCommand)cmd); - } else if (cmd instanceof CreateNetworkCommand) { - return executeRequest((CreateNetworkCommand)cmd, numRetries); - } else if (cmd instanceof AssociateMacToNetworkCommand) { - return executeRequest((AssociateMacToNetworkCommand)cmd, numRetries); - } else if (cmd instanceof DisassociateMacFromNetworkCommand) { - return executeRequest((DisassociateMacFromNetworkCommand)cmd, numRetries); - } else if (cmd instanceof DeleteNetworkCommand) { - return executeRequest((DeleteNetworkCommand)cmd, numRetries); - } - logger.debug("Received unsupported command " + cmd.toString()); - return Answer.createUnsupportedCommandAnswer(cmd); - } - - @Override - public void disconnected() { - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - } - - private Answer executeRequest(CreateNetworkCommand cmd, int numRetries) { - - try { - boolean result = _brocadeVcsApi.createNetwork(cmd.getVlanId(), cmd.getNetworkId()); - return new CreateNetworkAnswer(cmd, result, "Port Profile " + cmd.getNetworkId() + " created"); - } catch (BrocadeVcsApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new CreateNetworkAnswer(cmd, e); - } - } - - } - - private Answer executeRequest(AssociateMacToNetworkCommand cmd, int numRetries) { - - try { - - String mac = macReformat64To32(cmd.getInterfaceMac()); - boolean result = _brocadeVcsApi.associateMacToNetwork(cmd.getNetworkId(), mac); - return new AssociateMacToNetworkAnswer(cmd, result, "Association of mac " + cmd.getInterfaceMac() + " to network " + cmd.getNetworkId() + " done"); - } catch (BrocadeVcsApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new AssociateMacToNetworkAnswer(cmd, e); - } - } - - } - - private Answer executeRequest(DisassociateMacFromNetworkCommand cmd, int numRetries) { - - try { - - String mac = macReformat64To32(cmd.getInterfaceMac()); - boolean result = _brocadeVcsApi.disassociateMacFromNetwork(cmd.getNetworkId(), mac); - return new DisassociateMacFromNetworkAnswer(cmd, result, "Disassociation of mac " + cmd.getInterfaceMac() + " from network " + cmd.getNetworkId() + " done"); - } catch (BrocadeVcsApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new DisassociateMacFromNetworkAnswer(cmd, e); - } - } - - } - - private Answer executeRequest(DeleteNetworkCommand cmd, int numRetries) { - - try { - boolean result = _brocadeVcsApi.deleteNetwork(cmd.getVlanId(), cmd.getNetworkId()); - return new DeleteNetworkAnswer(cmd, result, "Port Profile " + cmd.getNetworkId() + " deleted"); - } catch (BrocadeVcsApiException e) { - if (numRetries > 0) { - return retry(cmd, --numRetries); - } else { - return new DeleteNetworkAnswer(cmd, e); - } - } - - } - - private String macReformat64To32(String interfaceMac) { - String mac = interfaceMac.replace(":", ""); - mac = mac.substring(0, 4) + "." + mac.substring(4, 8) + "." + mac.subSequence(8, 12); - return mac; - - } - - private Answer executeRequest(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - private Answer executeRequest(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - private Answer retry(Command cmd, int numRetries) { - logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries); - return executeRequest(cmd, numRetries); - } - - @Override - public void setName(String name) { - - } - - @Override - public void setConfigParams(Map params) { - - } - - @Override - public Map getConfigParams() { - - return null; - } - - @Override - public int getRunLevel() { - - return 0; - } - - @Override - public void setRunLevel(int level) { - - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/main/resources/BrocadeInterfaceSchema.xsd b/plugins/network-elements/brocade-vcs/src/main/resources/BrocadeInterfaceSchema.xsd deleted file mode 100644 index d24e84506163..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/resources/BrocadeInterfaceSchema.xsd +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - 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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/brocade-vcs/src/main/resources/BrocadePortProfileSchema.xsd b/plugins/network-elements/brocade-vcs/src/main/resources/BrocadePortProfileSchema.xsd deleted file mode 100644 index 9f21ef070c87..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/resources/BrocadePortProfileSchema.xsd +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - 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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/brocade-vcs/src/main/resources/BrocadeShowVcsSchema.xsd b/plugins/network-elements/brocade-vcs/src/main/resources/BrocadeShowVcsSchema.xsd deleted file mode 100644 index aca9125a70ac..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/resources/BrocadeShowVcsSchema.xsd +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - 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. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/module.properties b/plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/module.properties deleted file mode 100644 index b010fba2ab92..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=vcs -parent=network diff --git a/plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/spring-vcs-context.xml b/plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/spring-vcs-context.xml deleted file mode 100644 index 4ba9ecbf46a2..000000000000 --- a/plugins/network-elements/brocade-vcs/src/main/resources/META-INF/cloudstack/vcs/spring-vcs-context.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - diff --git a/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/brocade/BrocadeVcsApiTest.java b/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/brocade/BrocadeVcsApiTest.java deleted file mode 100644 index 101421c88ffb..000000000000 --- a/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/brocade/BrocadeVcsApiTest.java +++ /dev/null @@ -1,185 +0,0 @@ -// -// 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.network.brocade; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import java.io.IOException; - -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; - -import com.cloud.network.schema.showvcs.Output; - -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.junit.Before; -import org.junit.Test; - -public class BrocadeVcsApiTest { - protected static final long NETWORK_ID = 42L; - protected static final int VLAN_ID = 14; - private static final String MAC_ADDRESS_32 = "0050.56bf.0002"; - protected static final String OUTPUT_XML_RESPONSE = " Online "; - BrocadeVcsApi api; - DefaultHttpClient client = mock(DefaultHttpClient.class); - HttpRequestBase method; - HttpResponse response; - HttpResponse postResponse; - String type; - String uri; - - @Before - public void setUp() { - api = new BrocadeVcsApi("localhost", "admin", "password") { - - @Override - public HttpRequestBase createMethod(final String newType, final String newUri) { - type = newType; - uri = newUri; - return method; - } - - @Override - public HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException { - return response; - } - - @Override - protected boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException { - - return true; - } - }; - - api._client = client; - - } - - @Test - public void testGetSwitchStatus() throws BrocadeVcsApiException, IOException { - // Prepare - - method = mock(HttpPost.class); - - response = mock(HttpResponse.class); - final StatusLine statusLine = mock(StatusLine.class); - when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK); - when(response.getStatusLine()).thenReturn(statusLine); - when(response.getEntity()).thenReturn(new StringEntity(OUTPUT_XML_RESPONSE)); - - // Execute - final Output result = api.getSwitchStatus(); - - // Assert - verify(method, times(1)).releaseConnection(); - assertEquals("Wrong URI for get SwitchStatus REST service", Constants.STATUS_URI, uri); - assertEquals("Wrong HTTP method for get SwitchStatus REST service", "post", type); - assertEquals("Wrong state for get SwitchStatus REST service", "Online", result.getVcsNodes().getVcsNodeInfo().get(0).getNodeState()); - } - - @Test - public void testCreateNetwork() throws BrocadeVcsApiException, IOException { - // Prepare - - method = mock(HttpPatch.class); - - response = mock(HttpResponse.class); - final StatusLine statusLine = mock(StatusLine.class); - when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(response.getStatusLine()).thenReturn(statusLine); - - // Execute - api.createNetwork(VLAN_ID, NETWORK_ID); - - // Assert - verify(method, times(6)).releaseConnection(); - assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri); - assertEquals("Wrong HTTP method for Network creation REST service", "patch", type); - } - - @Test - public void testDeleteNetwork() throws BrocadeVcsApiException, IOException { - // Prepare - - method = mock(HttpPatch.class); - - response = mock(HttpResponse.class); - final StatusLine statusLine = mock(StatusLine.class); - when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(response.getStatusLine()).thenReturn(statusLine); - - // Execute - api.deleteNetwork(VLAN_ID, NETWORK_ID); - - // Assert - verify(method, times(3)).releaseConnection(); - assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri); - assertEquals("Wrong HTTP method for Network creation REST service", "patch", type); - } - - @Test - public void testAssociateMacToNetwork() throws BrocadeVcsApiException, IOException { - // Prepare - - method = mock(HttpPatch.class); - - response = mock(HttpResponse.class); - final StatusLine statusLine = mock(StatusLine.class); - when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(response.getStatusLine()).thenReturn(statusLine); - - // Execute - api.associateMacToNetwork(NETWORK_ID, MAC_ADDRESS_32); - - // Assert - verify(method, times(1)).releaseConnection(); - assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri); - assertEquals("Wrong HTTP method for Network creation REST service", "patch", type); - } - - @Test - public void testDisassociateMacFromNetwork() throws BrocadeVcsApiException, IOException { - // Prepare - - method = mock(HttpPatch.class); - - response = mock(HttpResponse.class); - final StatusLine statusLine = mock(StatusLine.class); - when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(response.getStatusLine()).thenReturn(statusLine); - - // Execute - api.disassociateMacFromNetwork(NETWORK_ID, MAC_ADDRESS_32); - - // Assert - verify(method, times(1)).releaseConnection(); - assertEquals("Wrong URI for Network creation REST service", Constants.URI, uri); - assertEquals("Wrong HTTP method for Network creation REST service", "patch", type); - } - -} diff --git a/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuruTest.java b/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuruTest.java deleted file mode 100644 index 3f5a047b9115..000000000000 --- a/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/guru/BrocadeVcsGuestNetworkGuruTest.java +++ /dev/null @@ -1,593 +0,0 @@ -// -// 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.network.guru; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.AssociateMacToNetworkAnswer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreateNetworkAnswer; -import com.cloud.agent.api.DeleteNetworkAnswer; -import com.cloud.agent.api.DisassociateMacFromNetworkAnswer; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.domain.Domain; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.BrocadeVcsDeviceVO; -import com.cloud.network.BrocadeVcsNetworkVlanMappingVO; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Service; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.BrocadeVcsDao; -import com.cloud.network.dao.BrocadeVcsNetworkVlanMappingDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; -import com.cloud.user.Account; -import com.cloud.vm.Nic.ReservationStrategy; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -public class BrocadeVcsGuestNetworkGuruTest { - private static final long NETWORK_ID = 42L; - PhysicalNetworkDao physnetdao = mock(PhysicalNetworkDao.class); - BrocadeVcsDao vcsdao = mock(BrocadeVcsDao.class); - BrocadeVcsNetworkVlanMappingDao vcsmapdao = mock(BrocadeVcsNetworkVlanMappingDao.class); - DataCenterDao dcdao = mock(DataCenterDao.class); - NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class); - AgentManager agentmgr = mock(AgentManager.class); - NetworkOrchestrationService netmgr = mock(NetworkOrchestrationService.class); - NetworkModel netmodel = mock(NetworkModel.class); - - HostDao hostdao = mock(HostDao.class); - NetworkDao netdao = mock(NetworkDao.class); - GuestNetworkGuru guestGuru = mock(GuestNetworkGuru.class); - BrocadeVcsGuestNetworkGuru guru; - - @Before - public void setUp() { - - guru = new BrocadeVcsGuestNetworkGuru(); - ((GuestNetworkGuru)guru)._physicalNetworkDao = physnetdao; - guru._brocadeVcsDao = vcsdao; - guru._brocadeVcsNetworkVlanDao = vcsmapdao; - guru._hostDao = hostdao; - guru._ntwkOfferingSrvcDao = nosd; - guru._dcDao = dcdao; - guru._agentMgr = agentmgr; - ((GuestNetworkGuru)guru)._networkModel = netmodel; - - final DataCenterVO dc = mock(DataCenterVO.class); - when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); - when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); - - when(dcdao.findById((Long)any())).thenReturn(dc); - } - - @Test - public void testCanHandle() { - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VCS"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); - - assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported TrafficType != Guest - when(offering.getTrafficType()).thenReturn(TrafficType.Management); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported: GuestType Shared - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Shared); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported: Basic networking - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true); - - // Not supported: IsolationMethod != VCS - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - } - - @Test - public void testDesign() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VCS"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); - - when(netmodel.listNetworkOfferingServices(NETWORK_ID)).thenReturn(Arrays.asList(Service.Connectivity)); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork != null); - assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Vcs); - } - - @Test - public void testDesignNoIsolationMethodVCS() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork == null); - } - - @Test - public void testDesignNoConnectivityInOffering() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VCS"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork == null); - } - - @Test - public void testImplement() throws InsufficientVirtualNetworkCapacityException, URISyntaxException { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VCS"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); - - mock(DeploymentPlan.class); - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getBroadcastUri()).thenReturn(new URI("vlan://14")); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - List devices = new ArrayList(); - devices.add(brocadeDevice); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - when(guestGuru.implement(network, offering, dest, res)).thenReturn(network); - - final CreateNetworkAnswer answer = mock(CreateNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - final Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork != null); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testImplementFail() throws InsufficientVirtualNetworkCapacityException, URISyntaxException { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VCS"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - mock(DeploymentPlan.class); - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getBroadcastUri()).thenReturn(new URI("vlan://14")); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - final List devices = mock(List.class); - when(devices.isEmpty()).thenReturn(true); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - when(guestGuru.implement(network, offering, dest, res)).thenReturn(network); - - final CreateNetworkAnswer answer = mock(CreateNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - final Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork == null); - verify(agentmgr, times(0)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testReserve() throws InsufficientVirtualNetworkCapacityException, URISyntaxException, InsufficientAddressCapacityException { - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getBroadcastUri()).thenReturn(new URI("vlan://14")); - when(network.getDataCenterId()).thenReturn(NETWORK_ID); - - final NicProfile nic = mock(NicProfile.class); - when(nic.getMacAddress()).thenReturn("macaddress"); - when(nic.getReservationStrategy()).thenReturn(ReservationStrategy.Start); - - final VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenterVO dc = mock(DataCenterVO.class); - when(dest.getDataCenter()).thenReturn(dc); - when(dcdao.findById((long)anyInt())).thenReturn(dc); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - List devices = new ArrayList(); - devices.add(brocadeDevice); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - final AssociateMacToNetworkAnswer answer = mock(AssociateMacToNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - guru.reserve(nic, network, vmProfile, dest, res); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testReserveFail() throws InsufficientVirtualNetworkCapacityException, URISyntaxException, InsufficientAddressCapacityException { - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getBroadcastUri()).thenReturn(new URI("vlan://14")); - when(network.getDataCenterId()).thenReturn(NETWORK_ID); - - final NicProfile nic = mock(NicProfile.class); - when(nic.getMacAddress()).thenReturn("macaddress"); - when(nic.getReservationStrategy()).thenReturn(ReservationStrategy.Start); - - final VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenterVO dc = mock(DataCenterVO.class); - when(dest.getDataCenter()).thenReturn(dc); - when(dcdao.findById((long)anyInt())).thenReturn(dc); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - final List devices = mock(List.class); - when(devices.isEmpty()).thenReturn(true); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - final AssociateMacToNetworkAnswer answer = mock(AssociateMacToNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - guru.reserve(nic, network, vmProfile, dest, res); - verify(agentmgr, times(0)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testDeallocate() { - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getDataCenterId()).thenReturn(NETWORK_ID); - - final NicProfile nic = mock(NicProfile.class); - when(nic.getMacAddress()).thenReturn("macaddress"); - when(nic.getReservationStrategy()).thenReturn(ReservationStrategy.Start); - - final VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - final List devices = new ArrayList(); - devices.add(brocadeDevice); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final DisassociateMacFromNetworkAnswer answer = mock(DisassociateMacFromNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - guru.deallocate(network, nic, vmProfile); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testDeallocateFail() { - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getDataCenterId()).thenReturn(NETWORK_ID); - - final NicProfile nic = mock(NicProfile.class); - when(nic.getMacAddress()).thenReturn("macaddress"); - when(nic.getReservationStrategy()).thenReturn(ReservationStrategy.Start); - - final VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - final List devices = mock(List.class); - when(devices.isEmpty()).thenReturn(true); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final DisassociateMacFromNetworkAnswer answer = mock(DisassociateMacFromNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - guru.deallocate(network, nic, vmProfile); - verify(agentmgr, times(0)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testTrash() { - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getDataCenterId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsNetworkVlanMappingVO mapping = mock(BrocadeVcsNetworkVlanMappingVO.class); - when(mapping.getVlanId()).thenReturn(14); - when(vcsmapdao.findByNetworkId(anyLong())).thenReturn(mapping); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - final List devices = new ArrayList(); - devices.add(brocadeDevice); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final DeleteNetworkAnswer answer = mock(DeleteNetworkAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - when(vcsdao.remove((long)anyInt())).thenReturn(true); - - final boolean result = guru.trash(network, offering); - assertTrue(result == true); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testTrashFail() { - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getDataCenterId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final HostVO brocadeHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(brocadeHost); - when(brocadeHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - - final BrocadeVcsNetworkVlanMappingVO mapping = mock(BrocadeVcsNetworkVlanMappingVO.class); - when(mapping.getVlanId()).thenReturn(14); - when(vcsmapdao.findByNetworkId(anyLong())).thenReturn(mapping); - when(vcsmapdao.remove(anyLong())).thenReturn(true); - - final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class); - when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID); - - final List devices = mock(List.class); - when(devices.isEmpty()).thenReturn(true); - when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices); - - final boolean result = guru.trash(network, offering); - assertTrue(result == false); - verify(agentmgr, times(0)).easySend(eq(NETWORK_ID), (Command)any()); - } -} diff --git a/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/resource/BrocadeVcsResourceTest.java b/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/resource/BrocadeVcsResourceTest.java deleted file mode 100644 index f903d0e1c170..000000000000 --- a/plugins/network-elements/brocade-vcs/src/test/java/com/cloud/network/resource/BrocadeVcsResourceTest.java +++ /dev/null @@ -1,261 +0,0 @@ -// -// 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.network.resource; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.junit.Before; -import org.junit.Test; - -import com.cloud.agent.api.AssociateMacToNetworkAnswer; -import com.cloud.agent.api.AssociateMacToNetworkCommand; -import com.cloud.agent.api.CreateNetworkAnswer; -import com.cloud.agent.api.CreateNetworkCommand; -import com.cloud.agent.api.DeleteNetworkAnswer; -import com.cloud.agent.api.DeleteNetworkCommand; -import com.cloud.agent.api.DisassociateMacFromNetworkAnswer; -import com.cloud.agent.api.DisassociateMacFromNetworkCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.host.Host; -import com.cloud.network.brocade.BrocadeVcsApi; -import com.cloud.network.brocade.BrocadeVcsApiException; -import com.cloud.network.schema.showvcs.Output; -import com.cloud.network.schema.showvcs.VcsNodeInfo; -import com.cloud.network.schema.showvcs.VcsNodes; - -public class BrocadeVcsResourceTest { - - private static final long NETWORK_ID = 42L; - private static final int VLAN_ID = 14; - private static final String MAC_ADDRESS_32 = "0050.56bf.0002"; - private static final String MAC_ADDRESS_64 = "00:50:56:bf:00:02"; - BrocadeVcsApi api = mock(BrocadeVcsApi.class); - BrocadeVcsResource resource; - Map parameters; - - @Before - public void setUp() throws ConfigurationException { - resource = new BrocadeVcsResource() { - @Override - protected BrocadeVcsApi createBrocadeVcsApi(String ip, String username, String password) { - return api; - } - }; - - parameters = new HashMap(); - parameters.put("name", "vcstestdevice"); - parameters.put("ip", "127.0.0.1"); - parameters.put("adminuser", "adminuser"); - parameters.put("guid", "aaaaa-bbbbb-ccccc"); - parameters.put("zoneId", "blublub"); - parameters.put("adminpass", "adminpass"); - } - - @Test(expected = ConfigurationException.class) - public void resourceConfigureFailure() throws ConfigurationException { - resource.configure("BrocadeVcsResource", Collections. emptyMap()); - } - - @Test - public void resourceConfigure() throws ConfigurationException { - resource.configure("BrocadeVcsResource", parameters); - assertTrue("Incorrect resource name", "vcstestdevice".equals(resource.getName())); - - assertTrue("Incorrect resource type", resource.getType() == Host.Type.L2Networking); - } - - @Test - public void testInitialization() throws ConfigurationException { - resource.configure("BrocadeVcsResource", parameters); - - final StartupCommand[] sc = resource.initialize(); - assertTrue(sc.length == 1); - assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); - assertTrue("Incorrect Brocade device name", "vcstestdevice".equals(sc[0].getName())); - assertTrue("Incorrect Data Center", "blublub".equals(sc[0].getDataCenter())); - } - - @Test - public void testPingCommandStatusOk() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - final VcsNodeInfo nodeInfo = mock(VcsNodeInfo.class); - when(nodeInfo.getNodeState()).thenReturn("Online"); - - List nodes = new ArrayList(); - nodes.add(nodeInfo); - - final VcsNodes vcsNodes = mock(VcsNodes.class); - final Output output = mock(Output.class); - when(output.getVcsNodes()).thenReturn(vcsNodes); - when(vcsNodes.getVcsNodeInfo()).thenReturn(nodes); - when(api.getSwitchStatus()).thenReturn(output); - - final PingCommand ping = resource.getCurrentStatus(42); - assertTrue(ping != null); - assertTrue(ping.getHostId() == 42); - assertTrue(ping.getHostType() == Host.Type.L2Networking); - - } - - @Test - public void testPingCommandStatusFail() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - final VcsNodeInfo nodeInfo = mock(VcsNodeInfo.class); - when(nodeInfo.getNodeState()).thenReturn("Offline"); - - List nodes = new ArrayList(); - nodes.add(nodeInfo); - - final VcsNodes vcsNodes = mock(VcsNodes.class); - final Output output = mock(Output.class); - when(output.getVcsNodes()).thenReturn(vcsNodes); - when(vcsNodes.getVcsNodeInfo()).thenReturn(nodes); - when(api.getSwitchStatus()).thenReturn(output); - - final PingCommand ping = resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testPingCommandStatusApiException() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - when(api.getSwitchStatus()).thenThrow(new BrocadeVcsApiException()); - - final PingCommand ping = resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testRetries() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.createNetwork(VLAN_ID, NETWORK_ID)).thenThrow(new BrocadeVcsApiException()).thenThrow(new BrocadeVcsApiException()).thenReturn(true); - - final CreateNetworkCommand cmd = new CreateNetworkCommand(VLAN_ID, NETWORK_ID, "owner"); - final CreateNetworkAnswer answer = (CreateNetworkAnswer)resource.executeRequest(cmd); - assertTrue(answer.getResult()); - - } - - @Test - public void testCreateNetworkApi() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.createNetwork(VLAN_ID, NETWORK_ID)).thenReturn(true); - - final CreateNetworkCommand cmd = new CreateNetworkCommand(VLAN_ID, NETWORK_ID, "owner"); - final CreateNetworkAnswer answer = (CreateNetworkAnswer)resource.executeRequest(cmd); - //verify(api).createNetwork(VLAN_ID, NETWORK_ID); - assertTrue(answer.getResult()); - - } - - @Test - public void testCreateNetworkApiException() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.createNetwork(VLAN_ID, NETWORK_ID)).thenThrow(new BrocadeVcsApiException()); - - final CreateNetworkCommand cmd = new CreateNetworkCommand(VLAN_ID, NETWORK_ID, "owner"); - final CreateNetworkAnswer answer = (CreateNetworkAnswer)resource.executeRequest(cmd); - assertFalse(answer.getResult()); - - } - - @Test - public void testDeleteNetworkApi() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.deleteNetwork(VLAN_ID, NETWORK_ID)).thenReturn(true); - - final DeleteNetworkCommand cmd = new DeleteNetworkCommand(VLAN_ID, NETWORK_ID); - final DeleteNetworkAnswer answer = (DeleteNetworkAnswer)resource.executeRequest(cmd); - assertTrue(answer.getResult()); - } - - @Test - public void testDeleteNetworkApiException() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.deleteNetwork(VLAN_ID, NETWORK_ID)).thenThrow(new BrocadeVcsApiException()); - - final DeleteNetworkCommand cmd = new DeleteNetworkCommand(VLAN_ID, NETWORK_ID); - final DeleteNetworkAnswer answer = (DeleteNetworkAnswer)resource.executeRequest(cmd); - assertFalse(answer.getResult()); - } - - @Test - public void testAssociateMacToNetworkApi() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.associateMacToNetwork(NETWORK_ID, MAC_ADDRESS_32)).thenReturn(true); - - final AssociateMacToNetworkCommand cmd = new AssociateMacToNetworkCommand(NETWORK_ID, MAC_ADDRESS_64, "owner"); - final AssociateMacToNetworkAnswer answer = (AssociateMacToNetworkAnswer)resource.executeRequest(cmd); - assertTrue(answer.getResult()); - } - - @Test - public void testAssociateMacToNetworkApiException() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.associateMacToNetwork(NETWORK_ID, MAC_ADDRESS_32)).thenThrow(new BrocadeVcsApiException()); - - final AssociateMacToNetworkCommand cmd = new AssociateMacToNetworkCommand(NETWORK_ID, MAC_ADDRESS_64, "owner"); - final AssociateMacToNetworkAnswer answer = (AssociateMacToNetworkAnswer)resource.executeRequest(cmd); - assertFalse(answer.getResult()); - } - - @Test - public void testDisassociateMacFromNetworkApi() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.disassociateMacFromNetwork(NETWORK_ID, MAC_ADDRESS_32)).thenReturn(true); - - final DisassociateMacFromNetworkCommand cmd = new DisassociateMacFromNetworkCommand(NETWORK_ID, MAC_ADDRESS_64); - final DisassociateMacFromNetworkAnswer answer = (DisassociateMacFromNetworkAnswer)resource.executeRequest(cmd); - assertTrue(answer.getResult()); - } - - @Test - public void testDisassociateMacFromNetworkApiException() throws ConfigurationException, BrocadeVcsApiException { - resource.configure("BrocadeVcsResource", parameters); - - when(api.disassociateMacFromNetwork(NETWORK_ID, MAC_ADDRESS_32)).thenThrow(new BrocadeVcsApiException()); - - final DisassociateMacFromNetworkCommand cmd = new DisassociateMacFromNetworkCommand(NETWORK_ID, MAC_ADDRESS_64); - final DisassociateMacFromNetworkAnswer answer = (DisassociateMacFromNetworkAnswer)resource.executeRequest(cmd); - assertFalse(answer.getResult()); - } -} diff --git a/plugins/network-elements/cisco-vnmc/pom.xml b/plugins/network-elements/cisco-vnmc/pom.xml deleted file mode 100644 index c183d03259ae..000000000000 --- a/plugins/network-elements/cisco-vnmc/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-cisco-vnmc - Apache CloudStack Plugin - Cisco VNMC - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - org.apache.cloudstack - cloud-plugin-hypervisor-vmware - ${project.version} - - - org.apache.cloudstack - cloud-vmware-base - ${project.version} - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/AssociateAsaWithLogicalEdgeFirewallCommand.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/AssociateAsaWithLogicalEdgeFirewallCommand.java deleted file mode 100644 index 4f86d4b8d13f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/AssociateAsaWithLogicalEdgeFirewallCommand.java +++ /dev/null @@ -1,53 +0,0 @@ -// 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.api; - -/** - * Associates an ASA 1000v appliance with logical edge firewall in VNMC - */ -public class AssociateAsaWithLogicalEdgeFirewallCommand extends Command { - private long _vlanId; - private String _asaMgmtIp; - - public AssociateAsaWithLogicalEdgeFirewallCommand(long vlanId, String asaMgmtIp) { - super(); - this._vlanId = vlanId; - this._asaMgmtIp = asaMgmtIp; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public long getVlanId() { - return _vlanId; - } - - public void setVlanId(long vlanId) { - this._vlanId = vlanId; - } - - public String getAsaMgmtIp() { - return _asaMgmtIp; - } - - public void setAsaMgmtIp(String asaMgmtIp) { - this._asaMgmtIp = asaMgmtIp; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CleanupLogicalEdgeFirewallCommand.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CleanupLogicalEdgeFirewallCommand.java deleted file mode 100644 index 421f5f307325..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CleanupLogicalEdgeFirewallCommand.java +++ /dev/null @@ -1,43 +0,0 @@ -// 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.api; - -/** - * Command for cleaning up logical edge firewall in VNMC - */ -public class CleanupLogicalEdgeFirewallCommand extends Command { - private long _vlanId; - - public CleanupLogicalEdgeFirewallCommand(long vlanId) { - super(); - this._vlanId = vlanId; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public long getVlanId() { - return _vlanId; - } - - public void setVlanId(long vlanId) { - this._vlanId = vlanId; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java deleted file mode 100644 index fba9942cda9d..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/ConfigureNexusVsmForAsaCommand.java +++ /dev/null @@ -1,97 +0,0 @@ -// 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.api; - -import com.cloud.agent.api.LogLevel.Log4jLevel; - -/** - * Command for configuring n1kv VSM for asa1kv device. It does the following in VSM: - * a. creating vservice node for asa1kv - * b. updating vlan of inside port profile associated with asa1kv - */ -public class ConfigureNexusVsmForAsaCommand extends Command { - private long _vlanId; - private String _ipAddress; - private String _vsmUsername; - @LogLevel(Log4jLevel.Off) - private String _vsmPassword; - private String _vsmIp; - private String _asaInPortProfile; - - public ConfigureNexusVsmForAsaCommand(long vlanId, String ipAddress, String vsmUsername, String vsmPassword, String vsmIp, String asaInPortProfile) { - super(); - this._vlanId = vlanId; - this._ipAddress = ipAddress; - this._vsmUsername = vsmUsername; - this._vsmPassword = vsmPassword; - this._vsmIp = vsmIp; - this._asaInPortProfile = asaInPortProfile; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public long getVlanId() { - return _vlanId; - } - - public void setVlanId(long vlanId) { - this._vlanId = vlanId; - } - - public String getIpAddress() { - return _ipAddress; - } - - public void setIpAddress(String ipAddress) { - this._ipAddress = ipAddress; - } - - public String getVsmUsername() { - return _vsmUsername; - } - - public void setVsmUsername(String vsmUsername) { - this._vsmUsername = vsmUsername; - } - - public String getVsmPassword() { - return _vsmPassword; - } - - public void setVsmPassword(String vsmPassword) { - this._vsmPassword = vsmPassword; - } - - public String getVsmIp() { - return _vsmIp; - } - - public void setVsmIp(String vsmIp) { - this._vsmIp = vsmIp; - } - - public String getAsaInPortProfile() { - return _asaInPortProfile; - } - - public void setAsaInPortProfile(String asaInPortProfile) { - this._asaInPortProfile = asaInPortProfile; - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java deleted file mode 100644 index 89e411bddaa3..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/agent/api/CreateLogicalEdgeFirewallCommand.java +++ /dev/null @@ -1,92 +0,0 @@ -// 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.api; - -import java.util.ArrayList; -import java.util.List; - -/** - * Command for creating a logical edge firewall in VNMC - */ -public class CreateLogicalEdgeFirewallCommand extends Command { - private long _vlanId; - private String _publicIp; - private String _internalIp; - private String _publicSubnet; - private String internalSubnet; - private List _publicGateways; - - public CreateLogicalEdgeFirewallCommand(long vlanId, String publicIp, String internalIp, String publicSubnet, String internalSubnet) { - super(); - this._vlanId = vlanId; - this._publicIp = publicIp; - this._internalIp = internalIp; - this._publicSubnet = publicSubnet; - this.setInternalSubnet(internalSubnet); - _publicGateways = new ArrayList(); - } - - @Override - public boolean executeInSequence() { - return false; - } - - public long getVlanId() { - return _vlanId; - } - - public void setVlanId(long vlanId) { - this._vlanId = vlanId; - } - - public String getPublicIp() { - return _publicIp; - } - - public void setPublicIp(String publicIp) { - this._publicIp = publicIp; - } - - public String getInternalIp() { - return _internalIp; - } - - public void setInternalIp(String internalIp) { - this._internalIp = internalIp; - } - - public String getPublicSubnet() { - return _publicSubnet; - } - - public void setPublicSubnet(String publicSubnet) { - this._publicSubnet = publicSubnet; - } - - public String getInternalSubnet() { - return internalSubnet; - } - - public void setInternalSubnet(String internalSubnet) { - this.internalSubnet = internalSubnet; - } - - public List getPublicGateways() { - return _publicGateways; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoAsa1000vResourceCmd.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoAsa1000vResourceCmd.java deleted file mode 100644 index 67a7381a82b8..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoAsa1000vResourceCmd.java +++ /dev/null @@ -1,125 +0,0 @@ -// 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.api.commands; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ClusterResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.CiscoAsa1000vResourceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.cisco.CiscoAsa1000vDevice; -import com.cloud.network.element.CiscoAsa1000vService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addCiscoAsa1000vResource", responseObject = CiscoAsa1000vResourceResponse.class, description = "Adds a Cisco Asa 1000v appliance", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddCiscoAsa1000vResourceCmd extends BaseCmd { - private static final String s_name = "addCiscoAsa1000vResource"; - @Inject - CiscoAsa1000vService _ciscoAsa1000vService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - required = true, - description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname or ip address of the Cisco ASA 1000v appliance.") - private String host; - - @Parameter(name = ApiConstants.ASA_INSIDE_PORT_PROFILE, - type = CommandType.STRING, - required = true, - description = "Nexus port profile associated with inside interface of ASA 1000v") - private String inPortProfile; - - @Parameter(name = ApiConstants.CLUSTER_ID, type = CommandType.UUID, entityType = ClusterResponse.class, required = true, description = "The Cluster ID") - private Long clusterId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getManagementIp() { - return host; - } - - public String getInPortProfile() { - return inPortProfile; - } - - public Long getClusterId() { - return clusterId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - CiscoAsa1000vDevice ciscoAsa1000v = _ciscoAsa1000vService.addCiscoAsa1000vResource(this); - if (ciscoAsa1000v != null) { - CiscoAsa1000vResourceResponse response = _ciscoAsa1000vService.createCiscoAsa1000vResourceResponse(ciscoAsa1000v); - response.setObjectName("CiscoAsa1000vResource"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Cisco ASA 1000v appliance due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoVnmcResourceCmd.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoVnmcResourceCmd.java deleted file mode 100644 index 9cc93d9e2394..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/AddCiscoVnmcResourceCmd.java +++ /dev/null @@ -1,121 +0,0 @@ -// 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.api.commands; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.CiscoVnmcResourceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.cisco.CiscoVnmcController; -import com.cloud.network.element.CiscoVnmcElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addCiscoVnmcResource", responseObject = CiscoVnmcResourceResponse.class, description = "Adds a Cisco Vnmc Controller", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddCiscoVnmcResourceCmd extends BaseCmd { - private static final String s_name = "addCiscoVnmcResource"; - @Inject - CiscoVnmcElementService _ciscoVnmcElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - required = true, - description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname or ip address of the Cisco VNMC Controller.") - private String host; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to access the Cisco VNMC Controller API") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to access the Cisco VNMC Controller API") - private String password; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getHost() { - return host; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - CiscoVnmcController CiscoVnmcResourceVO = _ciscoVnmcElementService.addCiscoVnmcResource(this); - if (CiscoVnmcResourceVO != null) { - CiscoVnmcResourceResponse response = _ciscoVnmcElementService.createCiscoVnmcResourceResponse(CiscoVnmcResourceVO); - response.setObjectName("CiscoVnmcResource"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Cisco VNMC controller due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoAsa1000vResourceCmd.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoAsa1000vResourceCmd.java deleted file mode 100644 index c0c8101ed80c..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoAsa1000vResourceCmd.java +++ /dev/null @@ -1,99 +0,0 @@ -// 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.api.commands; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.CiscoAsa1000vResourceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.element.CiscoAsa1000vService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteCiscoAsa1000vResource", responseObject = SuccessResponse.class, description = "Deletes a Cisco ASA 1000v appliance", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteCiscoAsa1000vResourceCmd extends BaseCmd { - private static final String s_name = "deleteCiscoAsa1000vResource"; - @Inject - CiscoAsa1000vService _ciscoAsa1000vService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.RESOURCE_ID, - type = CommandType.UUID, - required = true, - entityType = CiscoAsa1000vResourceResponse.class, - description = "Cisco ASA 1000v resource ID") - private Long ciscoAsa1000vResourceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getCiscoAsa1000vResourceId() { - return ciscoAsa1000vResourceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - boolean result = _ciscoAsa1000vService.deleteCiscoAsa1000vResource(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Cisco ASA 1000v appliance."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoVnmcResourceCmd.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoVnmcResourceCmd.java deleted file mode 100644 index 456b8cf40088..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/DeleteCiscoVnmcResourceCmd.java +++ /dev/null @@ -1,99 +0,0 @@ -// 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.api.commands; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.CiscoVnmcResourceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.element.CiscoVnmcElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteCiscoVnmcResource", responseObject = SuccessResponse.class, description = "Deletes a Cisco Vnmc controller", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteCiscoVnmcResourceCmd extends BaseCmd { - private static final String s_name = "deleteCiscoVnmcResource"; - @Inject - CiscoVnmcElementService _ciscoVnmcElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.RESOURCE_ID, - type = CommandType.UUID, - required = true, - entityType = CiscoVnmcResourceResponse.class, - description = "Cisco Vnmc resource ID") - private Long ciscoVnmcResourceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getCiscoVnmcResourceId() { - return ciscoVnmcResourceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - boolean result = _ciscoVnmcElementService.deleteCiscoVnmcResource(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Cisco Vnmc resource."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoAsa1000vResourcesCmd.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoAsa1000vResourcesCmd.java deleted file mode 100644 index 7049df6b02eb..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoAsa1000vResourcesCmd.java +++ /dev/null @@ -1,115 +0,0 @@ -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.CiscoAsa1000vResourceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.cisco.CiscoAsa1000vDevice; -import com.cloud.network.cisco.CiscoAsa1000vDeviceVO; -import com.cloud.network.element.CiscoAsa1000vService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listCiscoAsa1000vResources", responseObject = CiscoAsa1000vResourceResponse.class, description = "Lists Cisco ASA 1000v appliances", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListCiscoAsa1000vResourcesCmd extends BaseListCmd { - private static final String s_name = "listCiscoAsa1000vResources"; - @Inject - CiscoAsa1000vService _ciscoAsa1000vService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.RESOURCE_ID, type = CommandType.UUID, entityType = CiscoAsa1000vResourceResponse.class, description = "Cisco ASA 1000v resource ID") - private Long ciscoAsa1000vResourceId; - - @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, description = "Hostname or ip address of the Cisco ASA 1000v appliance.") - private String host; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getCiscoAsa1000vResourceId() { - return ciscoAsa1000vResourceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getManagementIp() { - return host; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List ciscoAsa1000vDevices = _ciscoAsa1000vService.listCiscoAsa1000vResources(this); - ListResponse response = new ListResponse(); - List ciscoAsa1000vResourcesResponse = new ArrayList(); - - if (ciscoAsa1000vDevices != null && !ciscoAsa1000vDevices.isEmpty()) { - for (CiscoAsa1000vDevice ciscoAsa1000vDeviceVO : ciscoAsa1000vDevices) { - CiscoAsa1000vResourceResponse ciscoAsa1000vResourceResponse = _ciscoAsa1000vService.createCiscoAsa1000vResourceResponse(ciscoAsa1000vDeviceVO); - ciscoAsa1000vResourceResponse.setObjectName("CiscoAsa1000vResource"); - ciscoAsa1000vResourcesResponse.add(ciscoAsa1000vResourceResponse); - } - } - - response.setResponses(ciscoAsa1000vResourcesResponse); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoVnmcResourcesCmd.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoVnmcResourcesCmd.java deleted file mode 100644 index f5beba911726..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/commands/ListCiscoVnmcResourcesCmd.java +++ /dev/null @@ -1,109 +0,0 @@ -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.CiscoVnmcResourceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.cisco.CiscoVnmcController; -import com.cloud.network.cisco.CiscoVnmcControllerVO; -import com.cloud.network.element.CiscoVnmcElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listCiscoVnmcResources", responseObject = CiscoVnmcResourceResponse.class, description = "Lists Cisco VNMC controllers", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListCiscoVnmcResourcesCmd extends BaseListCmd { - private static final String s_name = "listCiscoVnmcResources"; - @Inject - CiscoVnmcElementService _ciscoVnmcElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.RESOURCE_ID, type = CommandType.UUID, entityType = CiscoVnmcResourceResponse.class, description = "Cisco VNMC resource ID") - private Long ciscoVnmcResourceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getCiscoVnmcResourceId() { - return ciscoVnmcResourceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List ciscoVnmcResources = _ciscoVnmcElementService.listCiscoVnmcResources(this); - ListResponse response = new ListResponse(); - List ciscoVnmcResourcesResponse = new ArrayList(); - - if (ciscoVnmcResources != null && !ciscoVnmcResources.isEmpty()) { - for (CiscoVnmcController ciscoVnmcResourceVO : ciscoVnmcResources) { - CiscoVnmcResourceResponse ciscoVnmcResourceResponse = _ciscoVnmcElementService.createCiscoVnmcResourceResponse(ciscoVnmcResourceVO); - ciscoVnmcResourceResponse.setObjectName("CiscoVnmcResource"); - ciscoVnmcResourcesResponse.add(ciscoVnmcResourceResponse); - } - } - - response.setResponses(ciscoVnmcResourcesResponse); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoAsa1000vResourceResponse.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoAsa1000vResourceResponse.java deleted file mode 100644 index 33c46582d7d1..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoAsa1000vResourceResponse.java +++ /dev/null @@ -1,97 +0,0 @@ -// 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.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.NetworkResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.network.cisco.CiscoAsa1000vDevice; - -@EntityReference(value = CiscoAsa1000vDevice.class) -public class CiscoAsa1000vResourceResponse extends BaseResponse { - - @SerializedName(ApiConstants.RESOURCE_ID) - @Parameter(description = "Resource ID of the Cisco ASA 1000v appliance") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Parameter(description = "The physical Network to which this ASA 1000v belongs to", entityType = PhysicalNetworkResponse.class) - private Long physicalNetworkId; - - @SerializedName(ApiConstants.HOST_NAME) - @Parameter(description = "Management IP address of ASA 1000v") - private String managementIp; - - @SerializedName(ApiConstants.ASA_INSIDE_PORT_PROFILE) - @Parameter(description = "Port profile associated with inside interface of ASA 1000v") - private String inPortProfile; - - @SerializedName(ApiConstants.NETWORK_ID) - @Parameter(description = "The guest network to which ASA 1000v is associated", entityType = NetworkResponse.class) - private Long guestNetworkId; - - public String getId() { - return id; - } - - public void setId(String ciscoAsa1000vResourceId) { - this.id = ciscoAsa1000vResourceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public void setPhysicalNetworkId(Long physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public String getManagementIp() { - return managementIp; - } - - public void setManagementIp(String managementIp) { - this.managementIp = managementIp; - } - - public String getInPortProfile() { - return inPortProfile; - } - - public void setInPortProfile(String inPortProfile) { - this.inPortProfile = inPortProfile; - } - - public Long getGuestNetworkId() { - return guestNetworkId; - } - - public void setGuestNetworkId(Long guestNetworkId) { - this.guestNetworkId = guestNetworkId; - } - - @Override - public String getObjectId() { - return this.getId(); - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoVnmcResourceResponse.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoVnmcResourceResponse.java deleted file mode 100644 index 9944e9f34155..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/api/response/CiscoVnmcResourceResponse.java +++ /dev/null @@ -1,85 +0,0 @@ -// 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.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.network.cisco.CiscoVnmcController; - -@EntityReference(value = CiscoVnmcController.class) -public class CiscoVnmcResourceResponse extends BaseResponse { - public static final String RESOURCE_NAME = "resourcename"; - - @SerializedName(ApiConstants.RESOURCE_ID) - @Parameter(description = "Resource ID of the Cisco VNMC controller") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Parameter(description = "The physical network to which this VNMC belongs to", entityType = PhysicalNetworkResponse.class) - private Long physicalNetworkId; - - @SerializedName(ApiConstants.PROVIDER) - @Parameter(description = "Name of the provider") - private String providerName; - - @SerializedName(RESOURCE_NAME) - @Parameter(description = "Cisco VNMC resource name") - private String resourceName; - - public String getId() { - return id; - } - - public void setId(String ciscoVnmcResourceId) { - this.id = ciscoVnmcResourceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public void setPhysicalNetworkId(Long physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public String getProviderName() { - return providerName; - } - - public void setProviderName(String providerName) { - this.providerName = providerName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - @Override - public String getObjectId() { - return this.getId(); - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDevice.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDevice.java deleted file mode 100644 index fc3de52a7514..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDevice.java +++ /dev/null @@ -1,41 +0,0 @@ -// 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.network.cisco; - -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - -import com.cloud.org.Grouping; - -public interface CiscoAsa1000vDevice extends Grouping, InternalIdentity, Identity { - - @Override - long getId(); - - @Override - String getUuid(); - - void setUuid(String uuid); - - long getPhysicalNetworkId(); - - String getManagementIp(); - - String getInPortProfile(); - - long getClusterId(); -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDeviceVO.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDeviceVO.java deleted file mode 100644 index 323c874d5c91..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoAsa1000vDeviceVO.java +++ /dev/null @@ -1,100 +0,0 @@ -// 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.network.cisco; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "external_cisco_asa1000v_devices") -public class CiscoAsa1000vDeviceVO implements CiscoAsa1000vDevice { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "physical_network_id") - private long physicalNetworkId; - - @Column(name = "management_ip") - private String managementIp; - - @Column(name = "in_Port_profile") - private String inPortProfile; - - @Column(name = "cluster_id") - private long clusterId; - - public CiscoAsa1000vDeviceVO() { - this.uuid = UUID.randomUUID().toString(); - } - - public CiscoAsa1000vDeviceVO(long physicalNetworkId, String managementIp, String inPortProfile, long clusterId) { - super(); - this.physicalNetworkId = physicalNetworkId; - this.managementIp = managementIp; - this.inPortProfile = inPortProfile; - this.uuid = UUID.randomUUID().toString(); - this.clusterId = clusterId; - } - - @Override - public long getId() { - return id; - } - - @Override - public String getUuid() { - return uuid; - } - - @Override - public void setUuid(String uuid) { - this.uuid = uuid; - } - - @Override - public long getPhysicalNetworkId() { - return physicalNetworkId; - } - - @Override - public String getManagementIp() { - return managementIp; - } - - @Override - public String getInPortProfile() { - return inPortProfile; - } - - @Override - public long getClusterId() { - return clusterId; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnection.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnection.java deleted file mode 100644 index ade85c36818f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnection.java +++ /dev/null @@ -1,133 +0,0 @@ -// 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.network.cisco; - -import java.util.Map; - -import com.cloud.utils.exception.ExecutionException; - -public interface CiscoVnmcConnection { - - public boolean createTenant(String tenantName) throws ExecutionException; - - public boolean deleteTenant(String tenantName) throws ExecutionException; - - public boolean createTenantVDC(String tenantName) throws ExecutionException; - - public boolean deleteTenantVDC(String tenantName) throws ExecutionException; - - public boolean createTenantVDCEdgeDeviceProfile(String tenantName) throws ExecutionException; - - public boolean createTenantVDCEdgeStaticRoutePolicy(String tenantName) throws ExecutionException; - - public boolean createTenantVDCEdgeStaticRoute(String tenantName, String nextHopIp, String destination, String netmask) throws ExecutionException; - - public boolean associateTenantVDCEdgeStaticRoutePolicy(String tenantName) throws ExecutionException; - - public boolean associateTenantVDCEdgeDhcpPolicy(String tenantName, String intfName) throws ExecutionException; - - public boolean createTenantVDCEdgeDhcpPolicy(String tenantName, String startIp, String endIp, String subnet, String nameServerIp, String domain) - throws ExecutionException; - - public boolean associateTenantVDCEdgeDhcpServerPolicy(String tenantName, String intfName) throws ExecutionException; - - public boolean createTenantVDCEdgeSecurityProfile(String tenantName) throws ExecutionException; - - public boolean deleteTenantVDCEdgeSecurityProfile(String tenantName) throws ExecutionException; - - public boolean createTenantVDCSourceNatIpPool(String tenantName, String identifier, String publicIp) throws ExecutionException; - - public boolean createTenantVDCSourceNatRule(String tenantName, String identifier, String startSourceIp, String endSourceIp) throws ExecutionException; - - public boolean createTenantVDCSourceNatPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCSourceNatPolicyRef(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCDNatIpPool(String tenantName, String identifier, String ipAddress) throws ExecutionException; - - public boolean createTenantVDCDNatRule(String tenantName, long ruleId, String policyIdentifier, String publicIp) throws ExecutionException; - - public boolean deleteTenantVDCDNatRule(String tenantName, long ruleId, String policyIdentifier) throws ExecutionException; - - public boolean createTenantVDCAclRuleForDNat(String tenantName, long ruleId, String policyIdentifier, String ipAddress) throws ExecutionException; - - public boolean createTenantVDCDNatPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean deleteTenantVDCDNatPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCDNatPolicyRef(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCPFPortPool(String tenantName, String identifier, String startPort, String endPort) throws ExecutionException; - - public boolean createTenantVDCPFIpPool(String tenantName, String identifier, String ipAddress) throws ExecutionException; - - public boolean createTenantVDCPFRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String publicIp, String startPort, String endPort) - throws ExecutionException; - - public boolean deleteTenantVDCPFRule(String tenantName, long ruleId, String policyIdentifier) throws ExecutionException; - - public boolean createTenantVDCAclRuleForPF(String tenantName, long ruleId, String policyIdentifier, String protocol, String ipAddress, String startPort, - String endPort) throws ExecutionException; - - public boolean createTenantVDCPFPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean deleteTenantVDCPFPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCPFPolicyRef(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCNatPolicySet(String tenantName) throws ExecutionException; - - public boolean deleteTenantVDCNatPolicySet(String tenantName) throws ExecutionException; - - public boolean associateNatPolicySet(String tenantName) throws ExecutionException; - - public boolean createTenantVDCIngressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp, - String destStartPort, String destEndPort) throws ExecutionException; - - public boolean createTenantVDCIngressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp) - throws ExecutionException; - - public boolean createTenantVDCEgressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp, - String destStartPort, String destEndPort) throws ExecutionException; - - public boolean createTenantVDCEgressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp) - throws ExecutionException; - - public boolean deleteTenantVDCAclRule(String tenantName, long ruleId, String policyIdentifier) throws ExecutionException; - - public boolean createTenantVDCAclPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCAclPolicyRef(String tenantName, String identifier, boolean ingress) throws ExecutionException; - - public boolean deleteTenantVDCAclPolicy(String tenantName, String identifier) throws ExecutionException; - - public boolean createTenantVDCAclPolicySet(String tenantName, boolean ingress) throws ExecutionException; - - public boolean deleteTenantVDCAclPolicySet(String tenantName, boolean ingress) throws ExecutionException; - - public boolean associateAclPolicySet(String tenantName) throws ExecutionException; - - public boolean createEdgeFirewall(String tenantName, String publicIp, String insideIp, String publicSubnet, String insideSubnet) throws ExecutionException; - - public boolean deleteEdgeFirewall(String tenantName) throws ExecutionException; - - public Map listUnAssocAsa1000v() throws ExecutionException; - - public boolean assignAsa1000v(String tenantName, String firewallDn) throws ExecutionException; - - public boolean unassignAsa1000v(String tenantName, String firewallDn) throws ExecutionException; -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java deleted file mode 100644 index e0ab727930e8..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcConnectionImpl.java +++ /dev/null @@ -1,1330 +0,0 @@ -// 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.network.cisco; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.cloudstack.utils.security.ParserUtils; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -import com.cloud.utils.exception.ExecutionException; -import com.cloud.utils.script.Script; - -public class CiscoVnmcConnectionImpl implements CiscoVnmcConnection { - - private final String _ip; - private final String _username; - private final String _password; - private String _cookie; - - protected static Logger LOGGER = LogManager.getLogger(CiscoVnmcConnectionImpl.class); - - private enum VnmcXml { - LOGIN("login.xml", "mgmt-controller"), - - CREATE_TENANT("create-tenant.xml", "service-reg"), - DELETE_TENANT("delete-tenant.xml", "service-reg"), - CREATE_VDC("create-vdc.xml", "service-reg"), - DELETE_VDC("delete-vdc.xml", "service-reg"), - - CREATE_EDGE_DEVICE_PROFILE("create-edge-device-profile.xml", "policy-mgr"), - CREATE_EDGE_ROUTE_POLICY("create-edge-device-route-policy.xml", "policy-mgr"), - CREATE_EDGE_ROUTE("create-edge-device-route.xml", "policy-mgr"), - RESOLVE_EDGE_ROUTE_POLICY("associate-route-policy.xml", "policy-mgr"), - - CREATE_DHCP_POLICY("create-dhcp-policy.xml", "policy-mgr"), - RESOLVE_EDGE_DHCP_POLICY("associate-dhcp-policy.xml", "policy-mgr"), - RESOLVE_EDGE_DHCP_SERVER_POLICY("associate-dhcp-server.xml", "policy-mgr"), - - CREATE_EDGE_SECURITY_PROFILE("create-edge-security-profile.xml", "policy-mgr"), - DELETE_EDGE_SECURITY_PROFILE("delete-edge-security-profile.xml", "policy-mgr"), - - CREATE_NAT_POLICY_SET("create-nat-policy-set.xml", "policy-mgr"), - DELETE_NAT_POLICY_SET("delete-nat-policy-set.xml", "policy-mgr"), - RESOLVE_NAT_POLICY_SET("associate-nat-policy-set.xml", "policy-mgr"), - CREATE_NAT_POLICY("create-nat-policy.xml", "policy-mgr"), - DELETE_NAT_POLICY("delete-nat-policy.xml", "policy-mgr"), - LIST_NAT_POLICIES("list-nat-policies.xml", "policy-mgr"), - CREATE_NAT_POLICY_REF("create-nat-policy-ref.xml", "policy-mgr"), - CREATE_PORT_POOL("create-port-pool.xml", "policy-mgr"), - CREATE_IP_POOL("create-ip-pool.xml", "policy-mgr"), - - CREATE_PF_RULE("create-pf-rule.xml", "policy-mgr"), - CREATE_ACL_RULE_FOR_PF("create-acl-rule-for-pf.xml", "policy-mgr"), - CREATE_DNAT_RULE("create-dnat-rule.xml", "policy-mgr"), - CREATE_ACL_RULE_FOR_DNAT("create-acl-rule-for-dnat.xml", "policy-mgr"), - CREATE_SOURCE_NAT_RULE("create-source-nat-rule.xml", "policy-mgr"), - - CREATE_ACL_POLICY_SET("create-acl-policy-set.xml", "policy-mgr"), - DELETE_ACL_POLICY_SET("delete-acl-policy-set.xml", "policy-mgr"), - RESOLVE_ACL_POLICY_SET("associate-acl-policy-set.xml", "policy-mgr"), - CREATE_ACL_POLICY("create-acl-policy.xml", "policy-mgr"), - DELETE_ACL_POLICY("delete-acl-policy.xml", "policy-mgr"), - LIST_ACL_POLICIES("list-acl-policies.xml", "policy-mgr"), - CREATE_ACL_POLICY_REF("create-acl-policy-ref.xml", "policy-mgr"), - CREATE_INGRESS_ACL_RULE("create-ingress-acl-rule.xml", "policy-mgr"), - CREATE_EGRESS_ACL_RULE("create-egress-acl-rule.xml", "policy-mgr"), - CREATE_GENERIC_INGRESS_ACL_RULE("create-generic-ingress-acl-rule.xml", "policy-mgr"), - CREATE_GENERIC_EGRESS_ACL_RULE("create-generic-egress-acl-rule.xml", "policy-mgr"), - CREATE_GENERIC_EGRESS_ACL_NO_PROTOCOL_RULE("create-generic-egress-acl-no-protocol-rule.xml", "policy-mgr"), - - DELETE_RULE("delete-rule.xml", "policy-mgr"), - - LIST_CHILDREN("list-children.xml", "policy-mgr"), - - CREATE_EDGE_FIREWALL("create-edge-firewall.xml", "resource-mgr"), - DELETE_EDGE_FIREWALL("delete-edge-firewall.xml", "resource-mgr"), - - LIST_UNASSOC_ASA1000V("list-unassigned-asa1000v.xml", "resource-mgr"), - ASSIGN_ASA1000V("assoc-asa1000v.xml", "resource-mgr"), - UNASSIGN_ASA1000V("disassoc-asa1000v.xml", "resource-mgr"); - - private final String scriptsDir = "scripts/network/cisco"; - private String xml; - private String service; - - private VnmcXml(String filename, String service) { - xml = getXml(filename); - this.service = service; - } - - public String getXml() { - return xml; - } - - private String getXml(String filename) { - try { - String xmlFilePath = Script.findScript(scriptsDir, filename); - - if (xmlFilePath == null) { - throw new Exception("Failed to find Cisco VNMC XML file: " + filename); - } - - InputStreamReader fr = new InputStreamReader(new FileInputStream(xmlFilePath),"UTF-8"); - BufferedReader br = new BufferedReader(fr); - - String xml = ""; - String line; - while ((line = br.readLine()) != null) { - xml += line; - } - - return xml; - } catch (Exception e) { - LOGGER.debug(e); - return null; - } - } - - public String getService() { - return service; - } - } - - public CiscoVnmcConnectionImpl(String hostIp, String userName, String password) { - _ip = hostIp; - _username = userName; - _password = password; - - } - - public boolean login() throws ExecutionException { - String xml = VnmcXml.LOGIN.getXml(); - String service = VnmcXml.LOGIN.getService(); - xml = replaceXmlValue(xml, "username", _username); - xml = replaceXmlValue(xml, "password", _password); - String response = sendRequest(service, xml); - Map checked = checkResponse(response, "outCookie", "errorCode", "response"); - - if (checked.get("errorCode") != null) - return false; - _cookie = checked.get("outCookie"); - if (_cookie == null) { - return false; - } - return true; - } - - private String getDnForTenant(String tenantName) { - return "org-root/org-" + tenantName; - } - - private String getDnForTenantVDC(String tenantName) { - return getDnForTenant(tenantName) + "/org-VDC-" + tenantName; - } - - private String getDnForTenantVDCEdgeDeviceProfile(String tenantName) { - return getDnForTenantVDC(tenantName) + "/edsp-" + getNameForEdgeDeviceServiceProfile(tenantName); - } - - private String getDnForTenantVDCEdgeSecurityProfile(String tenantName) { - return getDnForTenantVDC(tenantName) + "/vnep-" + getNameForEdgeDeviceSecurityProfile(tenantName); - } - - private String getDnForEdgeDeviceRoutingPolicy(String tenantName) { - return getDnForTenantVDC(tenantName) + "/routing-policy-" + getNameForEdgeDeviceRoutePolicy(tenantName); - //FIXME: any other construct is unreliable. why? - } - - private String getDnForDhcpPolicy(String tenantName, String intfName) { - return getDnForTenantVDCEdgeDeviceProfile(tenantName) + "/dhcp-" + intfName; - } - - private String getNameForDhcpPolicy(String tenantName) { - return tenantName + "-Dhcp-Policy"; - } - - private String getNameForDhcpServer(String tenantName) { - return tenantName + "-Dhcp-Server"; - } - - private String getDnForDhcpServerPolicy(String tenantName) { - return getDnForTenantVDC(tenantName) + "/dhcp-server-" + getNameForDhcpPolicy(tenantName); - } - - private String getNameForIpRange() { - return "iprange"; - } - - private String getDnForDhcpIpRange(String tenantName) { - return getDnForDhcpServerPolicy(tenantName) + "/ip-range-" + getNameForIpRange(); - } - - private String getNameForDNSService(String tenantName) { - return tenantName + "-DNS"; - } - - private String getDnForDnsService(String tenantName) { - return getDnForDhcpServerPolicy(tenantName) + "/dns-svc-" + getNameForDNSService(tenantName); - } - - private String getDnForDnsServer(String tenantName, String dnsip) { - return getDnForDnsService(tenantName) + "/dns-" + dnsip; - } - - private String getNameForTenantVDC(String tenantName) { - return "VDC-" + tenantName; - } - - private String getNameForEdgeDeviceServiceProfile(String tenantName) { - return "EDSP-" + tenantName; - } - - private String getNameForEdgeDeviceSecurityProfile(String tenantName) { - return "ESP-" + tenantName; - } - - private String getNameForEdgeDeviceRoutePolicy(String tenantName) { - return "EDSP-" + tenantName + "-Routes"; - } - - @Override - public boolean createTenant(String tenantName) throws ExecutionException { - String xml = VnmcXml.CREATE_TENANT.getXml(); - String service = VnmcXml.CREATE_TENANT.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "Tenant for account " + tenantName); - xml = replaceXmlValue(xml, "name", tenantName); - xml = replaceXmlValue(xml, "dn", getDnForTenant(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenant(String tenantName) throws ExecutionException { - String xml = VnmcXml.DELETE_TENANT.getXml(); - String service = VnmcXml.DELETE_TENANT.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "name", tenantName); - xml = replaceXmlValue(xml, "dn", getDnForTenant(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDC(String tenantName) throws ExecutionException { - String xml = VnmcXml.CREATE_VDC.getXml(); - String service = VnmcXml.CREATE_VDC.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "VDC for Tenant " + tenantName); - xml = replaceXmlValue(xml, "name", getNameForTenantVDC(tenantName)); - xml = replaceXmlValue(xml, "dn", getDnForTenantVDC(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDC(String tenantName) throws ExecutionException { - String xml = VnmcXml.DELETE_VDC.getXml(); - String service = VnmcXml.DELETE_VDC.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "name", getNameForTenantVDC(tenantName)); - xml = replaceXmlValue(xml, "dn", getDnForTenantVDC(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEdgeDeviceProfile(String tenantName) throws ExecutionException { - String xml = VnmcXml.CREATE_EDGE_DEVICE_PROFILE.getXml(); - String service = VnmcXml.CREATE_EDGE_DEVICE_PROFILE.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "Edge Device Profile for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceServiceProfile(tenantName)); - xml = replaceXmlValue(xml, "dn", getDnForTenantVDCEdgeDeviceProfile(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEdgeStaticRoutePolicy(String tenantName) throws ExecutionException { - String xml = VnmcXml.CREATE_EDGE_ROUTE_POLICY.getXml(); - String service = VnmcXml.CREATE_EDGE_ROUTE_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceRoutePolicy(tenantName)); - xml = replaceXmlValue(xml, "routepolicydn", getDnForEdgeDeviceRoutingPolicy(tenantName)); - xml = replaceXmlValue(xml, "descr", "Routing Policy for Edge Device for Tenant " + tenantName); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEdgeStaticRoute(String tenantName, String nextHopIp, String destination, String netmask) throws ExecutionException { - String xml = VnmcXml.CREATE_EDGE_ROUTE.getXml(); - String service = VnmcXml.CREATE_EDGE_ROUTE.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "routepolicydn", getDnForEdgeDeviceRoutingPolicy(tenantName)); - xml = replaceXmlValue(xml, "nexthop", nextHopIp); - xml = replaceXmlValue(xml, "nexthopintf", getNameForEdgeOutsideIntf(tenantName)); - xml = replaceXmlValue(xml, "destination", destination); - xml = replaceXmlValue(xml, "netmask", netmask); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean associateTenantVDCEdgeStaticRoutePolicy(String tenantName) throws ExecutionException { - String xml = VnmcXml.RESOLVE_EDGE_ROUTE_POLICY.getXml(); - String service = VnmcXml.RESOLVE_EDGE_ROUTE_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceServiceProfile(tenantName)); - xml = replaceXmlValue(xml, "dn", getDnForTenantVDCEdgeDeviceProfile(tenantName)); - xml = replaceXmlValue(xml, "routepolicyname", getNameForEdgeDeviceRoutePolicy(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean associateTenantVDCEdgeDhcpPolicy(String tenantName, String intfName) throws ExecutionException { - String xml = VnmcXml.RESOLVE_EDGE_DHCP_POLICY.getXml(); - String service = VnmcXml.RESOLVE_EDGE_DHCP_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "dhcpdn", getDnForDhcpPolicy(tenantName, intfName)); - xml = replaceXmlValue(xml, "insideintf", intfName); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEdgeDhcpPolicy(String tenantName, String startIp, String endIp, String subnet, String nameServerIp, String domain) - throws ExecutionException { - String xml = VnmcXml.CREATE_DHCP_POLICY.getXml(); - String service = VnmcXml.CREATE_DHCP_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "dhcpserverdn", getDnForDhcpServerPolicy(tenantName)); - xml = replaceXmlValue(xml, "dhcpserverdescr", "DHCP server for " + tenantName); - xml = replaceXmlValue(xml, "dhcpservername", getNameForDhcpPolicy(tenantName)); - xml = replaceXmlValue(xml, "iprangedn", getDnForDhcpIpRange(tenantName)); - xml = replaceXmlValue(xml, "startip", startIp); - xml = replaceXmlValue(xml, "endip", endIp); - xml = replaceXmlValue(xml, "subnet", subnet); - xml = replaceXmlValue(xml, "domain", domain); - xml = replaceXmlValue(xml, "dnsservicedn", getDnForDnsService(tenantName)); - xml = replaceXmlValue(xml, "dnsservicename", getNameForDNSService(tenantName)); - xml = replaceXmlValue(xml, "nameserverip", nameServerIp); - xml = replaceXmlValue(xml, "nameserverdn", getDnForDnsServer(tenantName, nameServerIp)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean associateTenantVDCEdgeDhcpServerPolicy(String tenantName, String intfName) throws ExecutionException { - String xml = VnmcXml.RESOLVE_EDGE_DHCP_SERVER_POLICY.getXml(); - String service = VnmcXml.RESOLVE_EDGE_DHCP_SERVER_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "dhcpdn", getDnForDhcpPolicy(tenantName, intfName)); - xml = replaceXmlValue(xml, "insideintf", intfName); - xml = replaceXmlValue(xml, "dhcpserverpolicyname", getNameForDhcpServer(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEdgeSecurityProfile(String tenantName) throws ExecutionException { - String xml = VnmcXml.CREATE_EDGE_SECURITY_PROFILE.getXml(); - String service = VnmcXml.CREATE_EDGE_SECURITY_PROFILE.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "Edge Security Profile for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "espdn", getDnForTenantVDCEdgeSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "egressref", "default-egress"); - xml = replaceXmlValue(xml, "ingressref", "default-ingress"); //FIXME: allows everything - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCEdgeSecurityProfile(String tenantName) throws ExecutionException { - String xml = VnmcXml.DELETE_EDGE_SECURITY_PROFILE.getXml(); - String service = VnmcXml.DELETE_EDGE_SECURITY_PROFILE.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "espdn", getDnForTenantVDCEdgeSecurityProfile(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private String getNameForSourceNatIpPool(String tenantName) { - return "SNATIp-" + tenantName; - } - - private String getDnForSourceNatPool(String tenantName) { - return getDnForTenantVDC(tenantName) + "/objgrp-" + getNameForSourceNatIpPool(tenantName); - } - - @Override - public boolean createTenantVDCSourceNatIpPool(String tenantName, String identifier, String publicIp) throws ExecutionException { - return createTenantVDCIpPool(getDnForSourceNatPool(tenantName), getNameForSourceNatIpPool(tenantName), "Source NAT ip pool for Tenant VDC " + tenantName, - publicIp); - } - - private String getNameForSourceNatPolicy(String tenantName) { - return "SNAT-Policy-" + tenantName; - } - - private String getDnForSourceNatPolicy(String tenantName) { - return getDnForTenantVDC(tenantName) + "/natpol-" + getNameForSourceNatPolicy(tenantName); - } - - private String getNameForSourceNatRule(String tenantName) { - return "SNAT-Rule-" + tenantName; - } - - private String getDnForSourceNatRule(String tenantName) { - return getDnForSourceNatPolicy(tenantName) + "/rule-" + getNameForSourceNatRule(tenantName); - } - - private String getNameForNatPolicySet(String tenantName) { - return "NAT-PolicySet-" + tenantName; - } - - private String getDnForNatPolicySet(String tenantName) { - return getDnForTenantVDC(tenantName) + "/natpset-" + getNameForNatPolicySet(tenantName); - } - - private String getDnForSourceNatPolicyRef(String tenantName) { - return getDnForNatPolicySet(tenantName) + "/polref-" + getNameForSourceNatPolicy(tenantName); - } - - @Override - public boolean createTenantVDCSourceNatRule(String tenantName, String identifier, String startSourceIp, String endSourceIp) throws ExecutionException { - - String xml = VnmcXml.CREATE_SOURCE_NAT_RULE.getXml(); - String service = VnmcXml.CREATE_SOURCE_NAT_RULE.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natruledn", getDnForSourceNatRule(tenantName)); - xml = replaceXmlValue(xml, "natrulename", getNameForSourceNatRule(tenantName)); - xml = replaceXmlValue(xml, "descr", "Source NAT rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "srcstartip", startSourceIp); - xml = replaceXmlValue(xml, "srcendip", endSourceIp); - xml = replaceXmlValue(xml, "ippoolname", getNameForSourceNatIpPool(tenantName)); - - long order = 100; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCSourceNatPolicyRef(String tenantName, String identifier) throws ExecutionException { - return createTenantVDCNatPolicyRef(getDnForSourceNatPolicyRef(tenantName), getNameForSourceNatPolicy(tenantName), tenantName, true); - } - - @Override - public boolean createTenantVDCSourceNatPolicy(String tenantName, String identifier) throws ExecutionException { - return createTenantVDCNatPolicy(getDnForSourceNatPolicy(tenantName), getNameForSourceNatPolicy(tenantName)); - } - - @Override - public boolean createTenantVDCNatPolicySet(String tenantName) throws ExecutionException { - String xml = VnmcXml.CREATE_NAT_POLICY_SET.getXml(); - String service = VnmcXml.CREATE_NAT_POLICY_SET.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "NAT policy set for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "natpolicysetname", getNameForNatPolicySet(tenantName)); - xml = replaceXmlValue(xml, "natpolicysetdn", getDnForNatPolicySet(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCNatPolicySet(String tenantName) throws ExecutionException { - String xml = VnmcXml.DELETE_NAT_POLICY_SET.getXml(); - String service = VnmcXml.DELETE_NAT_POLICY_SET.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natpolicysetname", getNameForNatPolicySet(tenantName)); - xml = replaceXmlValue(xml, "natpolicysetdn", getDnForNatPolicySet(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean associateNatPolicySet(String tenantName) throws ExecutionException { - String xml = VnmcXml.RESOLVE_NAT_POLICY_SET.getXml(); - String service = VnmcXml.RESOLVE_NAT_POLICY_SET.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "Edge Security Profile for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "espdn", getDnForTenantVDCEdgeSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "natpolicysetname", getNameForNatPolicySet(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private String getNameForAclPolicySet(String tenantName, boolean ingress) { - return (ingress ? "Ingress-" : "Egress-") + "ACL-PolicySet-" + tenantName; - } - - private String getDnForAclPolicySet(String tenantName, boolean ingress) { - return getDnForTenantVDC(tenantName) + "/pset-" + getNameForAclPolicySet(tenantName, ingress); - } - - private String getNameForAclPolicy(String tenantName, String identifier) { - return "ACL-" + tenantName + "-" + identifier; - } - - private String getDnForAclPolicy(String tenantName, String identifier) { - return getDnForTenantVDC(tenantName) + "/pol-" + getNameForAclPolicy(tenantName, identifier); - } - - private String getDnForAclPolicyRef(String tenantName, String identifier, boolean ingress) { - return getDnForAclPolicySet(tenantName, ingress) + "/polref-" + getNameForAclPolicy(tenantName, identifier); - } - - private String getNameForAclRule(String tenantName, String identifier) { - return "Rule-" + tenantName + "-" + identifier; - } - - private String getDnForAclRule(String tenantName, String identifier, String policyIdentifier) { - return getDnForAclPolicy(tenantName, policyIdentifier) + "/rule-" + getNameForAclRule(tenantName, identifier); - } - - @Override - public boolean createTenantVDCAclPolicy(String tenantName, String identifier) throws ExecutionException { - String xml = VnmcXml.CREATE_ACL_POLICY.getXml(); - String service = VnmcXml.CREATE_ACL_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclpolicyname", getNameForAclPolicy(tenantName, identifier)); - xml = replaceXmlValue(xml, "aclpolicydn", getDnForAclPolicy(tenantName, identifier)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCAclPolicy(String tenantName, String identifier) throws ExecutionException { - String xml = VnmcXml.DELETE_ACL_POLICY.getXml(); - String service = VnmcXml.DELETE_ACL_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclpolicyname", getNameForAclPolicy(tenantName, identifier)); - xml = replaceXmlValue(xml, "aclpolicydn", getDnForAclPolicy(tenantName, identifier)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCAclPolicyRef(String tenantName, String identifier, boolean ingress) throws ExecutionException { - String xml = VnmcXml.CREATE_ACL_POLICY_REF.getXml(); - String service = VnmcXml.CREATE_ACL_POLICY_REF.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclpolicyname", getNameForAclPolicy(tenantName, identifier)); - xml = replaceXmlValue(xml, "aclpolicydn", getDnForAclPolicy(tenantName, identifier)); - xml = replaceXmlValue(xml, "aclpolicyrefdn", getDnForAclPolicyRef(tenantName, identifier, ingress)); - - List policies = listAclPolicies(tenantName); - int order = 100; - if (policies != null) { - order += policies.size(); - } - xml = replaceXmlValue(xml, "order", Integer.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCAclPolicySet(String tenantName, boolean ingress) throws ExecutionException { - String xml = VnmcXml.CREATE_ACL_POLICY_SET.getXml(); - String service = VnmcXml.CREATE_ACL_POLICY_SET.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "ACL policy set for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "aclpolicysetname", getNameForAclPolicySet(tenantName, ingress)); - xml = replaceXmlValue(xml, "aclpolicysetdn", getDnForAclPolicySet(tenantName, ingress)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCAclPolicySet(String tenantName, boolean ingress) throws ExecutionException { - String xml = VnmcXml.DELETE_ACL_POLICY_SET.getXml(); - String service = VnmcXml.DELETE_ACL_POLICY_SET.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclpolicysetname", getNameForAclPolicySet(tenantName, ingress)); - xml = replaceXmlValue(xml, "aclpolicysetdn", getDnForAclPolicySet(tenantName, ingress)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean associateAclPolicySet(String tenantName) throws ExecutionException { - String xml = VnmcXml.RESOLVE_ACL_POLICY_SET.getXml(); - String service = VnmcXml.RESOLVE_ACL_POLICY_SET.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "descr", "Edge Security Profile for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "name", getNameForEdgeDeviceSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "espdn", getDnForTenantVDCEdgeSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "egresspolicysetname", getNameForAclPolicySet(tenantName, false)); - xml = replaceXmlValue(xml, "ingresspolicysetname", getNameForAclPolicySet(tenantName, true)); - xml = replaceXmlValue(xml, "natpolicysetname", getNameForNatPolicySet(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCIngressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp, - String destStartPort, String destEndPort) throws ExecutionException { - String xml = VnmcXml.CREATE_INGRESS_ACL_RULE.getXml(); - String service = VnmcXml.CREATE_INGRESS_ACL_RULE.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclruledn", getDnForAclRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "aclrulename", getNameForAclRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "Ingress ACL rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "actiontype", "permit"); - xml = replaceXmlValue(xml, "protocolvalue", protocol); - xml = replaceXmlValue(xml, "sourcestartip", sourceStartIp); - xml = replaceXmlValue(xml, "sourceendip", sourceEndIp); - xml = replaceXmlValue(xml, "deststartport", destStartPort); - xml = replaceXmlValue(xml, "destendport", destEndPort); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCIngressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp) - throws ExecutionException { - String xml = VnmcXml.CREATE_GENERIC_INGRESS_ACL_RULE.getXml(); - String service = VnmcXml.CREATE_GENERIC_INGRESS_ACL_RULE.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclruledn", getDnForAclRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "aclrulename", getNameForAclRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "Ingress ACL rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "actiontype", "permit"); - xml = replaceXmlValue(xml, "protocolvalue", protocol); - xml = replaceXmlValue(xml, "sourcestartip", sourceStartIp); - xml = replaceXmlValue(xml, "sourceendip", sourceEndIp); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEgressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp, - String destStartPort, String destEndPort) throws ExecutionException { - String xml = VnmcXml.CREATE_EGRESS_ACL_RULE.getXml(); - String service = VnmcXml.CREATE_EGRESS_ACL_RULE.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclruledn", getDnForAclRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "aclrulename", getNameForAclRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "Egress ACL rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "actiontype", "permit"); - xml = replaceXmlValue(xml, "protocolvalue", protocol); - xml = replaceXmlValue(xml, "sourcestartip", sourceStartIp); - xml = replaceXmlValue(xml, "sourceendip", sourceEndIp); - xml = replaceXmlValue(xml, "deststartport", destStartPort); - xml = replaceXmlValue(xml, "destendport", destEndPort); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCEgressAclRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String sourceStartIp, String sourceEndIp) - throws ExecutionException { - String xml = VnmcXml.CREATE_GENERIC_EGRESS_ACL_RULE.getXml(); - String service = VnmcXml.CREATE_GENERIC_EGRESS_ACL_RULE.getService(); - if (protocol.equalsIgnoreCase("all")) { // any protocol - xml = VnmcXml.CREATE_GENERIC_EGRESS_ACL_NO_PROTOCOL_RULE.getXml(); - service = VnmcXml.CREATE_GENERIC_EGRESS_ACL_NO_PROTOCOL_RULE.getService(); - } else { // specific protocol - xml = replaceXmlValue(xml, "protocolvalue", protocol); - } - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclruledn", getDnForAclRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "aclrulename", getNameForAclRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "Egress ACL rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "actiontype", "permit"); - xml = replaceXmlValue(xml, "sourcestartip", sourceStartIp); - xml = replaceXmlValue(xml, "sourceendip", sourceEndIp); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCAclRule(String tenantName, long ruleId, String policyIdentifier) throws ExecutionException { - String identifier = Long.toString(ruleId); - return deleteTenantVDCRule(getDnForAclRule(tenantName, identifier, policyIdentifier), getNameForAclRule(tenantName, identifier)); - } - - private String getNameForPFPortPool(String tenantName, String identifier) { - return "PortPool-" + tenantName + "-" + identifier; - } - - private String getDnForPFPortPool(String tenantName, String identifier) { - return getDnForTenantVDC(tenantName) + "/objgrp-" + getNameForPFPortPool(tenantName, identifier); - } - - private String getNameForPFIpPool(String tenantName, String identifier) { - return "IpPool-" + tenantName + "-" + identifier; - } - - private String getDnForPFIpPool(String tenantName, String identifier) { - return getDnForTenantVDC(tenantName) + "/objgrp-" + getNameForPFIpPool(tenantName, identifier); - } - - private boolean createTenantVDCPortPool(String poolDn, String name, String description, String startPort, String endPort) throws ExecutionException { - String xml = VnmcXml.CREATE_PORT_POOL.getXml(); - String service = VnmcXml.CREATE_PORT_POOL.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "portpooldn", poolDn); - xml = replaceXmlValue(xml, "portpoolname", name); - xml = replaceXmlValue(xml, "descr", description); - xml = replaceXmlValue(xml, "startport", startPort); - xml = replaceXmlValue(xml, "endport", endPort); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private boolean createTenantVDCIpPool(String poolDn, String name, String description, String ipAddress) throws ExecutionException { - String xml = VnmcXml.CREATE_IP_POOL.getXml(); - String service = VnmcXml.CREATE_IP_POOL.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "ippooldn", poolDn); - xml = replaceXmlValue(xml, "ippoolname", name); - xml = replaceXmlValue(xml, "descr", description); - xml = replaceXmlValue(xml, "ipvalue", ipAddress); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private boolean createTenantVDCNatPolicyRef(String policyRefDn, String name, String tenantName, boolean isSourceNat) throws ExecutionException { - String xml = VnmcXml.CREATE_NAT_POLICY_REF.getXml(); - String service = VnmcXml.CREATE_NAT_POLICY_REF.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natpolicyrefdn", policyRefDn); - xml = replaceXmlValue(xml, "natpolicyname", name); - - // PF and static NAT policies need to come before source NAT, so leaving buffer - // and creating source NAT with a high order value. - // Initially tried setting MAX_INT as the order but VNMC complains about it - int order = 10000; // TODO: For now value should be sufficient, if required may need to increase - if (!isSourceNat) { - List policies = listNatPolicies(tenantName); - order = 100; // order starts at 100 - if (policies != null) { - order += policies.size(); - } - } - xml = replaceXmlValue(xml, "order", Integer.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private boolean createTenantVDCNatPolicy(String policyDn, String name) throws ExecutionException { - String xml = VnmcXml.CREATE_NAT_POLICY.getXml(); - String service = VnmcXml.CREATE_NAT_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natpolicydn", policyDn); - xml = replaceXmlValue(xml, "natpolicyname", name); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private boolean deleteTenantVDCNatPolicy(String policyDn, String name) throws ExecutionException { - String xml = VnmcXml.DELETE_NAT_POLICY.getXml(); - String service = VnmcXml.DELETE_NAT_POLICY.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natpolicydn", policyDn); - xml = replaceXmlValue(xml, "natpolicyname", name); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private boolean deleteTenantVDCRule(String ruledn, String ruleName) throws ExecutionException { - String xml = VnmcXml.DELETE_RULE.getXml(); - String service = VnmcXml.DELETE_RULE.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "ruledn", ruledn); - xml = replaceXmlValue(xml, "rulename", ruleName); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private List listNatPolicies(String tenantName) throws ExecutionException { - - String xml = VnmcXml.LIST_NAT_POLICIES.getXml(); - String service = VnmcXml.LIST_NAT_POLICIES.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "vdcdn", getDnForTenantVDC(tenantName)); - - String response = sendRequest(service, xml); - - List result = new ArrayList(); - Document xmlDoc = getDocument(response); - xmlDoc.normalize(); - NodeList policyList = xmlDoc.getElementsByTagName("pair"); - for (int i = 0; i < policyList.getLength(); i++) { - Node policyNode = policyList.item(i); - result.add(policyNode.getAttributes().getNamedItem("key").getNodeValue()); - } - - return result; - } - - private List listAclPolicies(String tenantName) throws ExecutionException { - - String xml = VnmcXml.LIST_ACL_POLICIES.getXml(); - String service = VnmcXml.LIST_ACL_POLICIES.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "vdcdn", getDnForTenantVDC(tenantName)); - - String response = sendRequest(service, xml); - - List result = new ArrayList(); - Document xmlDoc = getDocument(response); - xmlDoc.normalize(); - NodeList policyList = xmlDoc.getElementsByTagName("pair"); - for (int i = 0; i < policyList.getLength(); i++) { - Node policyNode = policyList.item(i); - result.add(policyNode.getAttributes().getNamedItem("key").getNodeValue()); - } - - return result; - } - - private List listChildren(String dn) throws ExecutionException { - - String xml = VnmcXml.LIST_CHILDREN.getXml(); - String service = VnmcXml.LIST_CHILDREN.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "dn", dn); - - String response = sendRequest(service, xml); - - List result = new ArrayList(); - Document xmlDoc = getDocument(response); - xmlDoc.normalize(); - NodeList policyList = xmlDoc.getElementsByTagName("policyRule"); - for (int i = 0; i < policyList.getLength(); i++) { - Node policyNode = policyList.item(i); - result.add(policyNode.getAttributes().getNamedItem("name").getNodeValue()); - } - - return result; - } - - @Override - public boolean createTenantVDCPFPortPool(String tenantName, String identifier, String startPort, String endPort) throws ExecutionException { - return createTenantVDCPortPool(getDnForPFPortPool(tenantName, identifier), getNameForPFPortPool(tenantName, identifier), "PF port pool for " + - getNameForPFPortPool(tenantName, identifier), startPort, endPort); - } - - @Override - public boolean createTenantVDCPFIpPool(String tenantName, String identifier, String ipAddress) throws ExecutionException { - return createTenantVDCIpPool(getDnForPFIpPool(tenantName, identifier), getNameForPFIpPool(tenantName, identifier), - "PF ip pool for " + getNameForPFIpPool(tenantName, identifier), ipAddress); - } - - private String getNameForPFPolicy(String tenantName, String identifier) { - return "PF-" + tenantName + "-" + identifier; - } - - private String getDnForPFPolicy(String tenantName, String identifier) { - return getDnForTenantVDC(tenantName) + "/natpol-" + getNameForPFPolicy(tenantName, identifier); - } - - private String getDnForPFPolicyRef(String tenantName, String identifier) { - return getDnForNatPolicySet(tenantName) + "/polref-" + getNameForPFPolicy(tenantName, identifier); - } - - private String getNameForPFRule(String tenantName, String identifier) { - return "Rule-" + tenantName + "-" + identifier; - } - - private String getDnForPFRule(String tenantName, String identifier, String policyIdentifier) { - return getDnForPFPolicy(tenantName, policyIdentifier) + "/rule-" + getNameForPFRule(tenantName, identifier); - } - - @Override - public boolean createTenantVDCPFRule(String tenantName, long ruleId, String policyIdentifier, String protocol, String publicIp, String startPort, String endPort) - throws ExecutionException { - String xml = VnmcXml.CREATE_PF_RULE.getXml(); - String service = VnmcXml.CREATE_PF_RULE.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natruledn", getDnForPFRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "natrulename", getNameForPFRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "PF rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "ippoolname", getNameForPFIpPool(tenantName, identifier)); - xml = replaceXmlValue(xml, "portpoolname", getNameForPFPortPool(tenantName, identifier)); - xml = replaceXmlValue(xml, "ip", publicIp); - xml = replaceXmlValue(xml, "startport", startPort); - xml = replaceXmlValue(xml, "endport", endPort); - xml = replaceXmlValue(xml, "protocolvalue", protocol); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCPFRule(String tenantName, long ruleId, String policyIdentifier) throws ExecutionException { - String identifier = Long.toString(ruleId); - return deleteTenantVDCRule(getDnForPFRule(tenantName, identifier, policyIdentifier), getNameForPFRule(tenantName, identifier)); - } - - @Override - public boolean createTenantVDCAclRuleForPF(String tenantName, long ruleId, String policyIdentifier, String protocol, String ipAddress, String startPort, - String endPort) throws ExecutionException { - String xml = VnmcXml.CREATE_ACL_RULE_FOR_PF.getXml(); - String service = VnmcXml.CREATE_ACL_RULE_FOR_PF.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclruledn", getDnForAclRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "aclrulename", getNameForAclRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "ACL rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "actiontype", "permit"); - xml = replaceXmlValue(xml, "protocolvalue", protocol); - xml = replaceXmlValue(xml, "ip", ipAddress); - xml = replaceXmlValue(xml, "startport", startPort); - xml = replaceXmlValue(xml, "endport", endPort); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCPFPolicyRef(String tenantName, String identifier) throws ExecutionException { - return createTenantVDCNatPolicyRef(getDnForPFPolicyRef(tenantName, identifier), getNameForPFPolicy(tenantName, identifier), tenantName, false); - } - - @Override - public boolean createTenantVDCPFPolicy(String tenantName, String identifier) throws ExecutionException { - return createTenantVDCNatPolicy(getDnForPFPolicy(tenantName, identifier), getNameForPFPolicy(tenantName, identifier)); - } - - @Override - public boolean deleteTenantVDCPFPolicy(String tenantName, String identifier) throws ExecutionException { - return deleteTenantVDCNatPolicy(getDnForPFPolicy(tenantName, identifier), getNameForPFPolicy(tenantName, identifier)); - } - - private String getNameForDNatIpPool(String tenantName, String identifier) { - return "IpPool-" + tenantName + "-" + identifier + "n"; - } - - private String getDnForDNatIpPool(String tenantName, String identifier) { - return getDnForTenantVDC(tenantName) + "/objgrp-" + getNameForDNatIpPool(tenantName, identifier); - } - - @Override - public boolean createTenantVDCDNatIpPool(String tenantName, String identifier, String ipAddress) throws ExecutionException { - return createTenantVDCIpPool(getDnForDNatIpPool(tenantName, identifier), getNameForDNatIpPool(tenantName, identifier), "DNAT ip pool for " + - getNameForDNatIpPool(tenantName, identifier), ipAddress); - } - - private String getNameForDNatRule(String tenantName, String identifier) { - return "Rule-" + tenantName + "-" + identifier; - } - - private String getDnForDNatRule(String tenantName, String identifier, String policyIdentifier) { - return getDnForDNatPolicy(tenantName, policyIdentifier) + "/rule-" + getNameForDNatRule(tenantName, identifier); - } - - private String getNameForDNatPolicy(String tenantName, String identifier) { - return "DNAT-" + tenantName + "-" + identifier; - } - - private String getDnForDNatPolicy(String tenantName, String identifier) { - return getDnForTenantVDC(tenantName) + "/natpol-" + getNameForDNatPolicy(tenantName, identifier); - } - - private String getDnForDNatPolicyRef(String tenantName, String identifier) { - return getDnForNatPolicySet(tenantName) + "/polref-" + getNameForDNatPolicy(tenantName, identifier); - } - - @Override - public boolean createTenantVDCDNatRule(String tenantName, long ruleId, String policyIdentifier, String publicIp) throws ExecutionException { - String xml = VnmcXml.CREATE_DNAT_RULE.getXml(); - String service = VnmcXml.CREATE_DNAT_RULE.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "natruledn", getDnForDNatRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "natrulename", getNameForDNatRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "DNAT rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "ippoolname", getNameForDNatIpPool(tenantName, identifier)); - xml = replaceXmlValue(xml, "ip", publicIp); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteTenantVDCDNatRule(String tenantName, long ruleId, String policyIdentifier) throws ExecutionException { - String identifier = Long.toString(ruleId); - return deleteTenantVDCRule(getDnForDNatRule(tenantName, identifier, policyIdentifier), getNameForDNatRule(tenantName, identifier)); - } - - @Override - public boolean createTenantVDCAclRuleForDNat(String tenantName, long ruleId, String policyIdentifier, String ipAddress) throws ExecutionException { - String xml = VnmcXml.CREATE_ACL_RULE_FOR_DNAT.getXml(); - String service = VnmcXml.CREATE_ACL_RULE_FOR_DNAT.getService(); - - String identifier = Long.toString(ruleId); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "aclruledn", getDnForAclRule(tenantName, identifier, policyIdentifier)); - xml = replaceXmlValue(xml, "aclrulename", getNameForAclRule(tenantName, identifier)); - xml = replaceXmlValue(xml, "descr", "ACL rule for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "actiontype", "permit"); - xml = replaceXmlValue(xml, "ip", ipAddress); - - long order = 100 + ruleId; - xml = replaceXmlValue(xml, "order", Long.toString(order)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean createTenantVDCDNatPolicyRef(String tenantName, String identifier) throws ExecutionException { - return createTenantVDCNatPolicyRef(getDnForDNatPolicyRef(tenantName, identifier), getNameForDNatPolicy(tenantName, identifier), tenantName, false); - } - - @Override - public boolean createTenantVDCDNatPolicy(String tenantName, String identifier) throws ExecutionException { - return createTenantVDCNatPolicy(getDnForDNatPolicy(tenantName, identifier), getNameForDNatPolicy(tenantName, identifier)); - } - - @Override - public boolean deleteTenantVDCDNatPolicy(String tenantName, String identifier) throws ExecutionException { - return deleteTenantVDCNatPolicy(getDnForDNatPolicy(tenantName, identifier), getNameForDNatPolicy(tenantName, identifier)); - } - - private String getNameForEdgeFirewall(String tenantName) { - return "ASA-1000v-" + tenantName; - } - - private String getDnForEdgeFirewall(String tenantName) { - return getDnForTenantVDC(tenantName) + "/efw-" + getNameForEdgeFirewall(tenantName); - } - - private String getNameForEdgeInsideIntf(String tenantName) { - return "Edge_Inside"; //TODO: make this configurable - } - - private String getNameForEdgeOutsideIntf(String tenantName) { - return "Edge_Outside"; //TODO: make this configurable - } - - private String getDnForOutsideIntf(String tenantName) { - return getDnForEdgeFirewall(tenantName) + "/interface-" + getNameForEdgeOutsideIntf(tenantName); - } - - private String getDnForInsideIntf(String tenantName) { - return getDnForEdgeFirewall(tenantName) + "/interface-" + getNameForEdgeInsideIntf(tenantName); - } - - @Override - public boolean createEdgeFirewall(String tenantName, String publicIp, String insideIp, String publicSubnet, String insideSubnet) throws ExecutionException { - String xml = VnmcXml.CREATE_EDGE_FIREWALL.getXml(); - String service = VnmcXml.CREATE_EDGE_FIREWALL.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "edgefwdescr", "Edge Firewall for Tenant VDC " + tenantName); - xml = replaceXmlValue(xml, "edgefwname", getNameForEdgeFirewall(tenantName)); - xml = replaceXmlValue(xml, "edgefwdn", getDnForEdgeFirewall(tenantName)); - xml = replaceXmlValue(xml, "insideintfname", getNameForEdgeInsideIntf(tenantName)); - xml = replaceXmlValue(xml, "outsideintfname", getNameForEdgeOutsideIntf(tenantName)); - - xml = replaceXmlValue(xml, "insideintfdn", getDnForInsideIntf(tenantName)); - xml = replaceXmlValue(xml, "outsideintfdn", getDnForOutsideIntf(tenantName)); - - xml = replaceXmlValue(xml, "deviceserviceprofiledn", getDnForEdgeFirewall(tenantName) + "/device-service-profile"); - xml = replaceXmlValue(xml, "outsideintfsp", getDnForOutsideIntf(tenantName) + "/interface-service-profile"); - - xml = replaceXmlValue(xml, "secprofileref", getNameForEdgeDeviceSecurityProfile(tenantName)); - xml = replaceXmlValue(xml, "deviceserviceprofile", getNameForEdgeDeviceServiceProfile(tenantName)); - - xml = replaceXmlValue(xml, "insideip", insideIp); - xml = replaceXmlValue(xml, "publicip", publicIp); - xml = replaceXmlValue(xml, "insidesubnet", insideSubnet); - xml = replaceXmlValue(xml, "outsidesubnet", publicSubnet); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean deleteEdgeFirewall(String tenantName) throws ExecutionException { - String xml = VnmcXml.DELETE_EDGE_FIREWALL.getXml(); - String service = VnmcXml.DELETE_EDGE_FIREWALL.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "edgefwname", getNameForEdgeFirewall(tenantName)); - xml = replaceXmlValue(xml, "edgefwdn", getDnForEdgeFirewall(tenantName)); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public Map listUnAssocAsa1000v() throws ExecutionException { - String xml = VnmcXml.LIST_UNASSOC_ASA1000V.getXml(); - String service = VnmcXml.LIST_UNASSOC_ASA1000V.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - - String response = sendRequest(service, xml); - - Map result = new HashMap(); - Document xmlDoc = getDocument(response); - xmlDoc.normalize(); - NodeList fwList = xmlDoc.getElementsByTagName("fwInstance"); - for (int j = 0; j < fwList.getLength(); j++) { - Node fwNode = fwList.item(j); - result.put(fwNode.getAttributes().getNamedItem("mgmtIp").getNodeValue(), fwNode.getAttributes().getNamedItem("dn").getNodeValue()); - } - - return result; - } - - @Override - public boolean assignAsa1000v(String tenantName, String firewallDn) throws ExecutionException { - String xml = VnmcXml.ASSIGN_ASA1000V.getXml(); - String service = VnmcXml.ASSIGN_ASA1000V.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "binddn", getDnForEdgeFirewall(tenantName) + "/binding"); - xml = replaceXmlValue(xml, "fwdn", firewallDn); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - @Override - public boolean unassignAsa1000v(String tenantName, String firewallDn) throws ExecutionException { - String xml = VnmcXml.UNASSIGN_ASA1000V.getXml(); - String service = VnmcXml.UNASSIGN_ASA1000V.getService(); - xml = replaceXmlValue(xml, "cookie", _cookie); - xml = replaceXmlValue(xml, "binddn", getDnForEdgeFirewall(tenantName) + "/binding"); - xml = replaceXmlValue(xml, "fwdn", firewallDn); - - String response = sendRequest(service, xml); - return verifySuccess(response); - } - - private String sendRequest(String service, String xmlRequest) throws ExecutionException { - HttpClient client = new HttpClient(); - String response = null; - PostMethod method = new PostMethod("/xmlIM/" + service); - method.setRequestBody(xmlRequest); - - try { - org.apache.commons.httpclient.protocol.Protocol myhttps = new org.apache.commons.httpclient.protocol.Protocol("https", new EasySSLProtocolSocketFactory(), 443); - client.getHostConfiguration().setHost(_ip, 443, myhttps); - int statusCode = client.executeMethod(method); - - if (statusCode != HttpStatus.SC_OK) { - throw new Exception("Error code : " + statusCode); - } - response = method.getResponseBodyAsString(); - } catch (Exception e) { - System.out.println(e.getMessage()); - throw new ExecutionException(e.getMessage()); - } - System.out.println(response); - return response; - } - - private Map checkResponse(String xmlResponse, String... keys) throws ExecutionException { - Document xmlDoc = getDocument(xmlResponse); - Map result = new HashMap(); - Node topElement = xmlDoc.getChildNodes().item(0); - if (topElement != null) { - for (String key : keys) { - Node valueNode = topElement.getAttributes().getNamedItem(key); - result.put(key, valueNode == null ? null : valueNode.getNodeValue()); - } - } - return result; - } - - private boolean verifySuccess(String xmlResponse) throws ExecutionException { - Map checked = checkResponse(xmlResponse, "errorCode", "errorDescr"); - - if (checked.get("errorCode") != null) { - String errorCode = checked.get("errorCode"); - if (errorCode.equals("103")) { - //tenant already exists - return true; - } - String errorDescr = checked.get("errorDescr"); - throw new ExecutionException(errorDescr); - } - return true; - } - - /* - * XML utils - */ - - private Document getDocument(String xml) throws ExecutionException { - StringReader xmlReader = new StringReader(" \n" + xml.trim()); - InputSource xmlSource = new InputSource(xmlReader); - Document doc = null; - - try { - doc = ParserUtils.getSaferDocumentBuilderFactory().newDocumentBuilder().parse(xmlSource); - - } catch (Exception e) { - LOGGER.error(e); - throw new ExecutionException(e.getMessage()); - } - - if (doc == null) { - throw new ExecutionException("Failed to parse xml " + xml); - } else { - return doc; - } - } - - private String replaceXmlTag(String xml, String oldTag, String newTag) { - return xml.replaceAll(oldTag, newTag); - } - - private String replaceXmlValue(String xml, String marker, String value) { - marker = "\\s*%" + marker + "%\\s*"; - - if (value == null) { - value = ""; - } - - return xml.replaceAll(marker, value); - } - - private String extractXml(String xml, String marker) { - String startMarker = "<" + marker + ">"; - String endMarker = ""; - if (xml.contains(startMarker) && xml.contains(endMarker)) { - return xml.substring(xml.indexOf(startMarker) + startMarker.length(), xml.indexOf(endMarker)); - } else { - return null; - } - - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcController.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcController.java deleted file mode 100644 index 80d6f1747b96..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcController.java +++ /dev/null @@ -1,42 +0,0 @@ -// 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.network.cisco; - -import org.apache.cloudstack.api.Identity; -import org.apache.cloudstack.api.InternalIdentity; - -import com.cloud.org.Grouping; - -public interface CiscoVnmcController extends Grouping, InternalIdentity, Identity { - - @Override - long getId(); - - @Override - String getUuid(); - - void setUuid(String uuid); - - long getPhysicalNetworkId(); - - long getHostId(); - - String getProviderName(); - - String getDeviceName(); - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcControllerVO.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcControllerVO.java deleted file mode 100644 index f03ea9a56568..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/CiscoVnmcControllerVO.java +++ /dev/null @@ -1,109 +0,0 @@ -// 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.network.cisco; - -import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "external_cisco_vnmc_devices") -public class CiscoVnmcControllerVO implements CiscoVnmcController { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "host_id") - private long hostId; - - @Column(name = "physical_network_id") - private long physicalNetworkId; - - @Column(name = "provider_name") - private String providerName; - - @Column(name = "device_name") - private String deviceName; - - public CiscoVnmcControllerVO() { - this.uuid = UUID.randomUUID().toString(); - } - - public CiscoVnmcControllerVO(long hostId, long physicalNetworkId, String providerName, String deviceName) { - super(); - this.hostId = hostId; - this.physicalNetworkId = physicalNetworkId; - this.providerName = providerName; - this.deviceName = deviceName; - this.uuid = UUID.randomUUID().toString(); - } - - @Override - public String toString() { - return String.format("CiscoVnmcController %s", - ReflectionToStringBuilderUtils.reflectOnlySelectedFields( - this, "id", "uuid", "name")); - } - - @Override - public long getId() { - return id; - } - - @Override - public String getUuid() { - return uuid; - } - - @Override - public void setUuid(String uuid) { - this.uuid = uuid; - } - - @Override - public long getPhysicalNetworkId() { - return physicalNetworkId; - } - - @Override - public long getHostId() { - return hostId; - } - - @Override - public String getProviderName() { - return providerName; - } - - @Override - public String getDeviceName() { - return deviceName; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMap.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMap.java deleted file mode 100644 index a86055189a6f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMap.java +++ /dev/null @@ -1,32 +0,0 @@ -// 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.network.cisco; - -import org.apache.cloudstack.api.InternalIdentity; - -import com.cloud.org.Grouping; - -public interface NetworkAsa1000vMap extends Grouping, InternalIdentity { - - @Override - long getId(); - - long getNetworkId(); - - long getAsa1000vId(); - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMapVO.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMapVO.java deleted file mode 100644 index e2837efc0ab1..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/cisco/NetworkAsa1000vMapVO.java +++ /dev/null @@ -1,73 +0,0 @@ -// 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.network.cisco; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "network_asa1000v_map") -public class NetworkAsa1000vMapVO implements NetworkAsa1000vMap { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "network_id") - private long networkId; - - @Column(name = "asa1000v_id") - private long asa1000vId; - - public NetworkAsa1000vMapVO() { - } - - public NetworkAsa1000vMapVO(long networkId, long asa1000vId) { - super(); - this.networkId = networkId; - this.asa1000vId = asa1000vId; - } - - @Override - public long getId() { - return id; - } - - @Override - public long getAsa1000vId() { - return asa1000vId; - } - - public void setAsa1000vId(long asa1000vId) { - this.asa1000vId = asa1000vId; - } - - @Override - public long getNetworkId() { - return networkId; - } - - public void setNetworkId(long networkId) { - this.networkId = networkId; - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDao.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDao.java deleted file mode 100644 index 272c3c6101a0..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDao.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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.network.dao; - -import java.util.List; - -import com.cloud.network.cisco.CiscoAsa1000vDeviceVO; -import com.cloud.utils.db.GenericDao; - -public interface CiscoAsa1000vDao extends GenericDao { - /** - * list all the Cisco Asa 1000v devices added in to this physical network - * @param physicalNetworkId physical Network Id - * @return list of CiscoAsa1000vDeviceVO for this physical network. - */ - List listByPhysicalNetwork(long physicalNetworkId); - - CiscoAsa1000vDeviceVO findByManagementIp(String managementIp); -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDaoImpl.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDaoImpl.java deleted file mode 100644 index f10b11251a89..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoAsa1000vDaoImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -// 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.network.dao; - -import java.util.List; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.cisco.CiscoAsa1000vDeviceVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class CiscoAsa1000vDaoImpl extends GenericDaoBase implements CiscoAsa1000vDao { - - protected final SearchBuilder physicalNetworkIdSearch; - protected final SearchBuilder managementIpSearch; - - public CiscoAsa1000vDaoImpl() { - physicalNetworkIdSearch = createSearchBuilder(); - physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); - physicalNetworkIdSearch.done(); - - managementIpSearch = createSearchBuilder(); - managementIpSearch.and("managementIp", managementIpSearch.entity().getManagementIp(), Op.EQ); - managementIpSearch.done(); - } - - @Override - public List listByPhysicalNetwork(long physicalNetworkId) { - SearchCriteria sc = physicalNetworkIdSearch.create(); - sc.setParameters("physicalNetworkId", physicalNetworkId); - return search(sc, null); - } - - @Override - public CiscoAsa1000vDeviceVO findByManagementIp(String managementIp) { - SearchCriteria sc = managementIpSearch.create(); - sc.setParameters("managementIp", managementIp); - return findOneBy(sc); - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDao.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDao.java deleted file mode 100644 index 85c891eb8f30..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDao.java +++ /dev/null @@ -1,32 +0,0 @@ -// 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.network.dao; - -import java.util.List; - -import com.cloud.network.cisco.CiscoVnmcControllerVO; -import com.cloud.utils.db.GenericDao; - -public interface CiscoVnmcDao extends GenericDao { - /** - * list all the Cisco VNMC devices added in to this physical network - * @param physicalNetworkId physical Network Id - * @return list of CiscoVnmcDeviceVO for this physical network. - */ - List listByPhysicalNetwork(long physicalNetworkId); - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDaoImpl.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDaoImpl.java deleted file mode 100644 index c0f83582efd8..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/CiscoVnmcDaoImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -// 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.network.dao; - -import java.util.List; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.cisco.CiscoVnmcControllerVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class CiscoVnmcDaoImpl extends GenericDaoBase implements CiscoVnmcDao { - - protected final SearchBuilder physicalNetworkIdSearch; - - public CiscoVnmcDaoImpl() { - physicalNetworkIdSearch = createSearchBuilder(); - physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); - physicalNetworkIdSearch.done(); - } - - @Override - public List listByPhysicalNetwork(long physicalNetworkId) { - SearchCriteria sc = physicalNetworkIdSearch.create(); - sc.setParameters("physicalNetworkId", physicalNetworkId); - return search(sc, null); - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDao.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDao.java deleted file mode 100644 index 4619b53e4fad..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDao.java +++ /dev/null @@ -1,28 +0,0 @@ -// 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.network.dao; - -import com.cloud.network.cisco.NetworkAsa1000vMapVO; -import com.cloud.utils.db.GenericDao; - -public interface NetworkAsa1000vMapDao extends GenericDao { - - NetworkAsa1000vMapVO findByNetworkId(long networkId); - - NetworkAsa1000vMapVO findByAsa1000vId(long asa1000vId); - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDaoImpl.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDaoImpl.java deleted file mode 100644 index a3627f101c81..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/dao/NetworkAsa1000vMapDaoImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -// 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.network.dao; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.cisco.NetworkAsa1000vMapVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class NetworkAsa1000vMapDaoImpl extends GenericDaoBase implements NetworkAsa1000vMapDao { - - protected final SearchBuilder networkSearch; - protected final SearchBuilder asa1000vSearch; - - public NetworkAsa1000vMapDaoImpl() { - networkSearch = createSearchBuilder(); - networkSearch.and("networkId", networkSearch.entity().getNetworkId(), Op.EQ); - networkSearch.done(); - - asa1000vSearch = createSearchBuilder(); - asa1000vSearch.and("asa1000vId", asa1000vSearch.entity().getAsa1000vId(), Op.EQ); - asa1000vSearch.done(); - } - - @Override - public NetworkAsa1000vMapVO findByNetworkId(long networkId) { - SearchCriteria sc = networkSearch.create(); - sc.setParameters("networkId", networkId); - return findOneBy(sc); - } - - @Override - public NetworkAsa1000vMapVO findByAsa1000vId(long asa1000vId) { - SearchCriteria sc = asa1000vSearch.create(); - sc.setParameters("asa1000vId", asa1000vId); - return findOneBy(sc); - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoAsa1000vService.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoAsa1000vService.java deleted file mode 100644 index ca92ec27b68c..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoAsa1000vService.java +++ /dev/null @@ -1,42 +0,0 @@ -// 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.network.element; - -import java.util.List; - -import com.cloud.api.commands.AddCiscoAsa1000vResourceCmd; -import com.cloud.api.commands.DeleteCiscoAsa1000vResourceCmd; -import com.cloud.api.commands.ListCiscoAsa1000vResourcesCmd; -import com.cloud.api.response.CiscoAsa1000vResourceResponse; -import com.cloud.network.Network; -import com.cloud.network.cisco.CiscoAsa1000vDevice; -import com.cloud.network.cisco.CiscoAsa1000vDeviceVO; -import com.cloud.utils.component.PluggableService; - -public interface CiscoAsa1000vService extends PluggableService { - - public CiscoAsa1000vDevice addCiscoAsa1000vResource(AddCiscoAsa1000vResourceCmd cmd); - - public CiscoAsa1000vResourceResponse createCiscoAsa1000vResourceResponse(CiscoAsa1000vDevice ciscoAsa1000vDeviceVO); - - boolean deleteCiscoAsa1000vResource(DeleteCiscoAsa1000vResourceCmd cmd); - - List listCiscoAsa1000vResources(ListCiscoAsa1000vResourcesCmd cmd); - - CiscoAsa1000vDevice assignAsa1000vToNetwork(Network network); - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElement.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElement.java deleted file mode 100644 index 2ec05f679add..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElement.java +++ /dev/null @@ -1,932 +0,0 @@ -// 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.network.element; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; -import javax.persistence.EntityExistsException; - -import com.cloud.user.User; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AssociateAsaWithLogicalEdgeFirewallCommand; -import com.cloud.agent.api.CleanupLogicalEdgeFirewallCommand; -import com.cloud.agent.api.ConfigureNexusVsmForAsaCommand; -import com.cloud.agent.api.CreateLogicalEdgeFirewallCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupExternalFirewallCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.to.FirewallRuleTO; -import com.cloud.agent.api.to.IpAddressTO; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.commands.AddCiscoAsa1000vResourceCmd; -import com.cloud.api.commands.AddCiscoVnmcResourceCmd; -import com.cloud.api.commands.DeleteCiscoAsa1000vResourceCmd; -import com.cloud.api.commands.DeleteCiscoVnmcResourceCmd; -import com.cloud.api.commands.ListCiscoAsa1000vResourcesCmd; -import com.cloud.api.commands.ListCiscoVnmcResourcesCmd; -import com.cloud.api.response.CiscoAsa1000vResourceResponse; -import com.cloud.api.response.CiscoVnmcResourceResponse; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.ClusterVSMMapVO; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.Vlan; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.ClusterVSMMapDao; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.DetailVO; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.CiscoNexusVSMDeviceVO; -import com.cloud.network.IpAddress; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.cisco.CiscoAsa1000vDevice; -import com.cloud.network.cisco.CiscoAsa1000vDeviceVO; -import com.cloud.network.cisco.CiscoVnmcController; -import com.cloud.network.cisco.CiscoVnmcControllerVO; -import com.cloud.network.cisco.NetworkAsa1000vMapVO; -import com.cloud.network.dao.CiscoAsa1000vDao; -import com.cloud.network.dao.CiscoNexusVSMDeviceDao; -import com.cloud.network.dao.CiscoVnmcDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.NetworkAsa1000vMapDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.resource.CiscoVnmcResource; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.FirewallRule.TrafficType; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNat; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceState; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.user.Account; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.EntityManager; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.exception.ExceptionUtil; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine.Type; -import com.cloud.vm.VirtualMachineProfile; - -public class CiscoVnmcElement extends AdapterBase implements SourceNatServiceProvider, FirewallServiceProvider, PortForwardingServiceProvider, IpDeployer, - StaticNatServiceProvider, ResourceStateAdapter, NetworkElement, CiscoVnmcElementService, CiscoAsa1000vService { - private static final Map> capabilities = setCapabilities(); - - @Inject - EntityManager _entityMgr; - @Inject - AgentManager _agentMgr; - @Inject - ResourceManager _resourceMgr; - @Inject - ConfigurationManager _configMgr; - @Inject - NetworkOrchestrationService _networkMgr; - @Inject - NetworkModel _networkModel; - @Inject - IpAddressManager _ipAddrMgr; - - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - @Inject - IPAddressDao _ipAddressDao; - @Inject - HostDetailsDao _hostDetailsDao; - @Inject - HostDao _hostDao; - @Inject - NetworkDao _networkDao; - @Inject - ClusterDao _clusterDao; - @Inject - VlanDao _vlanDao; - @Inject - ClusterVSMMapDao _clusterVsmMapDao; - @Inject - CiscoNexusVSMDeviceDao _vsmDeviceDao; - @Inject - CiscoVnmcDao _ciscoVnmcDao; - @Inject - CiscoAsa1000vDao _ciscoAsa1000vDao; - @Inject - NetworkAsa1000vMapDao _networkAsa1000vMapDao; - - protected boolean canHandle(Network network) { - if (network.getBroadcastDomainType() != BroadcastDomainType.Vlan) { - return false; //TODO: should handle VxLAN as well - } - - return true; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); - return true; - } - - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); - capabilities.put(Service.Gateway, null); - - Map firewallCapabilities = new HashMap(); - firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); - firewallCapabilities.put(Capability.SupportedTrafficDirection, "ingress,egress"); - firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); - firewallCapabilities.put(Capability.SupportedEgressProtocols, "tcp,udp,icmp"); - firewallCapabilities.put(Capability.MultipleIps, "true"); - capabilities.put(Service.Firewall, firewallCapabilities); - - capabilities.put(Service.StaticNat, null); - capabilities.put(Service.PortForwarding, null); - - Map sourceNatCapabilities = new HashMap(); - sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "peraccount"); - sourceNatCapabilities.put(Capability.RedundantRouter, "false"); //TODO: - capabilities.put(Service.SourceNat, sourceNatCapabilities); - return capabilities; - } - - @Override - public Map> getCapabilities() { - return capabilities; - } - - @Override - public Provider getProvider() { - return Provider.CiscoVnmc; - } - - private boolean createLogicalEdgeFirewall(long vlanId, String gateway, String gatewayNetmask, String publicIp, String publicNetmask, List publicGateways, - long hostId) { - CreateLogicalEdgeFirewallCommand cmd = new CreateLogicalEdgeFirewallCommand(vlanId, publicIp, gateway, publicNetmask, gatewayNetmask); - for (String publicGateway : publicGateways) { - cmd.getPublicGateways().add(publicGateway); - } - Answer answer = _agentMgr.easySend(hostId, cmd); - return answer.getResult(); - } - - private boolean configureNexusVsmForAsa(long vlanId, String gateway, String vsmUsername, String vsmPassword, String vsmIp, String asaInPortProfile, long hostId) { - ConfigureNexusVsmForAsaCommand cmd = new ConfigureNexusVsmForAsaCommand(vlanId, gateway, vsmUsername, vsmPassword, vsmIp, asaInPortProfile); - Answer answer = _agentMgr.easySend(hostId, cmd); - return answer.getResult(); - } - - private boolean configureSourceNat(long vlanId, String guestCidr, PublicIp sourceNatIp, long hostId) { - boolean add = (sourceNatIp.getState() == IpAddress.State.Releasing ? false : true); - IpAddressTO ip = - new IpAddressTO(sourceNatIp.getAccountId(), sourceNatIp.getAddress().addr(), add, false, sourceNatIp.isSourceNat(), sourceNatIp.getVlanTag(), - sourceNatIp.getGateway(), sourceNatIp.getNetmask(), sourceNatIp.getMacAddress(), null, sourceNatIp.isOneToOneNat()); - boolean addSourceNat = false; - if (sourceNatIp.isSourceNat()) { - addSourceNat = add; - } - - SetSourceNatCommand cmd = new SetSourceNatCommand(ip, addSourceNat); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId)); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, guestCidr); - Answer answer = _agentMgr.easySend(hostId, cmd); - return answer.getResult(); - } - - private boolean associateAsaWithLogicalEdgeFirewall(long vlanId, String asaMgmtIp, long hostId) { - AssociateAsaWithLogicalEdgeFirewallCommand cmd = new AssociateAsaWithLogicalEdgeFirewallCommand(vlanId, asaMgmtIp); - Answer answer = _agentMgr.easySend(hostId, cmd); - return answer.getResult(); - } - - @Override - public boolean implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId()); - - if (zone.getNetworkType() == NetworkType.Basic) { - logger.debug("Not handling network implement in zone of type " + NetworkType.Basic); - return false; - } - - if (!canHandle(network)) { - return false; - } - - final List devices = _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Cisco Vnmc device on network {}", network); - return false; - } - - List asaList = _ciscoAsa1000vDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (asaList.isEmpty()) { - logger.debug("No Cisco ASA 1000v device on network {}", network); - return false; - } - - NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId()); - if (asaForNetwork != null) { - logger.debug("Cisco ASA 1000v device already associated with network {}", network); - return true; - } - - if (!_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.CiscoVnmc)) { - logger.error("SourceNat service is not provided by Cisco Vnmc device on network {}", network); - return false; - } - - try { - // ensure that there is an ASA 1000v assigned to this network - CiscoAsa1000vDevice assignedAsa = assignAsa1000vToNetwork(network); - if (assignedAsa == null) { - logger.error("Unable to assign ASA 1000v device to network {}", network); - throw new CloudRuntimeException(String.format("Unable to assign ASA 1000v device to network %s", network)); - } - - ClusterVO asaCluster = _clusterDao.findById(assignedAsa.getClusterId()); - ClusterVSMMapVO clusterVsmMap = _clusterVsmMapDao.findByClusterId(assignedAsa.getClusterId()); - if (clusterVsmMap == null) { - logger.error("Vmware cluster {} has no Cisco Nexus VSM device associated with it", asaCluster); - throw new CloudRuntimeException(String.format("Vmware cluster %s has no Cisco Nexus VSM device associated with it", asaCluster)); - } - - CiscoNexusVSMDeviceVO vsmDevice = _vsmDeviceDao.findById(clusterVsmMap.getVsmId()); - if (vsmDevice == null) { - logger.error("Unable to load details of Cisco Nexus VSM device associated with cluster {}", asaCluster); - throw new CloudRuntimeException(String.format("Unable to load details of Cisco Nexus VSM device associated with cluster %s", asaCluster)); - } - - CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0); - HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId()); - _hostDao.loadDetails(ciscoVnmcHost); - Account owner = context.getAccount(); - PublicIp sourceNatIp = _ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network); - long vlanId = Long.parseLong(BroadcastDomainType.getValue(network.getBroadcastUri())); - - List vlanVOList = _vlanDao.listVlansByPhysicalNetworkId(network.getPhysicalNetworkId()); - List publicGateways = new ArrayList(); - for (VlanVO vlanVO : vlanVOList) { - publicGateways.add(vlanVO.getVlanGateway()); - } - - // due to VNMC limitation of not allowing source NAT ip as the outside ip of firewall, - // an additional public ip needs to acquired for assigning as firewall outside ip. - // In case there are already additional ip addresses available (network restart) use one - // of them such that it is not the source NAT ip - IpAddress outsideIp = null; - List publicIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null); - for (IPAddressVO ip : publicIps) { - if (!ip.isSourceNat()) { - outsideIp = ip; - break; - } - } - if (outsideIp == null) { // none available, acquire one - try { - Account caller = CallContext.current().getCallingAccount(); - User callerUser = CallContext.current().getCallingUser(); - outsideIp = _ipAddrMgr.allocateIp(owner, false, caller, callerUser, zone, true, null); - } catch (ResourceAllocationException e) { - logger.error("Unable to allocate additional public Ip address. Exception details " + e); - throw new CloudRuntimeException("Unable to allocate additional public Ip address. Exception details " + e); - } - - try { - outsideIp = _ipAddrMgr.associateIPToGuestNetwork(outsideIp.getId(), network.getId(), true); - } catch (ResourceAllocationException e) { - logger.error("Unable to assign allocated additional public Ip " + outsideIp.getAddress().addr() + " to network with vlan " + vlanId + - ". Exception details " + e); - throw new CloudRuntimeException("Unable to assign allocated additional public Ip " + outsideIp.getAddress().addr() + " to network with vlan " + - vlanId + ". Exception details " + e); - } - } - - // create logical edge firewall in VNMC - String gatewayNetmask = NetUtils.getCidrNetmask(network.getCidr()); - // due to ASA limitation of allowing single subnet to be assigned to firewall interfaces, - // all public ip addresses must be from same subnet, this essentially means single public subnet in zone - if (!createLogicalEdgeFirewall(vlanId, network.getGateway(), gatewayNetmask, outsideIp.getAddress().addr(), sourceNatIp.getNetmask(), publicGateways, - ciscoVnmcHost.getId())) { - logger.error("Failed to create logical edge firewall in Cisco VNMC device for network {}", network); - throw new CloudRuntimeException(String.format("Failed to create logical edge firewall in Cisco VNMC device for network %s", network)); - } - - // create stuff in VSM for ASA device - if (!configureNexusVsmForAsa(vlanId, network.getGateway(), vsmDevice.getUserName(), vsmDevice.getPassword(), vsmDevice.getipaddr(), - assignedAsa.getInPortProfile(), ciscoVnmcHost.getId())) { - logger.error("Failed to configure Cisco Nexus VSM {} for ASA device for network {}", vsmDevice.getipaddr(), network); - throw new CloudRuntimeException(String.format("Failed to configure Cisco Nexus VSM %s for ASA device for network %s", vsmDevice.getipaddr(), network)); - } - - // configure source NAT - if (!configureSourceNat(vlanId, network.getCidr(), sourceNatIp, ciscoVnmcHost.getId())) { - logger.error("Failed to configure source NAT in Cisco VNMC device for network {}", network); - throw new CloudRuntimeException(String.format("Failed to configure source NAT in Cisco VNMC device for network %s", network)); - } - - // associate Asa 1000v instance with logical edge firewall - if (!associateAsaWithLogicalEdgeFirewall(vlanId, assignedAsa.getManagementIp(), ciscoVnmcHost.getId())) { - logger.error("Failed to associate Cisco ASA 1000v ({}) with logical edge firewall in VNMC for network {}", assignedAsa.getManagementIp(), network); - throw new CloudRuntimeException(String.format("Failed to associate Cisco ASA 1000v (%s) with logical edge firewall in VNMC for network %s", assignedAsa.getManagementIp(), network)); - } - } catch (CloudRuntimeException e) { - unassignAsa1000vFromNetwork(network); - logger.error("CiscoVnmcElement failed", e); - return false; - } catch (Exception e) { - unassignAsa1000vFromNetwork(network); - ExceptionUtil.rethrowRuntime(e); - ExceptionUtil.rethrow(e, InsufficientAddressCapacityException.class); - ExceptionUtil.rethrow(e, ResourceUnavailableException.class); - throw new IllegalStateException(e); - } - - return true; - } - - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - if (vm.getType() != Type.User) { - return false; - } - - // ensure that there is an ASA 1000v assigned to this network - NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId()); - if (asaForNetwork == null) { - return false; - } - - return true; - } - - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - return true; - } - - private boolean cleanupLogicalEdgeFirewall(long vlanId, long hostId) { - CleanupLogicalEdgeFirewallCommand cmd = new CleanupLogicalEdgeFirewallCommand(vlanId); - Answer answer = _agentMgr.easySend(hostId, cmd); - return answer.getResult(); - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - - unassignAsa1000vFromNetwork(network); - - long vlanId = Long.parseLong(BroadcastDomainType.getValue(network.getBroadcastUri())); - List devices = _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (!devices.isEmpty()) { - CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0); - HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId()); - cleanupLogicalEdgeFirewall(vlanId, ciscoVnmcHost.getId()); - } - - return true; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - if (!services.contains(Service.Firewall)) { - logger.warn("CiscoVnmc must be used as Firewall Service Provider in the network"); - return false; - } - return true; - } - - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } - - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddCiscoVnmcResourceCmd.class); - cmdList.add(DeleteCiscoVnmcResourceCmd.class); - cmdList.add(ListCiscoVnmcResourcesCmd.class); - cmdList.add(AddCiscoAsa1000vResourceCmd.class); - cmdList.add(DeleteCiscoAsa1000vResourceCmd.class); - cmdList.add(ListCiscoAsa1000vResourcesCmd.class); - return cmdList; - } - - @Override - public CiscoVnmcController addCiscoVnmcResource(AddCiscoVnmcResourceCmd cmd) { - final String deviceName = Provider.CiscoVnmc.getName(); - NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName); - final Long physicalNetworkId = cmd.getPhysicalNetworkId(); - CiscoVnmcController ciscoVnmcResource = null; - - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); - } - long zoneId = physicalNetwork.getDataCenterId(); - - final PhysicalNetworkServiceProviderVO ntwkSvcProvider = - _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder()); - if (ntwkSvcProvider == null) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is not enabled in the physical network: %s to add this device", - networkDevice.getNetworkServiceProvder(), physicalNetwork)); - } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is in shutdown state in the physical network: %s to add this device", - ntwkSvcProvider.getProviderName(), physicalNetwork)); - } - - if (_ciscoVnmcDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) { - throw new CloudRuntimeException("A Cisco Vnmc device is already configured on this physical network"); - } - - Map params = new HashMap(); - params.put("guid", UUID.randomUUID().toString()); - params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); - params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); - params.put("name", "Cisco VNMC Controller - " + cmd.getHost()); - params.put("ip", cmd.getHost()); - params.put("username", cmd.getUsername()); - params.put("password", cmd.getPassword()); - - Map hostdetails = new HashMap(); - hostdetails.putAll(params); - - ServerResource resource = new CiscoVnmcResource(); - try { - resource.configure(cmd.getHost(), hostdetails); - - final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalFirewall, params); - if (host != null) { - return Transaction.execute(new TransactionCallback() { - @Override - public CiscoVnmcController doInTransaction(TransactionStatus status) { - CiscoVnmcController ciscoVnmcResource = new CiscoVnmcControllerVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName); - _ciscoVnmcDao.persist((CiscoVnmcControllerVO)ciscoVnmcResource); - - DetailVO detail = new DetailVO(host.getId(), "deviceid", String.valueOf(ciscoVnmcResource.getId())); - _hostDetailsDao.persist(detail); - - return ciscoVnmcResource; - } - }); - } else { - throw new CloudRuntimeException("Failed to add Cisco Vnmc device due to internal error."); - } - } catch (ConfigurationException e) { - throw new CloudRuntimeException(e.getMessage()); - } - } - - @Override - public CiscoVnmcResourceResponse createCiscoVnmcResourceResponse(CiscoVnmcController ciscoVnmcResourceVO) { - HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcResourceVO.getHostId()); - - CiscoVnmcResourceResponse response = new CiscoVnmcResourceResponse(); - response.setId(ciscoVnmcResourceVO.getUuid()); - response.setPhysicalNetworkId(ciscoVnmcResourceVO.getPhysicalNetworkId()); - response.setProviderName(ciscoVnmcResourceVO.getProviderName()); - response.setResourceName(ciscoVnmcHost.getName()); - - return response; - } - - @Override - public boolean deleteCiscoVnmcResource(DeleteCiscoVnmcResourceCmd cmd) { - Long vnmcResourceId = cmd.getCiscoVnmcResourceId(); - CiscoVnmcControllerVO vnmcResource = _ciscoVnmcDao.findById(vnmcResourceId); - if (vnmcResource == null) { - throw new InvalidParameterValueException("Could not find a Cisco VNMC appliance with id " + vnmcResourceId); - } - - // Check if there any ASA 1000v appliances - Long physicalNetworkId = vnmcResource.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork != null) { - List responseList = _ciscoAsa1000vDao.listByPhysicalNetwork(physicalNetworkId); - if (responseList.size() > 0) { - throw new CloudRuntimeException(String.format("Cisco VNMC appliance %s cannot be deleted as there Cisco ASA 1000v appliances using it", vnmcResource)); - } - } - - HostVO vnmcHost = _hostDao.findById(vnmcResource.getHostId()); - Long hostId = vnmcHost.getId(); - vnmcHost.setResourceState(ResourceState.Maintenance); - _hostDao.update(hostId, vnmcHost); - _resourceMgr.deleteHost(hostId, false, false); - _ciscoVnmcDao.remove(vnmcResourceId); - - return true; - } - - @Override - public List listCiscoVnmcResources(ListCiscoVnmcResourcesCmd cmd) { - Long physicalNetworkId = cmd.getPhysicalNetworkId(); - Long ciscoVnmcResourceId = cmd.getCiscoVnmcResourceId(); - List responseList = new ArrayList(); - - if (physicalNetworkId == null && ciscoVnmcResourceId == null) { - throw new InvalidParameterValueException("Either physical network Id or vnmc device Id must be specified"); - } - - if (ciscoVnmcResourceId != null) { - CiscoVnmcControllerVO ciscoVnmcResource = _ciscoVnmcDao.findById(ciscoVnmcResourceId); - if (ciscoVnmcResource == null) { - throw new InvalidParameterValueException(String.format("Could not find Cisco Vnmc device with id: %d", ciscoVnmcResourceId)); - } - responseList.add(ciscoVnmcResource); - } else { - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); - } - responseList = _ciscoVnmcDao.listByPhysicalNetwork(physicalNetworkId); - } - - return responseList; - } - - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } - - @Override - public boolean applyFWRules(Network network, List rules) throws ResourceUnavailableException { - - if (!_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, Provider.CiscoVnmc)) { - logger.error("Firewall service is not provided by Cisco Vnmc device on network {}", network); - return false; - } - - // Find VNMC host for physical network - List devices = _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Cisco Vnmc device on network {}", network); - return true; - } - - // Find if ASA 1000v is associated with network - NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId()); - if (asaForNetwork == null) { - logger.debug("Cisco ASA 1000v device is not associated with network {}", network); - return true; - } - - if (network.getState() == Network.State.Allocated) { - logger.debug("External firewall was asked to apply firewall rules for network {}; this network is not implemented. Skipping backend commands.", network); - return true; - } - - CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0); - HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId()); - - List rulesTO = new ArrayList(); - for (FirewallRule rule : rules) { - String address = "0.0.0.0"; - if (rule.getTrafficType() == TrafficType.Ingress) { - IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId()); - address = sourceIp.getAddress().addr(); - } - FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, address, rule.getPurpose(), rule.getTrafficType()); - rulesTO.add(ruleTO); - } - - if (!rulesTO.isEmpty()) { - SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rulesTO); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, BroadcastDomainType.getValue(network.getBroadcastUri())); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); - Answer answer = _agentMgr.easySend(ciscoVnmcHost.getId(), cmd); - if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "Unable to apply firewall rules to Cisco ASA 1000v appliance due to: " + details + "."; - logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } - } - - return true; - } - - @Override - public boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException { - - if (!_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, Provider.CiscoVnmc)) { - logger.error("Port forwarding service is not provided by Cisco Vnmc device on network {}", network); - return false; - } - - // Find VNMC host for physical network - List devices = _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Cisco Vnmc device on network {}", network); - return true; - } - - // Find if ASA 1000v is associated with network - NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId()); - if (asaForNetwork == null) { - logger.debug("Cisco ASA 1000v device is not associated with network {}", network); - return true; - } - - if (network.getState() == Network.State.Allocated) { - logger.debug("External firewall was asked to apply port forwarding rules for network with ID {}; this network is not implemented. Skipping backend commands.", network); - return true; - } - - CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0); - HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId()); - - List rulesTO = new ArrayList(); - for (PortForwardingRule rule : rules) { - IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId()); - Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); - PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); - rulesTO.add(ruleTO); - } - - if (!rulesTO.isEmpty()) { - SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(rulesTO); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, BroadcastDomainType.getValue(network.getBroadcastUri())); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); - Answer answer = _agentMgr.easySend(ciscoVnmcHost.getId(), cmd); - if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "Unable to apply port forwarding rules to Cisco ASA 1000v appliance due to: " + details + "."; - logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } - } - - return true; - } - - @Override - public boolean applyStaticNats(Network network, List rules) throws ResourceUnavailableException { - if (!_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.StaticNat, Provider.CiscoVnmc)) { - logger.error("Static NAT service is not provided by Cisco Vnmc device on network {}", network); - return false; - } - - // Find VNMC host for physical network - List devices = _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No Cisco Vnmc device on network {}", network); - return true; - } - - // Find if ASA 1000v is associated with network - NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId()); - if (asaForNetwork == null) { - logger.debug("Cisco ASA 1000v device is not associated with network {}", network); - return true; - } - - if (network.getState() == Network.State.Allocated) { - logger.debug("External firewall was asked to apply static NAT rules for network with ID {}; this network is not implemented. Skipping backend commands.", network); - return true; - } - - CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0); - HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId()); - - List rulesTO = new ArrayList(); - for (StaticNat rule : rules) { - IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId()); - StaticNatRuleTO ruleTO = - new StaticNatRuleTO(rule.getSourceIpAddressId(), sourceIp.getAddress().addr(), null, null, rule.getDestIpAddress(), null, null, null, rule.isForRevoke(), - false); - rulesTO.add(ruleTO); - } - - if (!rulesTO.isEmpty()) { - SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO, null); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, BroadcastDomainType.getValue(network.getBroadcastUri())); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); - Answer answer = _agentMgr.easySend(ciscoVnmcHost.getId(), cmd); - if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "Unable to apply static NAT rules to Cisco ASA 1000v appliance due to: " + details + "."; - logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } - } - - return true; - } - - @Override - public boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - if (!(startup[0] instanceof StartupExternalFirewallCommand)) { - return null; - } - host.setType(Host.Type.ExternalFirewall); - return host; - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (host.getType() != com.cloud.host.Host.Type.ExternalFirewall) { - return null; - } - return new DeleteHostAnswer(true); - } - - @Override - public CiscoAsa1000vDevice addCiscoAsa1000vResource(AddCiscoAsa1000vResourceCmd cmd) { - Long physicalNetworkId = cmd.getPhysicalNetworkId(); - CiscoAsa1000vDevice ciscoAsa1000vResource = null; - - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); - } - - ciscoAsa1000vResource = new CiscoAsa1000vDeviceVO(physicalNetworkId, cmd.getManagementIp().trim(), cmd.getInPortProfile(), cmd.getClusterId()); - try { - _ciscoAsa1000vDao.persist((CiscoAsa1000vDeviceVO)ciscoAsa1000vResource); - } catch (EntityExistsException e) { - throw new InvalidParameterValueException("An ASA 1000v appliance already exists with same configuration"); - } - - return ciscoAsa1000vResource; - } - - @Override - public CiscoAsa1000vResourceResponse createCiscoAsa1000vResourceResponse(CiscoAsa1000vDevice ciscoAsa1000vDeviceVO) { - CiscoAsa1000vResourceResponse response = new CiscoAsa1000vResourceResponse(); - response.setId(ciscoAsa1000vDeviceVO.getUuid()); - response.setManagementIp(ciscoAsa1000vDeviceVO.getManagementIp()); - response.setInPortProfile(ciscoAsa1000vDeviceVO.getInPortProfile()); - - NetworkAsa1000vMapVO networkAsaMap = _networkAsa1000vMapDao.findByAsa1000vId(ciscoAsa1000vDeviceVO.getId()); - if (networkAsaMap != null) { - response.setGuestNetworkId(networkAsaMap.getNetworkId()); - } - - return response; - } - - @Override - public boolean deleteCiscoAsa1000vResource(DeleteCiscoAsa1000vResourceCmd cmd) { - Long asaResourceId = cmd.getCiscoAsa1000vResourceId(); - CiscoAsa1000vDeviceVO asaResource = _ciscoAsa1000vDao.findById(asaResourceId); - if (asaResource == null) { - throw new InvalidParameterValueException("Could not find a Cisco ASA 1000v appliance with id " + asaResourceId); - } - - NetworkAsa1000vMapVO networkAsaMap = _networkAsa1000vMapDao.findByAsa1000vId(asaResource.getId()); - if (networkAsaMap != null) { - throw new CloudRuntimeException(String.format("Cisco ASA 1000v appliance %s cannot be deleted as it is associated with guest network", asaResource)); - } - - _ciscoAsa1000vDao.remove(asaResourceId); - - return true; - } - - @Override - public List listCiscoAsa1000vResources(ListCiscoAsa1000vResourcesCmd cmd) { - Long physicalNetworkId = cmd.getPhysicalNetworkId(); - Long ciscoAsa1000vResourceId = cmd.getCiscoAsa1000vResourceId(); - List responseList = new ArrayList(); - - if (physicalNetworkId == null && ciscoAsa1000vResourceId == null) { - throw new InvalidParameterValueException("Either physical network Id or Asa 1000v device Id must be specified"); - } - - if (ciscoAsa1000vResourceId != null) { - CiscoAsa1000vDeviceVO ciscoAsa1000vResource = _ciscoAsa1000vDao.findById(ciscoAsa1000vResourceId); - if (ciscoAsa1000vResource == null) { - throw new InvalidParameterValueException("Could not find Cisco Asa 1000v device with id: " + ciscoAsa1000vResourceId); - } - responseList.add(ciscoAsa1000vResource); - } else { - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); - } - responseList = _ciscoAsa1000vDao.listByPhysicalNetwork(physicalNetworkId); - } - - return responseList; - } - - @Override - public CiscoAsa1000vDevice assignAsa1000vToNetwork(Network network) { - List asaList = _ciscoAsa1000vDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - for (CiscoAsa1000vDeviceVO asa : asaList) { - NetworkAsa1000vMapVO assignedToNetwork = _networkAsa1000vMapDao.findByAsa1000vId(asa.getId()); - if (assignedToNetwork == null) { - NetworkAsa1000vMapVO networkAsaMap = new NetworkAsa1000vMapVO(network.getId(), asa.getId()); - _networkAsa1000vMapDao.persist(networkAsaMap); - return asa; - } - } - return null; - } - - private void unassignAsa1000vFromNetwork(Network network) { - NetworkAsa1000vMapVO networkAsaMap = _networkAsa1000vMapDao.findByNetworkId(network.getId()); - if (networkAsaMap != null) { - _networkAsa1000vMapDao.remove(networkAsaMap.getId()); - } - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElementService.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElementService.java deleted file mode 100644 index 8a52893274fa..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/element/CiscoVnmcElementService.java +++ /dev/null @@ -1,39 +0,0 @@ -// 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.network.element; - -import java.util.List; - -import com.cloud.api.commands.AddCiscoVnmcResourceCmd; -import com.cloud.api.commands.DeleteCiscoVnmcResourceCmd; -import com.cloud.api.commands.ListCiscoVnmcResourcesCmd; -import com.cloud.api.response.CiscoVnmcResourceResponse; -import com.cloud.network.cisco.CiscoVnmcController; -import com.cloud.network.cisco.CiscoVnmcControllerVO; -import com.cloud.utils.component.PluggableService; - -public interface CiscoVnmcElementService extends PluggableService { - - public CiscoVnmcController addCiscoVnmcResource(AddCiscoVnmcResourceCmd cmd); - - public CiscoVnmcResourceResponse createCiscoVnmcResourceResponse(CiscoVnmcController ciscoVnmcResourceVO); - - boolean deleteCiscoVnmcResource(DeleteCiscoVnmcResourceCmd cmd); - - List listCiscoVnmcResources(ListCiscoVnmcResourcesCmd cmd); - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/resource/CiscoVnmcResource.java b/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/resource/CiscoVnmcResource.java deleted file mode 100644 index bbecdaf05e02..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/java/com/cloud/network/resource/CiscoVnmcResource.java +++ /dev/null @@ -1,759 +0,0 @@ -// 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.network.resource; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AssociateAsaWithLogicalEdgeFirewallCommand; -import com.cloud.agent.api.CleanupLogicalEdgeFirewallCommand; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.ConfigureNexusVsmForAsaCommand; -import com.cloud.agent.api.CreateLogicalEdgeFirewallCommand; -import com.cloud.agent.api.ExternalNetworkResourceUsageAnswer; -import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupExternalFirewallCommand; -import com.cloud.agent.api.routing.IpAssocAnswer; -import com.cloud.agent.api.routing.IpAssocCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.to.FirewallRuleTO; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.host.Host; -import com.cloud.network.cisco.CiscoVnmcConnectionImpl; -import com.cloud.network.rules.FirewallRule.TrafficType; -import com.cloud.resource.ServerResource; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; -import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.OperationType; -import com.cloud.utils.cisco.n1kv.vsm.VsmCommand.SwitchPortMode; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.exception.ExecutionException; -import com.cloud.utils.net.NetUtils; - -public class CiscoVnmcResource implements ServerResource { - - private String _name; - private String _zoneId; - private String _physicalNetworkId; - private String _ip; - private String _username; - private String _password; - private String _guid; - private Integer _numRetries = 1; - - private CiscoVnmcConnectionImpl _connection; - - public void setConnection(CiscoVnmcConnectionImpl connection) { - _connection = connection; - } - - protected Logger logger = LogManager.getLogger(getClass()); - - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof ReadyCommand) { - return execute((ReadyCommand)cmd); - } else if (cmd instanceof MaintainCommand) { - return execute((MaintainCommand)cmd); - } else if (cmd instanceof IpAssocCommand) { - return execute((IpAssocCommand)cmd); - } else if (cmd instanceof SetSourceNatCommand) { - return execute((SetSourceNatCommand)cmd); - } else if (cmd instanceof SetFirewallRulesCommand) { - return execute((SetFirewallRulesCommand)cmd); - } else if (cmd instanceof SetStaticNatRulesCommand) { - return execute((SetStaticNatRulesCommand)cmd); - } else if (cmd instanceof SetPortForwardingRulesCommand) { - return execute((SetPortForwardingRulesCommand)cmd); - } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { - return execute((ExternalNetworkResourceUsageCommand)cmd); - } else if (cmd instanceof CreateLogicalEdgeFirewallCommand) { - return execute((CreateLogicalEdgeFirewallCommand)cmd); - } else if (cmd instanceof CleanupLogicalEdgeFirewallCommand) { - return execute((CleanupLogicalEdgeFirewallCommand)cmd); - } else if (cmd instanceof ConfigureNexusVsmForAsaCommand) { - return execute((ConfigureNexusVsmForAsaCommand)cmd); - } else if (cmd instanceof AssociateAsaWithLogicalEdgeFirewallCommand) { - return execute((AssociateAsaWithLogicalEdgeFirewallCommand)cmd); - } else { - return Answer.createUnsupportedCommandAnswer(cmd); - } - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - try { - _name = (String)params.get("name"); - if (_name == null) { - throw new ConfigurationException("Unable to find name"); - } - - _zoneId = (String)params.get("zoneId"); - if (_zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - _physicalNetworkId = (String)params.get("physicalNetworkId"); - if (_physicalNetworkId == null) { - throw new ConfigurationException("Unable to find physical network id in the configuration parameters"); - } - - _ip = (String)params.get("ip"); - if (_ip == null) { - throw new ConfigurationException("Unable to find IP"); - } - - _username = (String)params.get("username"); - if (_username == null) { - throw new ConfigurationException("Unable to find username"); - } - - _password = (String)params.get("password"); - if (_password == null) { - throw new ConfigurationException("Unable to find password"); - } - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - _numRetries = NumbersUtil.parseInt((String)params.get("numretries"), 1); - - NumbersUtil.parseInt((String)params.get("timeout"), 300); - - // Open a socket and login - _connection = new CiscoVnmcConnectionImpl(_ip, _username, _password); - if (!refreshVnmcConnection()) { - throw new ConfigurationException("Unable to connect to VNMC, check if ip/username/password is valid."); - } - - return true; - } catch (Exception e) { - throw new ConfigurationException(e.getMessage()); - } - - } - - @Override - public StartupCommand[] initialize() { - StartupExternalFirewallCommand cmd = new StartupExternalFirewallCommand(); - cmd.setName(_name); - cmd.setDataCenter(_zoneId); - cmd.setPod(""); - cmd.setPrivateIpAddress(_ip); - cmd.setStorageIpAddress(""); - cmd.setVersion(CiscoVnmcResource.class.getPackage().getImplementationVersion()); - cmd.setGuid(_guid); - return new StartupCommand[] {cmd}; - } - - @Override - public Host.Type getType() { - return Host.Type.ExternalFirewall; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public PingCommand getCurrentStatus(final long id) { - if (!refreshVnmcConnection()) { - return null; - } - return new PingCommand(Host.Type.ExternalFirewall, id); - } - - @Override - public void disconnected() { - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - return; - } - - private Answer execute(ReadyCommand cmd) { - return new ReadyAnswer(cmd); - } - - private Answer execute(MaintainCommand cmd) { - return new MaintainAnswer(cmd); - } - - private ExternalNetworkResourceUsageAnswer execute(ExternalNetworkResourceUsageCommand cmd) { - return new ExternalNetworkResourceUsageAnswer(cmd); - } - - /* - * Login - */ - private boolean refreshVnmcConnection() { - boolean ret = false; - try { - ret = _connection.login(); - } catch (ExecutionException ex) { - logger.error("Login to Vnmc failed", ex); - } - return ret; - } - - private synchronized Answer execute(IpAssocCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(IpAssocCommand cmd, int numRetries) { - String[] results = new String[cmd.getIpAddresses().length]; - return new IpAssocAnswer(cmd, results); - } - - private String[] getIpRangeFromCidr(String cidr) { - String[] result = new String[2]; - String[] cidrData = cidr.split("\\/"); - assert (cidrData.length == 2) : "Something is wrong with source cidr " + cidr; - long size = Long.parseLong(cidrData[1]); - result[0] = cidrData[0]; - result[1] = cidrData[0]; - if (size < 32) { - result[0] = NetUtils.getIpRangeStartIpFromCidr(cidrData[0], size); - result[1] = NetUtils.getIpRangeEndIpFromCidr(cidrData[0], size); - } - return result; - } - - /* - * Source NAT - */ - private synchronized Answer execute(SetSourceNatCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetSourceNatCommand cmd, int numRetries) { - String vlanId = cmd.getContextParam(NetworkElementCommand.GUEST_VLAN_TAG); - String tenant = "vlan-" + vlanId; - String policyIdentifier = cmd.getIpAddress().getPublicIp().replace('.', '-'); - try { - if (!_connection.createTenantVDCNatPolicySet(tenant)) { - throw new ExecutionException("Failed to create NAT policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCSourceNatPolicy(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to create source NAT policy in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCSourceNatPolicyRef(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to associate source NAT policy with NAT policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCSourceNatIpPool(tenant, policyIdentifier, cmd.getIpAddress().getPublicIp())) { - throw new ExecutionException("Failed to create source NAT ip pool in VNMC for guest network with vlan " + vlanId); - } - - String[] ipRange = getIpRangeFromCidr(cmd.getContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR)); - if (!_connection.createTenantVDCSourceNatRule(tenant, policyIdentifier, ipRange[0], ipRange[1])) { - throw new ExecutionException("Failed to create source NAT rule in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.associateNatPolicySet(tenant)) { - throw new ExecutionException("Failed to associate source NAT policy set with edge security profile in VNMC for guest network with vlan " + vlanId); - } - } catch (ExecutionException e) { - String msg = "SetSourceNatCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - /* - * Firewall rule - */ - private synchronized Answer execute(SetFirewallRulesCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetFirewallRulesCommand cmd, int numRetries) { - String vlanId = cmd.getContextParam(NetworkElementCommand.GUEST_VLAN_TAG); - String tenant = "vlan-" + vlanId; - - FirewallRuleTO[] rules = cmd.getRules(); - Map> publicIpRulesMap = new HashMap>(); - for (FirewallRuleTO rule : rules) { - String publicIp = rule.getSrcIp(); - if (!publicIpRulesMap.containsKey(publicIp)) { - List publicIpRulesList = new ArrayList(); - publicIpRulesMap.put(publicIp, publicIpRulesList); - } - publicIpRulesMap.get(publicIp).add(rule); - } - - try { - if (!_connection.createTenantVDCAclPolicySet(tenant, true)) { - throw new ExecutionException("Failed to create ACL ingress policy set in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicySet(tenant, false)) { - throw new ExecutionException("Failed to create ACL egress policy set in VNMC for guest network with vlan " + vlanId); - } - - for (String publicIp : publicIpRulesMap.keySet()) { - String policyIdentifier = publicIp.replace('.', '-'); - - if (!_connection.createTenantVDCAclPolicy(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to create ACL policy in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicyRef(tenant, policyIdentifier, true)) { - throw new ExecutionException("Failed to associate ACL policy with ACL ingress policy set in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicyRef(tenant, policyIdentifier, false)) { - throw new ExecutionException("Failed to associate ACL policy with ACL egress policy set in VNMC for guest network with vlan " + vlanId); - } - - for (FirewallRuleTO rule : publicIpRulesMap.get(publicIp)) { - if (rule.revoked()) { - if (!_connection.deleteTenantVDCAclRule(tenant, rule.getId(), policyIdentifier)) { - throw new ExecutionException("Failed to delete ACL rule in VNMC for guest network with vlan " + vlanId); - } - } else { - String[] externalIpRange = getIpRangeFromCidr(rule.getSourceCidrList().get(0)); - if (rule.getTrafficType() == TrafficType.Ingress) { - if (!rule.getProtocol().equalsIgnoreCase("icmp") && rule.getSrcPortRange() != null) { - if (!_connection.createTenantVDCIngressAclRule(tenant, rule.getId(), policyIdentifier, rule.getProtocol().toUpperCase(), - externalIpRange[0], externalIpRange[1], Integer.toString(rule.getSrcPortRange()[0]), Integer.toString(rule.getSrcPortRange()[1]))) { - throw new ExecutionException("Failed to create ACL ingress rule in VNMC for guest network with vlan " + vlanId); - } - } else { - if (!_connection.createTenantVDCIngressAclRule(tenant, rule.getId(), policyIdentifier, rule.getProtocol().toUpperCase(), - externalIpRange[0], externalIpRange[1])) { - throw new ExecutionException("Failed to create ACL ingress rule in VNMC for guest network with vlan " + vlanId); - } - } - } else { - if ((rule.getProtocol().equalsIgnoreCase("tcp") || rule.getProtocol().equalsIgnoreCase("udp")) && rule.getSrcPortRange() != null) { - if (!_connection.createTenantVDCEgressAclRule(tenant, rule.getId(), policyIdentifier, rule.getProtocol().toUpperCase(), - externalIpRange[0], externalIpRange[1], Integer.toString(rule.getSrcPortRange()[0]), Integer.toString(rule.getSrcPortRange()[1]))) { - throw new ExecutionException("Failed to create ACL egress rule in VNMC for guest network with vlan " + vlanId); - } - } else { - if (!_connection.createTenantVDCEgressAclRule(tenant, rule.getId(), policyIdentifier, rule.getProtocol().toUpperCase(), - externalIpRange[0], externalIpRange[1])) { - throw new ExecutionException("Failed to create ACL egress rule in VNMC for guest network with vlan " + vlanId); - } - } - } - } - } - } - - if (!_connection.associateAclPolicySet(tenant)) { - throw new ExecutionException("Failed to associate ACL policy set with edge security profile in VNMC for guest network with vlan " + vlanId); - } - } catch (ExecutionException e) { - String msg = "SetFirewallRulesCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - /* - * Static NAT - */ - private synchronized Answer execute(SetStaticNatRulesCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetStaticNatRulesCommand cmd, int numRetries) { - String vlanId = cmd.getContextParam(NetworkElementCommand.GUEST_VLAN_TAG); - String tenant = "vlan-" + vlanId; - - StaticNatRuleTO[] rules = cmd.getRules(); - Map> publicIpRulesMap = new HashMap>(); - for (StaticNatRuleTO rule : rules) { - String publicIp = rule.getSrcIp(); - if (!publicIpRulesMap.containsKey(publicIp)) { - List publicIpRulesList = new ArrayList(); - publicIpRulesMap.put(publicIp, publicIpRulesList); - } - publicIpRulesMap.get(publicIp).add(rule); - } - - try { - if (!_connection.createTenantVDCNatPolicySet(tenant)) { - throw new ExecutionException("Failed to create NAT policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCAclPolicySet(tenant, true)) { - throw new ExecutionException("Failed to create ACL ingress policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCAclPolicySet(tenant, false)) { - throw new ExecutionException("Failed to create ACL egress policy set in VNMC for guest network with vlan " + vlanId); - } - - for (String publicIp : publicIpRulesMap.keySet()) { - String policyIdentifier = publicIp.replace('.', '-'); - - if (!_connection.createTenantVDCDNatPolicy(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to create DNAT policy in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCDNatPolicyRef(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to associate DNAT policy with NAT policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCAclPolicy(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to create ACL policy in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicyRef(tenant, policyIdentifier, true)) { - throw new ExecutionException("Failed to associate ACL policy with ACL ingress policy set in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicyRef(tenant, policyIdentifier, false)) { - throw new ExecutionException("Failed to associate ACL policy with ACL egress policy set in VNMC for guest network with vlan " + vlanId); - } - - for (StaticNatRuleTO rule : publicIpRulesMap.get(publicIp)) { - if (rule.revoked()) { - if (!_connection.deleteTenantVDCDNatRule(tenant, rule.getId(), policyIdentifier)) { - throw new ExecutionException("Failed to delete DNAT rule in VNMC for guest network with vlan " + vlanId); - } - } else { - if (!_connection.createTenantVDCDNatIpPool(tenant, Long.toString(rule.getId()), rule.getDstIp())) { - throw new ExecutionException("Failed to create DNAT ip pool in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCDNatRule(tenant, rule.getId(), policyIdentifier, rule.getSrcIp())) { - throw new ExecutionException("Failed to create DNAT rule in VNMC for guest network with vlan " + vlanId); - } - } - } - } - - if (!_connection.associateAclPolicySet(tenant)) { - throw new ExecutionException("Failed to associate source NAT policy set with edge security profile in VNMC for guest network with vlan " + vlanId); - } - } catch (ExecutionException e) { - String msg = "SetStaticNatRulesCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - /* - * PF - */ - private synchronized Answer execute(SetPortForwardingRulesCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(SetPortForwardingRulesCommand cmd, int numRetries) { - String vlanId = cmd.getContextParam(NetworkElementCommand.GUEST_VLAN_TAG); - String tenant = "vlan-" + vlanId; - - PortForwardingRuleTO[] rules = cmd.getRules(); - Map> publicIpRulesMap = new HashMap>(); - for (PortForwardingRuleTO rule : rules) { - String publicIp = rule.getSrcIp(); - if (!publicIpRulesMap.containsKey(publicIp)) { - List publicIpRulesList = new ArrayList(); - publicIpRulesMap.put(publicIp, publicIpRulesList); - } - publicIpRulesMap.get(publicIp).add(rule); - } - - try { - if (!_connection.createTenantVDCNatPolicySet(tenant)) { - throw new ExecutionException("Failed to create NAT policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCAclPolicySet(tenant, true)) { - throw new ExecutionException("Failed to create ACL ingress policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCAclPolicySet(tenant, false)) { - throw new ExecutionException("Failed to create ACL egress policy set in VNMC for guest network with vlan " + vlanId); - } - - for (String publicIp : publicIpRulesMap.keySet()) { - String policyIdentifier = publicIp.replace('.', '-'); - - if (!_connection.createTenantVDCPFPolicy(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to create PF policy in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCPFPolicyRef(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to associate PF policy with NAT policy set in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCAclPolicy(tenant, policyIdentifier)) { - throw new ExecutionException("Failed to create ACL policy in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicyRef(tenant, policyIdentifier, true)) { - throw new ExecutionException("Failed to associate ACL policy with ACL ingress policy set in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCAclPolicyRef(tenant, policyIdentifier, false)) { - throw new ExecutionException("Failed to associate ACL policy with ACL egress policy set in VNMC for guest network with vlan " + vlanId); - } - - for (PortForwardingRuleTO rule : publicIpRulesMap.get(publicIp)) { - if (rule.revoked()) { - if (!_connection.deleteTenantVDCPFRule(tenant, rule.getId(), policyIdentifier)) { - throw new ExecutionException("Failed to delete PF rule in VNMC for guest network with vlan " + vlanId); - } - } else { - if (!_connection.createTenantVDCPFIpPool(tenant, Long.toString(rule.getId()), rule.getDstIp())) { - throw new ExecutionException("Failed to create PF ip pool in VNMC for guest network with vlan " + vlanId); - } - if (!_connection.createTenantVDCPFPortPool(tenant, Long.toString(rule.getId()), Integer.toString(rule.getDstPortRange()[0]), - Integer.toString(rule.getDstPortRange()[1]))) { - throw new ExecutionException("Failed to create PF port pool in VNMC for guest network with vlan " + vlanId); - } - - if (!_connection.createTenantVDCPFRule(tenant, rule.getId(), policyIdentifier, rule.getProtocol().toUpperCase(), rule.getSrcIp(), - Integer.toString(rule.getSrcPortRange()[0]), Integer.toString(rule.getSrcPortRange()[1]))) { - throw new ExecutionException("Failed to create PF rule in VNMC for guest network with vlan " + vlanId); - } - } - } - } - - if (!_connection.associateAclPolicySet(tenant)) { - throw new ExecutionException("Failed to associate source NAT policy set with edge security profile in VNMC for guest network with vlan " + vlanId); - } - } catch (ExecutionException e) { - String msg = "SetPortForwardingRulesCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - /* - * Logical edge firewall - */ - private synchronized Answer execute(CreateLogicalEdgeFirewallCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private void createEdgeDeviceProfile(String tenant, List gateways, Long vlanId) throws ExecutionException { - // create edge device profile - if (!_connection.createTenantVDCEdgeDeviceProfile(tenant)) - throw new ExecutionException("Failed to create tenant edge device profile in VNMC for guest network with vlan " + vlanId); - - // create edge static route policy - if (!_connection.createTenantVDCEdgeStaticRoutePolicy(tenant)) - throw new ExecutionException("Failed to create tenant edge static route policy in VNMC for guest network with vlan " + vlanId); - - // create edge static route for all gateways - for (String gateway : gateways) { - if (!_connection.createTenantVDCEdgeStaticRoute(tenant, gateway, "0.0.0.0", "0.0.0.0")) - throw new ExecutionException("Failed to create tenant edge static route in VNMC for guest network with vlan " + vlanId); - } - - // associate edge - if (!_connection.associateTenantVDCEdgeStaticRoutePolicy(tenant)) - throw new ExecutionException("Failed to associate edge static route policy with edge device profile in VNMC for guest network with vlan " + vlanId); - } - - private Answer execute(CreateLogicalEdgeFirewallCommand cmd, int numRetries) { - String tenant = "vlan-" + cmd.getVlanId(); - try { - // create tenant - if (!_connection.createTenant(tenant)) - throw new ExecutionException("Failed to create tenant in VNMC for guest network with vlan " + cmd.getVlanId()); - - // create tenant VDC - if (!_connection.createTenantVDC(tenant)) - throw new ExecutionException("Failed to create tenant VDC in VNMC for guest network with vlan " + cmd.getVlanId()); - - // create edge security profile - if (!_connection.createTenantVDCEdgeSecurityProfile(tenant)) - throw new ExecutionException("Failed to create tenant edge security profile in VNMC for guest network with vlan " + cmd.getVlanId()); - - // create edge device profile and associated route - createEdgeDeviceProfile(tenant, cmd.getPublicGateways(), cmd.getVlanId()); - - // create logical edge firewall - if (!_connection.createEdgeFirewall(tenant, cmd.getPublicIp(), cmd.getInternalIp(), cmd.getPublicSubnet(), cmd.getInternalSubnet())) - throw new ExecutionException("Failed to create edge firewall in VNMC for guest network with vlan " + cmd.getVlanId()); - } catch (ExecutionException e) { - String msg = "CreateLogicalEdgeFirewallCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - /* - * Create vservice node and update inside port profile for ASA appliance in VSM - */ - private synchronized Answer execute(ConfigureNexusVsmForAsaCommand cmd) { - return execute(cmd, _numRetries); - } - - private Answer execute(ConfigureNexusVsmForAsaCommand cmd, int numRetries) { - String vlanId = Long.toString(cmd.getVlanId()); - NetconfHelper helper = null; - List> params = new ArrayList>(); - params.add(new Pair(OperationType.addvlanid, vlanId)); - try { - helper = new NetconfHelper(cmd.getVsmIp(), cmd.getVsmUsername(), cmd.getVsmPassword()); - logger.debug("Connected to Cisco VSM " + cmd.getVsmIp()); - helper.addVServiceNode(vlanId, cmd.getIpAddress()); - logger.debug("Created vservice node for ASA appliance in Cisco VSM for vlan " + vlanId); - helper.updatePortProfile(cmd.getAsaInPortProfile(), SwitchPortMode.access, params); - logger.debug("Updated inside port profile for ASA appliance in Cisco VSM with new vlan " + vlanId); - } catch (CloudRuntimeException e) { - String msg = "ConfigureVSMForASACommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } finally { - if( helper != null) { - helper.disconnect(); - } - } - return new Answer(cmd, true, "Success"); - } - - /* - * Associates ASA 1000v with logical edge firewall in VNMC - */ - private synchronized Answer execute(AssociateAsaWithLogicalEdgeFirewallCommand cmd) { - return execute(cmd, _numRetries); - } - - private Answer execute(AssociateAsaWithLogicalEdgeFirewallCommand cmd, int numRetries) { - String tenant = "vlan-" + cmd.getVlanId(); - try { - Map availableAsaAppliances = _connection.listUnAssocAsa1000v(); - if (availableAsaAppliances.isEmpty()) { - throw new ExecutionException("No ASA 1000v available to associate with logical edge firewall for guest vlan " + cmd.getVlanId()); - } - - String asaInstanceDn = availableAsaAppliances.get(cmd.getAsaMgmtIp()); - if (asaInstanceDn == null) { - throw new ExecutionException("Requested ASA 1000v (" + cmd.getAsaMgmtIp() + ") is not available"); - } - - if (!_connection.assignAsa1000v(tenant, asaInstanceDn)) { - throw new ExecutionException("Failed to associate ASA 1000v (" + cmd.getAsaMgmtIp() + ") with logical edge firewall for guest vlan " + cmd.getVlanId()); - } - } catch (ExecutionException e) { - String msg = "AssociateAsaWithLogicalEdgeFirewallCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - /* - * Cleanup - */ - private synchronized Answer execute(CleanupLogicalEdgeFirewallCommand cmd) { - refreshVnmcConnection(); - return execute(cmd, _numRetries); - } - - private Answer execute(CleanupLogicalEdgeFirewallCommand cmd, int numRetries) { - String tenant = "vlan-" + cmd.getVlanId(); - try { - _connection.deleteTenant(tenant); - } catch (ExecutionException e) { - String msg = "CleanupLogicalEdgeFirewallCommand failed due to " + e.getMessage(); - logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd, true, "Success"); - } - - @Override - public void setName(String name) { - // TODO Auto-generated method stub - } - - @Override - public void setConfigParams(Map params) { - // TODO Auto-generated method stub - } - - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void setRunLevel(int level) { - // TODO Auto-generated method stub - } - -} diff --git a/plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/module.properties b/plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/module.properties deleted file mode 100644 index abaf57557370..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=cisco-vnmc -parent=network diff --git a/plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml b/plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml deleted file mode 100644 index 916a3d547af1..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/resources/META-INF/cloudstack/cisco-vnmc/spring-cisco-vnmc-context.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/assoc-asa1000v.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/assoc-asa1000v.xml deleted file mode 100644 index b0249db741be..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/assoc-asa1000v.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-acl-policy-set.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-acl-policy-set.xml deleted file mode 100755 index cd6d3073ea05..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-acl-policy-set.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-policy.xml deleted file mode 100644 index e866f51e366b..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-policy.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-server.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-server.xml deleted file mode 100644 index 930e4ec77a2f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-dhcp-server.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-nat-policy-set.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-nat-policy-set.xml deleted file mode 100644 index 6d67c31c5d61..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-nat-policy-set.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-route-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-route-policy.xml deleted file mode 100644 index 8884a1b96869..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/associate-route-policy.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-ref.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-ref.xml deleted file mode 100755 index cc076668f9e4..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-ref.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-set.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-set.xml deleted file mode 100755 index 3a554843204f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy-set.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy.xml deleted file mode 100755 index 1e088d566fdd..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-policy.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-dnat.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-dnat.xml deleted file mode 100755 index 57d692b534f9..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-dnat.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-pf.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-pf.xml deleted file mode 100755 index eebf1382a0a0..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-acl-rule-for-pf.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dhcp-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dhcp-policy.xml deleted file mode 100644 index bf3a60c67b95..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dhcp-policy.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dnat-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dnat-rule.xml deleted file mode 100755 index aa434795c1e4..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-dnat-rule.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-profile.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-profile.xml deleted file mode 100644 index c4bdd0261869..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-profile.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route-policy.xml deleted file mode 100644 index 69f4a5f7bfd7..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route-policy.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route.xml deleted file mode 100644 index 126c188f9791..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-device-route.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-firewall.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-firewall.xml deleted file mode 100644 index ba430bf6b9d7..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-firewall.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-security-profile.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-security-profile.xml deleted file mode 100644 index 29f7111c56a4..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-edge-security-profile.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-egress-acl-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-egress-acl-rule.xml deleted file mode 100755 index 81546bace9a5..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-egress-acl-rule.xml +++ /dev/null @@ -1,168 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-no-protocol-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-no-protocol-rule.xml deleted file mode 100755 index 1ad40b69221b..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-no-protocol-rule.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-rule.xml deleted file mode 100755 index 1d4e532a161d..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-egress-acl-rule.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-ingress-acl-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-ingress-acl-rule.xml deleted file mode 100755 index e368dbc73f43..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-generic-ingress-acl-rule.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ingress-acl-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ingress-acl-rule.xml deleted file mode 100755 index 81546bace9a5..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ingress-acl-rule.xml +++ /dev/null @@ -1,168 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ip-pool.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ip-pool.xml deleted file mode 100755 index 8bada00ed9ca..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-ip-pool.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-ref.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-ref.xml deleted file mode 100755 index ec0e2d74064b..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-ref.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-set.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-set.xml deleted file mode 100644 index 2e2c63e85f15..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy-set.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy.xml deleted file mode 100755 index ca8a3eeb1700..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-nat-policy.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-pf-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-pf-rule.xml deleted file mode 100755 index 275755de4144..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-pf-rule.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-port-pool.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-port-pool.xml deleted file mode 100755 index 58b848b818ad..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-port-pool.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-pool.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-pool.xml deleted file mode 100644 index b3951fc09538..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-pool.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-rule.xml deleted file mode 100644 index 131bcdfbf5b6..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-source-nat-rule.xml +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-tenant.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-tenant.xml deleted file mode 100644 index 085b7a2e533f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-tenant.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-vdc.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-vdc.xml deleted file mode 100644 index 4cb805ecf7e9..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/create-vdc.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy-set.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy-set.xml deleted file mode 100755 index 9dae29d7d145..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy-set.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy.xml deleted file mode 100755 index 6ba4034768f0..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-acl-policy.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-firewall.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-firewall.xml deleted file mode 100755 index 149efe515e11..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-firewall.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-security-profile.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-security-profile.xml deleted file mode 100755 index 23458593eb62..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-edge-security-profile.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy-set.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy-set.xml deleted file mode 100755 index 799f6d439573..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy-set.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy.xml deleted file mode 100755 index 83946f976814..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-nat-policy.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-rule.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-rule.xml deleted file mode 100755 index f9030710ec4c..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-rule.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-tenant.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-tenant.xml deleted file mode 100755 index 0dbb23d0cbfe..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-tenant.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-vdc.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-vdc.xml deleted file mode 100755 index 4c9b80694c3b..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/delete-vdc.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/disassoc-asa1000v.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/disassoc-asa1000v.xml deleted file mode 100755 index 06d0f41fff83..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/disassoc-asa1000v.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-acl-policies.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-acl-policies.xml deleted file mode 100755 index 9ddc58a46828..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-acl-policies.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-children.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-children.xml deleted file mode 100755 index a1bcf071557a..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-children.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-nat-policies.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-nat-policies.xml deleted file mode 100755 index c3f8f0103236..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-nat-policies.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-policyrefs-in-policyset.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-policyrefs-in-policyset.xml deleted file mode 100755 index fa54f5cf9865..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-policyrefs-in-policyset.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-tenants.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-tenants.xml deleted file mode 100644 index 63ae848b3e1f..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-tenants.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-unassigned-asa1000v.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-unassigned-asa1000v.xml deleted file mode 100644 index 539f330da8a7..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/list-unassigned-asa1000v.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - diff --git a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/login.xml b/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/login.xml deleted file mode 100644 index 8e1c435ea153..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/main/scripts/network/cisco/login.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/cisco/CiscoVnmcConnectionTest.java b/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/cisco/CiscoVnmcConnectionTest.java deleted file mode 100644 index 46e18a0e83fe..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/cisco/CiscoVnmcConnectionTest.java +++ /dev/null @@ -1,148 +0,0 @@ -// 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.network.cisco; - -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import com.cloud.utils.exception.ExecutionException; - -@Ignore("Requires actual VNMC to connect to") -public class CiscoVnmcConnectionTest { - static CiscoVnmcConnectionImpl connection; - static String tenantName = "TenantE"; - static Map fwDns = null; - - @BeforeClass - public static void setUpClass() throws Exception { - connection = new CiscoVnmcConnectionImpl("10.223.56.5", "admin", "C1sco123"); - boolean response = connection.login(); - assertTrue(response); - } - - @Test - public void testLogin() throws ExecutionException { - boolean response = connection.login(); - assertTrue(response); - } - - @Test - public void testCreateTenant() throws ExecutionException { - boolean response = connection.createTenant(tenantName); - assertTrue(response); - } - - @Test - public void testCreateTenantVDC() throws ExecutionException { - boolean response = connection.createTenantVDC(tenantName); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCEdgeDeviceProfile() throws ExecutionException { - boolean response = connection.createTenantVDCEdgeDeviceProfile(tenantName); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCEdgeDeviceRoutePolicy() throws ExecutionException { - boolean response = connection.createTenantVDCEdgeStaticRoutePolicy(tenantName); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCEdgeDeviceRoute() throws ExecutionException { - boolean response = connection.createTenantVDCEdgeStaticRoute(tenantName, "10.223.136.1", "0.0.0.0", "0.0.0.0"); - assertTrue(response); - } - - @Test - public void testAssociateRoutePolicyWithEdgeProfile() throws ExecutionException { - boolean response = connection.associateTenantVDCEdgeStaticRoutePolicy(tenantName); - assertTrue(response); - } - - @Test - public void testAssociateTenantVDCEdgeDhcpPolicy() throws ExecutionException { - boolean response = connection.associateTenantVDCEdgeDhcpPolicy(tenantName, "Edge_Inside"); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCEdgeDhcpPolicy() throws ExecutionException { - boolean response = connection.createTenantVDCEdgeDhcpPolicy(tenantName, "10.1.1.2", "10.1.1.254", "255.255.255.0", "4.4.4.4", tenantName + ".net"); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCEdgeSecurityProfile() throws ExecutionException { - boolean response = connection.createTenantVDCEdgeSecurityProfile(tenantName); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCSourceNatIpPool() throws ExecutionException { - boolean response = connection.createTenantVDCSourceNatIpPool(tenantName, "1", "10.223.136.10"); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCSourceNatPolicy() throws ExecutionException { - boolean response = connection.createTenantVDCSourceNatPolicy(tenantName, "1"); - assertTrue(response); - response = connection.createTenantVDCSourceNatPolicyRef(tenantName, "1"); - assertTrue(response); - response = connection.createTenantVDCSourceNatRule(tenantName, "1", "10.1.1.2", "10.1.1.254"); - assertTrue(response); - } - - @Test - public void testCreateTenantVDCNatPolicySet() throws ExecutionException { - boolean response = connection.createTenantVDCNatPolicySet(tenantName); - assertTrue(response); - } - - @Test - public void testAssociateNatPolicySet() throws ExecutionException { - boolean response = connection.associateNatPolicySet(tenantName); - assertTrue(response); - } - - @Test - public void testCreateEdgeFirewall() throws ExecutionException { - boolean response = connection.createEdgeFirewall(tenantName, "44.44.44.44", "192.168.1.1", "255.255.255.0", "255.255.255.192"); - assertTrue(response); - } - - @Test - public void testListUnassocAsa1000v() throws ExecutionException { - Map response = connection.listUnAssocAsa1000v(); - assertTrue(response.size() >= 0); - fwDns = response; - } - - @Test - public void assocAsa1000v() throws ExecutionException { - boolean result = connection.assignAsa1000v(tenantName, fwDns.entrySet().iterator().next().getValue()); - assertTrue(result); - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/element/CiscoVnmcElementTest.java b/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/element/CiscoVnmcElementTest.java deleted file mode 100644 index b013acd0f3e5..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/element/CiscoVnmcElementTest.java +++ /dev/null @@ -1,409 +0,0 @@ -// 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.network.element; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.naming.ConfigurationException; - -import org.junit.Before; -import org.junit.Test; - -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.AssociateAsaWithLogicalEdgeFirewallCommand; -import com.cloud.agent.api.CleanupLogicalEdgeFirewallCommand; -import com.cloud.agent.api.ConfigureNexusVsmForAsaCommand; -import com.cloud.agent.api.CreateLogicalEdgeFirewallCommand; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.ClusterVSMMapVO; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.ClusterVSMMapDao; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.domain.Domain; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.CiscoNexusVSMDeviceVO; -import com.cloud.network.IpAddress; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.cisco.CiscoAsa1000vDeviceVO; -import com.cloud.network.cisco.CiscoVnmcControllerVO; -import com.cloud.network.cisco.NetworkAsa1000vMapVO; -import com.cloud.network.dao.CiscoAsa1000vDao; -import com.cloud.network.dao.CiscoNexusVSMDeviceDao; -import com.cloud.network.dao.CiscoVnmcDao; -import com.cloud.network.dao.NetworkAsa1000vMapDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNat; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.user.Account; -import com.cloud.utils.db.EntityManager; -import com.cloud.utils.net.Ip; -import com.cloud.vm.ReservationContext; - -public class CiscoVnmcElementTest { - - CiscoVnmcElement _element = new CiscoVnmcElement(); - AgentManager _agentMgr = mock(AgentManager.class); - NetworkOrchestrationService _networkMgr = mock(NetworkOrchestrationService.class); - NetworkModel _networkModel = mock(NetworkModel.class); - HostDao _hostDao = mock(HostDao.class); - NetworkServiceMapDao _ntwkSrvcDao = mock(NetworkServiceMapDao.class); - ConfigurationManager _configMgr = mock(ConfigurationManager.class); - CiscoVnmcDao _ciscoVnmcDao = mock(CiscoVnmcDao.class); - CiscoAsa1000vDao _ciscoAsa1000vDao = mock(CiscoAsa1000vDao.class); - NetworkAsa1000vMapDao _networkAsa1000vMapDao = mock(NetworkAsa1000vMapDao.class); - ClusterVSMMapDao _clusterVsmMapDao = mock(ClusterVSMMapDao.class); - CiscoNexusVSMDeviceDao _vsmDeviceDao = mock(CiscoNexusVSMDeviceDao.class); - VlanDao _vlanDao = mock(VlanDao.class); - IpAddressManager _ipAddrMgr = mock(IpAddressManager.class); - EntityManager _entityMgr = mock(EntityManager.class); - - @Before - public void setUp() throws ConfigurationException { - _element._resourceMgr = mock(ResourceManager.class); - _element._agentMgr = _agentMgr; - _element._networkMgr = _networkMgr; - _element._networkModel = _networkModel; - _element._hostDao = _hostDao; - _element._configMgr = _configMgr; - _element._ciscoVnmcDao = _ciscoVnmcDao; - _element._ciscoAsa1000vDao = _ciscoAsa1000vDao; - _element._networkAsa1000vMapDao = _networkAsa1000vMapDao; - _element._clusterVsmMapDao = _clusterVsmMapDao; - _element._vsmDeviceDao = _vsmDeviceDao; - _element._vlanDao = _vlanDao; - _element._entityMgr = _entityMgr; - - // Standard responses - when(_networkModel.isProviderForNetwork(Provider.CiscoVnmc, 1L)).thenReturn(true); - - _element.configure("CiscoVnmcTestElement", Collections. emptyMap()); - } - - @Test - public void canHandleTest() { - Network network = mock(Network.class); - when(network.getId()).thenReturn(1L); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - assertTrue(_element.canHandle(network)); - - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.UnDecided); - assertFalse(_element.canHandle(network)); - } - - @Test - public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - URI uri = URI.create("vlan://123"); - - Network network = mock(Network.class); - when(network.getId()).thenReturn(1L); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - when(network.getDataCenterId()).thenReturn(1L); - when(network.getGateway()).thenReturn("1.1.1.1"); - when(network.getBroadcastUri()).thenReturn(uri); - when(network.getCidr()).thenReturn("1.1.1.0/24"); - - NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(1L); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - DeployDestination dest = mock(DeployDestination.class); - - Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("d1"); - Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("a1"); - ReservationContext context = mock(ReservationContext.class); - when(context.getDomain()).thenReturn(dom); - when(context.getAccount()).thenReturn(acc); - - DataCenter dc = mock(DataCenter.class); - when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); - when(_entityMgr.findById(DataCenter.class, network.getDataCenterId())).thenReturn(dc); - - List devices = new ArrayList(); - devices.add(mock(CiscoVnmcControllerVO.class)); - when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices); - - CiscoAsa1000vDeviceVO asaVO = mock(CiscoAsa1000vDeviceVO.class); - when(asaVO.getInPortProfile()).thenReturn("foo"); - when(asaVO.getManagementIp()).thenReturn("1.2.3.4"); - - List asaList = new ArrayList(); - asaList.add(asaVO); - when(_ciscoAsa1000vDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(asaList); - - when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class)); - when(_networkAsa1000vMapDao.findByAsa1000vId(anyLong())).thenReturn(null); - when(_networkAsa1000vMapDao.persist(any(NetworkAsa1000vMapVO.class))).thenReturn(mock(NetworkAsa1000vMapVO.class)); - - when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.CiscoVnmc)).thenReturn(true); - - ClusterVSMMapVO clusterVsmMap = mock(ClusterVSMMapVO.class); - when(_clusterVsmMapDao.findByClusterId(anyLong())).thenReturn(clusterVsmMap); - - CiscoNexusVSMDeviceVO vsmDevice = mock(CiscoNexusVSMDeviceVO.class); - when(vsmDevice.getUserName()).thenReturn("foo"); - when(vsmDevice.getPassword()).thenReturn("bar"); - when(vsmDevice.getipaddr()).thenReturn("1.2.3.4"); - when(_vsmDeviceDao.findById(anyLong())).thenReturn(vsmDevice); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(1L); - when(_hostDao.findById(anyLong())).thenReturn(hostVO); - - Ip ip = mock(Ip.class); - when(ip.addr()).thenReturn("1.2.3.4"); - - PublicIp publicIp = mock(PublicIp.class); - when(publicIp.getAddress()).thenReturn(ip); - when(publicIp.getState()).thenReturn(IpAddress.State.Releasing); - when(publicIp.getAccountId()).thenReturn(1L); - when(publicIp.isSourceNat()).thenReturn(true); - when(publicIp.getVlanTag()).thenReturn("123"); - when(publicIp.getGateway()).thenReturn("1.1.1.1"); - when(publicIp.getNetmask()).thenReturn("1.1.1.1"); - when(publicIp.getMacAddress()).thenReturn(null); - when(publicIp.isOneToOneNat()).thenReturn(true); - when(_ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(acc, network)).thenReturn(publicIp); - - VlanVO vlanVO = mock(VlanVO.class); - when(vlanVO.getVlanGateway()).thenReturn("1.1.1.1"); - List vlanVOList = new ArrayList(); - when(_vlanDao.listVlansByPhysicalNetworkId(network.getPhysicalNetworkId())).thenReturn(vlanVOList); - - Answer answer = mock(Answer.class); - when(answer.getResult()).thenReturn(true); - - when(_agentMgr.easySend(anyLong(), any(CreateLogicalEdgeFirewallCommand.class))).thenReturn(answer); - when(_agentMgr.easySend(anyLong(), any(ConfigureNexusVsmForAsaCommand.class))).thenReturn(answer); - when(_agentMgr.easySend(anyLong(), any(SetSourceNatCommand.class))).thenReturn(answer); - when(_agentMgr.easySend(anyLong(), any(AssociateAsaWithLogicalEdgeFirewallCommand.class))).thenReturn(answer); - - assertTrue(_element.implement(network, offering, dest, context)); - } - - @Test - public void shutdownTest() throws ConcurrentOperationException, ResourceUnavailableException { - URI uri = URI.create("vlan://123"); - - Network network = mock(Network.class); - when(network.getId()).thenReturn(1L); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - when(network.getDataCenterId()).thenReturn(1L); - when(network.getBroadcastUri()).thenReturn(uri); - - ReservationContext context = mock(ReservationContext.class); - - when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class)); - - List devices = new ArrayList(); - devices.add(mock(CiscoVnmcControllerVO.class)); - when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(1L); - when(_hostDao.findById(anyLong())).thenReturn(hostVO); - - Answer answer = mock(Answer.class); - when(answer.getResult()).thenReturn(true); - - when(_agentMgr.easySend(anyLong(), any(CleanupLogicalEdgeFirewallCommand.class))).thenReturn(answer); - - assertTrue(_element.shutdown(network, context, true)); - } - - @Test - public void applyFWRulesTest() throws ResourceUnavailableException { - URI uri = URI.create("vlan://123"); - - Network network = mock(Network.class); - when(network.getId()).thenReturn(1L); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - when(network.getDataCenterId()).thenReturn(1L); - when(network.getBroadcastUri()).thenReturn(uri); - when(network.getCidr()).thenReturn("1.1.1.0/24"); - when(network.getState()).thenReturn(Network.State.Implemented); - - Ip ip = mock(Ip.class); - when(ip.addr()).thenReturn("1.2.3.4"); - - IpAddress ipAddress = mock(IpAddress.class); - when(ipAddress.getAddress()).thenReturn(ip); - - when(_networkModel.getIp(anyLong())).thenReturn(ipAddress); - when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, Provider.CiscoVnmc)).thenReturn(true); - - List devices = new ArrayList(); - devices.add(mock(CiscoVnmcControllerVO.class)); - when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices); - - when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class)); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(1L); - when(_hostDao.findById(anyLong())).thenReturn(hostVO); - - FirewallRule rule = mock(FirewallRule.class); - when(rule.getSourceIpAddressId()).thenReturn(1L); - List rules = new ArrayList(); - rules.add(rule); - - Answer answer = mock(Answer.class); - when(answer.getResult()).thenReturn(true); - - when(_agentMgr.easySend(anyLong(), any(SetFirewallRulesCommand.class))).thenReturn(answer); - - assertTrue(_element.applyFWRules(network, rules)); - } - - @Test - public void applyPRulesTest() throws ResourceUnavailableException { - URI uri = URI.create("vlan://123"); - - Network network = mock(Network.class); - when(network.getId()).thenReturn(1L); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - when(network.getDataCenterId()).thenReturn(1L); - when(network.getBroadcastUri()).thenReturn(uri); - when(network.getCidr()).thenReturn("1.1.1.0/24"); - when(network.getState()).thenReturn(Network.State.Implemented); - - Ip ip = mock(Ip.class); - when(ip.addr()).thenReturn("1.2.3.4"); - - IpAddress ipAddress = mock(IpAddress.class); - when(ipAddress.getAddress()).thenReturn(ip); - when(ipAddress.getVlanId()).thenReturn(1L); - - when(_networkModel.getIp(anyLong())).thenReturn(ipAddress); - when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, Provider.CiscoVnmc)).thenReturn(true); - - List devices = new ArrayList(); - devices.add(mock(CiscoVnmcControllerVO.class)); - when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices); - - when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class)); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(1L); - when(_hostDao.findById(anyLong())).thenReturn(hostVO); - - VlanVO vlanVO = mock(VlanVO.class); - when(vlanVO.getVlanTag()).thenReturn(null); - when(_vlanDao.findById(anyLong())).thenReturn(vlanVO); - - PortForwardingRule rule = mock(PortForwardingRule.class); - when(rule.getSourceIpAddressId()).thenReturn(1L); - when(rule.getDestinationIpAddress()).thenReturn(ip); - List rules = new ArrayList(); - rules.add(rule); - - Answer answer = mock(Answer.class); - when(answer.getResult()).thenReturn(true); - - when(_agentMgr.easySend(anyLong(), any(SetPortForwardingRulesCommand.class))).thenReturn(answer); - - assertTrue(_element.applyPFRules(network, rules)); - } - - @Test - public void applyStaticNatsTest() throws ResourceUnavailableException { - URI uri = URI.create("vlan://123"); - - Network network = mock(Network.class); - when(network.getId()).thenReturn(1L); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - when(network.getDataCenterId()).thenReturn(1L); - when(network.getBroadcastUri()).thenReturn(uri); - when(network.getCidr()).thenReturn("1.1.1.0/24"); - when(network.getState()).thenReturn(Network.State.Implemented); - - Ip ip = mock(Ip.class); - when(ip.addr()).thenReturn("1.2.3.4"); - - IpAddress ipAddress = mock(IpAddress.class); - when(ipAddress.getAddress()).thenReturn(ip); - when(ipAddress.getVlanId()).thenReturn(1L); - - when(_networkModel.getIp(anyLong())).thenReturn(ipAddress); - when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.StaticNat, Provider.CiscoVnmc)).thenReturn(true); - - List devices = new ArrayList(); - devices.add(mock(CiscoVnmcControllerVO.class)); - when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices); - - when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class)); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(1L); - when(_hostDao.findById(anyLong())).thenReturn(hostVO); - - VlanVO vlanVO = mock(VlanVO.class); - when(vlanVO.getVlanTag()).thenReturn(null); - when(_vlanDao.findById(anyLong())).thenReturn(vlanVO); - - StaticNat rule = mock(StaticNat.class); - when(rule.getSourceIpAddressId()).thenReturn(1L); - when(rule.getDestIpAddress()).thenReturn("1.2.3.4"); - when(rule.isForRevoke()).thenReturn(false); - List rules = new ArrayList(); - rules.add(rule); - - Answer answer = mock(Answer.class); - when(answer.getResult()).thenReturn(true); - - when(_agentMgr.easySend(anyLong(), any(SetStaticNatRulesCommand.class))).thenReturn(answer); - - assertTrue(_element.applyStaticNats(network, rules)); - } -} diff --git a/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/resource/CiscoVnmcResourceTest.java b/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/resource/CiscoVnmcResourceTest.java deleted file mode 100644 index b331a2f72280..000000000000 --- a/plugins/network-elements/cisco-vnmc/src/test/java/com/cloud/network/resource/CiscoVnmcResourceTest.java +++ /dev/null @@ -1,255 +0,0 @@ -// 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.network.resource; - -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.junit.Before; -import org.junit.Test; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateLogicalEdgeFirewallCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetSourceNatCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.to.FirewallRuleTO; -import com.cloud.agent.api.to.IpAddressTO; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.host.Host; -import com.cloud.network.cisco.CiscoVnmcConnectionImpl; -import com.cloud.network.rules.FirewallRule; -import com.cloud.utils.exception.ExecutionException; - -public class CiscoVnmcResourceTest { - CiscoVnmcConnectionImpl _connection = mock(CiscoVnmcConnectionImpl.class); - CiscoVnmcResource _resource; - Map _parameters; - - @Before - public void setUp() throws ConfigurationException { - _resource = new CiscoVnmcResource(); - - _parameters = new HashMap(); - _parameters.put("name", "CiscoVnmc"); - _parameters.put("zoneId", "1"); - _parameters.put("physicalNetworkId", "100"); - _parameters.put("ip", "1.2.3.4"); - _parameters.put("username", "admin"); - _parameters.put("password", "pass"); - _parameters.put("guid", "e8e13097-0a08-4e82-b0af-1101589ec3b8"); - _parameters.put("numretries", "3"); - _parameters.put("timeout", "300"); - } - - //@Test(expected=ConfigurationException.class) - public void resourceConfigureFailure() throws ConfigurationException { - _resource.configure("CiscoVnmcResource", Collections. emptyMap()); - } - - //@Test - public void resourceConfigure() throws ConfigurationException { - _resource.configure("CiscoVnmcResource", _parameters); - assertTrue("CiscoVnmc".equals(_resource.getName())); - assertTrue(_resource.getType() == Host.Type.ExternalFirewall); - } - - //@Test - public void testInitialization() throws ConfigurationException { - _resource.configure("CiscoVnmcResource", _parameters); - StartupCommand[] sc = _resource.initialize(); - assertTrue(sc.length == 1); - assertTrue("e8e13097-0a08-4e82-b0af-1101589ec3b8".equals(sc[0].getGuid())); - assertTrue("CiscoVnmc".equals(sc[0].getName())); - assertTrue("1".equals(sc[0].getDataCenter())); - } - - @Test - public void testPingCommandStatusOk() throws ConfigurationException, ExecutionException { - _resource.setConnection(_connection); - when(_connection.login()).thenReturn(true); - PingCommand ping = _resource.getCurrentStatus(1); - assertTrue(ping != null); - assertTrue(ping.getHostId() == 1); - assertTrue(ping.getHostType() == Host.Type.ExternalFirewall); - } - - @Test - public void testPingCommandStatusFail() throws ConfigurationException, ExecutionException { - _resource.setConnection(_connection); - when(_connection.login()).thenReturn(false); - PingCommand ping = _resource.getCurrentStatus(1); - assertTrue(ping == null); - } - - @Test - public void testSourceNat() throws ConfigurationException, Exception { - long vlanId = 123; - IpAddressTO ip = new IpAddressTO(1, "1.2.3.4", true, false, false, null, "1.2.3.1", "255.255.255.0", null, null, false); - SetSourceNatCommand cmd = new SetSourceNatCommand(ip, true); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId)); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32"); - - _resource.setConnection(_connection); - when(_connection.login()).thenReturn(true); - when(_connection.createTenantVDCNatPolicySet(anyString())).thenReturn(true); - when(_connection.createTenantVDCSourceNatPolicy(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCSourceNatPolicyRef(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCSourceNatIpPool(anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCSourceNatRule(anyString(), anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.associateNatPolicySet(anyString())).thenReturn(true); - - Answer answer = _resource.executeRequest(cmd); - System.out.println(answer.getDetails()); - assertTrue(answer.getResult()); - } - - @Test - public void testFirewall() throws ConfigurationException, Exception { - long vlanId = 123; - List rules = new ArrayList(); - List cidrList = new ArrayList(); - cidrList.add("2.3.2.3/32"); - FirewallRuleTO active = new FirewallRuleTO(1, null, "1.2.3.4", "tcp", 22, 22, false, false, FirewallRule.Purpose.Firewall, cidrList, null, null); - rules.add(active); - FirewallRuleTO revoked = new FirewallRuleTO(1, null, "1.2.3.4", "tcp", 22, 22, true, false, FirewallRule.Purpose.Firewall, null, null, null); - rules.add(revoked); - - SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rules); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId)); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32"); - - _resource.setConnection(_connection); - when(_connection.createTenantVDCAclPolicySet(anyString(), anyBoolean())).thenReturn(true); - when(_connection.createTenantVDCAclPolicy(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicyRef(anyString(), anyString(), anyBoolean())).thenReturn(true); - when(_connection.deleteTenantVDCAclRule(anyString(), anyLong(), anyString())).thenReturn(true); - when(_connection.createTenantVDCIngressAclRule(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn( - true); - when(_connection.createTenantVDCEgressAclRule(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn( - true); - when(_connection.associateAclPolicySet(anyString())).thenReturn(true); - - Answer answer = _resource.executeRequest(cmd); - System.out.println(answer.getDetails()); - assertTrue(answer.getResult()); - } - - @Test - public void testStaticNat() throws ConfigurationException, Exception { - long vlanId = 123; - List rules = new ArrayList(); - StaticNatRuleTO active = new StaticNatRuleTO(0, "1.2.3.4", null, null, "5.6.7.8", null, null, null, false, false); - rules.add(active); - StaticNatRuleTO revoked = new StaticNatRuleTO(0, "1.2.3.4", null, null, "5.6.7.8", null, null, null, true, false); - rules.add(revoked); - - SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rules, null); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId)); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32"); - - _resource.setConnection(_connection); - when(_connection.createTenantVDCNatPolicySet(anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicySet(anyString(), anyBoolean())).thenReturn(true); - when(_connection.createTenantVDCDNatPolicy(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCDNatPolicyRef(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicy(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicyRef(anyString(), anyString(), anyBoolean())).thenReturn(true); - when(_connection.deleteTenantVDCDNatRule(anyString(), anyLong(), anyString())).thenReturn(true); - when(_connection.deleteTenantVDCAclRule(anyString(), anyLong(), anyString())).thenReturn(true); - when(_connection.createTenantVDCDNatIpPool(anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCDNatRule(anyString(), anyLong(), anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclRuleForDNat(anyString(), anyLong(), anyString(), anyString())).thenReturn(true); - when(_connection.associateAclPolicySet(anyString())).thenReturn(true); - - Answer answer = _resource.executeRequest(cmd); - System.out.println(answer.getDetails()); - assertTrue(answer.getResult()); - } - - @Test - public void testPortForwarding() throws ConfigurationException, Exception { - long vlanId = 123; - List rules = new ArrayList(); - PortForwardingRuleTO active = new PortForwardingRuleTO(1, "1.2.3.4", 22, 22, "5.6.7.8", 22, 22, "tcp", false, false); - rules.add(active); - PortForwardingRuleTO revoked = new PortForwardingRuleTO(1, "1.2.3.4", 22, 22, "5.6.7.8", 22, 22, "tcp", false, false); - rules.add(revoked); - - SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(rules); - cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, Long.toString(vlanId)); - cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, "1.2.3.4/32"); - - _resource.setConnection(_connection); - when(_connection.createTenantVDCNatPolicySet(anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicySet(anyString(), anyBoolean())).thenReturn(true); - when(_connection.createTenantVDCPFPolicy(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCPFPolicyRef(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicy(anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclPolicyRef(anyString(), anyString(), anyBoolean())).thenReturn(true); - when(_connection.deleteTenantVDCPFRule(anyString(), anyLong(), anyString())).thenReturn(true); - when(_connection.deleteTenantVDCAclRule(anyString(), anyLong(), anyString())).thenReturn(true); - when(_connection.createTenantVDCPFIpPool(anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCPFPortPool(anyString(), anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCPFRule(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.createTenantVDCAclRuleForPF(anyString(), anyLong(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.associateAclPolicySet(anyString())).thenReturn(true); - - Answer answer = _resource.executeRequest(cmd); - System.out.println(answer.getDetails()); - assertTrue(answer.getResult()); - } - - @Test - public void testCreateEdgeFirewall() throws ConfigurationException, Exception { - long vlanId = 123; - CreateLogicalEdgeFirewallCommand cmd = new CreateLogicalEdgeFirewallCommand(vlanId, "1.2.3.4", "5.6.7.8", "255.255.255.0", "255.255.255.0"); - cmd.getPublicGateways().add("1.1.1.1"); - cmd.getPublicGateways().add("2.2.2.2"); - - _resource.setConnection(_connection); - when(_connection.createTenant(anyString())).thenReturn(true); - when(_connection.createTenantVDC(anyString())).thenReturn(true); - when(_connection.createTenantVDCEdgeSecurityProfile(anyString())).thenReturn(true); - when(_connection.createTenantVDCEdgeDeviceProfile(anyString())).thenReturn(true); - when(_connection.createTenantVDCEdgeStaticRoutePolicy(anyString())).thenReturn(true); - when(_connection.createTenantVDCEdgeStaticRoute(anyString(), anyString(), anyString(), anyString())).thenReturn(true); - when(_connection.associateTenantVDCEdgeStaticRoutePolicy(anyString())).thenReturn(true); - when(_connection.createEdgeFirewall(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); - - Answer answer = _resource.executeRequest(cmd); - System.out.println(answer.getDetails()); - assertTrue(answer.getResult()); - } -} diff --git a/plugins/network-elements/dns-notifier/src/main/resources/components-example.xml b/plugins/network-elements/dns-notifier/src/main/resources/components-example.xml index 1498a2e72bf4..65620fcc66ec 100755 --- a/plugins/network-elements/dns-notifier/src/main/resources/components-example.xml +++ b/plugins/network-elements/dns-notifier/src/main/resources/components-example.xml @@ -76,7 +76,6 @@ under the License. - @@ -89,7 +88,6 @@ under the License. - @@ -101,7 +99,6 @@ under the License. - @@ -113,7 +110,6 @@ under the License. - @@ -136,7 +132,6 @@ under the License. - @@ -146,7 +141,6 @@ under the License. - @@ -156,12 +150,8 @@ under the License. - - - - diff --git a/plugins/network-elements/globodns/pom.xml b/plugins/network-elements/globodns/pom.xml deleted file mode 100644 index 11e84d777c15..000000000000 --- a/plugins/network-elements/globodns/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-globodns - Apache CloudStack Plugin - GloboDNS - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - com.globo.globodns - globodns-client - - - com.mysql - mysql-connector-j - test - - - diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/api/AddGloboDnsHostCmd.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/api/AddGloboDnsHostCmd.java deleted file mode 100644 index 3a1ca73f0fab..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/api/AddGloboDnsHostCmd.java +++ /dev/null @@ -1,118 +0,0 @@ -// 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.globo.globodns.cloudstack.api; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.utils.exception.CloudRuntimeException; -import com.globo.globodns.cloudstack.element.GloboDnsElementService; - -@APICommand(name = "addGloboDnsHost", responseObject = SuccessResponse.class, description = "Adds the GloboDNS external host", since="4.5.0") -public class AddGloboDnsHostCmd extends BaseAsyncCmd { - - @Inject - GloboDnsElementService _globoDnsElementService; - - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, required = true, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Username for GloboDNS") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Password for GloboDNS") - private String password; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "GloboDNS url") - private String url; - - // /////////////////////////////////////////////////// - // ///////////////// Accessors /////////////////////// - // /////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getUrl() { - return url; - } - - // /////////////////////////////////////////////////// - // ///////////// API Implementation/////////////////// - // /////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { - try { - Host host = _globoDnsElementService.addGloboDnsHost(physicalNetworkId, username, password, url); - - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setSuccess((host == null ? false : true)); - this.setResponseObject(response); - - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccountId(); - } - - @Override - public String getEventType() { - //EventTypes.EVENT_NETWORK_CREATE - return EventTypes.EVENT_NETWORK_CREATE; - } - - @Override - public String getEventDescription() { - return "Add GloboDNS provider to physical network with ID: " + getResourceUuid(ApiConstants.PHYSICAL_NETWORK_ID); - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateDomainCommand.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateDomainCommand.java deleted file mode 100644 index 83564cb9c860..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateDomainCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.commands; - -import com.cloud.agent.api.Command; - -public class CreateOrUpdateDomainCommand extends Command { - - private String domainName; - - private Long templateId; - - public CreateOrUpdateDomainCommand(String domainName, Long templateId) { - this.domainName = domainName; - this.templateId = templateId; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getDomainName() { - return domainName; - } - - public Long getTemplateId() { - return templateId; - } -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateRecordAndReverseCommand.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateRecordAndReverseCommand.java deleted file mode 100644 index a5bafe95dea4..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/CreateOrUpdateRecordAndReverseCommand.java +++ /dev/null @@ -1,66 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.commands; - -import com.cloud.agent.api.Command; - -public class CreateOrUpdateRecordAndReverseCommand extends Command { - - private String recordName; - - private String recordIp; - - private String networkDomain; - - private Long reverseTemplateId; - - private boolean override; - - public CreateOrUpdateRecordAndReverseCommand(String recordName, String recordIp, String networkDomain, Long reverseTemplateId, boolean override) { - this.recordName = recordName; - this.recordIp = recordIp; - this.networkDomain = networkDomain; - this.reverseTemplateId = reverseTemplateId; - this.override = override; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getRecordName() { - return this.recordName; - } - - public String getRecordIp() { - return this.recordIp; - } - - public String getNetworkDomain() { - return this.networkDomain; - } - - public Long getReverseTemplateId() { - return reverseTemplateId; - } - - public boolean isOverride() { - return override; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveDomainCommand.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveDomainCommand.java deleted file mode 100644 index dffdce14e7a4..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveDomainCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.commands; - -import com.cloud.agent.api.Command; - -public class RemoveDomainCommand extends Command { - - private String networkDomain; - - private boolean override; - - public RemoveDomainCommand(String networkDomain, boolean override) { - this.networkDomain = networkDomain; - this.override = override; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getNetworkDomain() { - return this.networkDomain; - } - - public boolean isOverride() { - return override; - } -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveRecordCommand.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveRecordCommand.java deleted file mode 100644 index 3479b26c39d4..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/RemoveRecordCommand.java +++ /dev/null @@ -1,59 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.commands; - -import com.cloud.agent.api.Command; - -public class RemoveRecordCommand extends Command { - - private String recordName; - - private String recordIp; - - private String networkDomain; - - private boolean override; - - public RemoveRecordCommand(String recordName, String recordIp, String networkDomain, boolean override) { - this.recordName = recordName; - this.recordIp = recordIp; - this.networkDomain = networkDomain; - this.override = override; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getRecordName() { - return recordName; - } - - public String getRecordIp() { - return recordIp; - } - - public String getNetworkDomain() { - return networkDomain; - } - - public boolean isOverride() { - return override; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/SignInCommand.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/SignInCommand.java deleted file mode 100644 index 86f82db0fa86..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/commands/SignInCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.commands; - -import com.cloud.agent.api.Command; - -public class SignInCommand extends Command { - - private String email; - - private String password; - - public SignInCommand(String email, String password) { - this.email = email; - this.password = password; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getEmail() { - return this.email; - } - - public String getPassword() { - return this.password; - } -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElement.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElement.java deleted file mode 100644 index 09830d9a810f..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElement.java +++ /dev/null @@ -1,384 +0,0 @@ -// 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 -// 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.globo.globodns.cloudstack.element; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.framework.config.ConfigKey; -import org.apache.cloudstack.framework.config.Configurable; -import org.springframework.stereotype.Component; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.StartupCommand; -import com.cloud.dc.DataCenter; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.host.Host.Type; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.element.NetworkElement; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackWithException; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; -import com.globo.globodns.cloudstack.api.AddGloboDnsHostCmd; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateDomainCommand; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateRecordAndReverseCommand; -import com.globo.globodns.cloudstack.commands.RemoveDomainCommand; -import com.globo.globodns.cloudstack.commands.RemoveRecordCommand; -import com.globo.globodns.cloudstack.commands.SignInCommand; -import com.globo.globodns.cloudstack.resource.GloboDnsResource; - -@Component -public class GloboDnsElement extends AdapterBase implements ResourceStateAdapter, NetworkElement, GloboDnsElementService, Configurable { - - - private static final Map> capabilities = setCapabilities(); - - private static final ConfigKey GloboDNSTemplateId = new ConfigKey("Advanced", Long.class, "globodns.domain.templateid", "1", - "Template id to be used when creating domains in GloboDNS", true, ConfigKey.Scope.Global); - private static final ConfigKey GloboDNSOverride = new ConfigKey("Advanced", Boolean.class, "globodns.override.entries", "true", - "Allow GloboDns to override entries that already exist", true, ConfigKey.Scope.Global); - - // DAOs - @Inject - DataCenterDao _dcDao; - @Inject - HostDao _hostDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - - // Managers - @Inject - AgentManager _agentMgr; - @Inject - ResourceManager _resourceMgr; - - protected boolean isTypeSupported(VirtualMachine.Type type) { - return type == VirtualMachine.Type.User || type == VirtualMachine.Type.ConsoleProxy || type == VirtualMachine.Type.DomainRouter; - } - - @Override - @DB - public boolean implement(final Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - - Long zoneId = network.getDataCenterId(); - DataCenter zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new CloudRuntimeException("Could not find zone associated to this network"); - } - CreateOrUpdateDomainCommand cmd = new CreateOrUpdateDomainCommand(network.getNetworkDomain(), GloboDNSTemplateId.value()); - callCommand(cmd, zoneId); - return true; - } - - protected String hostNameOfVirtualMachine(VirtualMachineProfile vm) { - return vm.getHostName().toLowerCase(); - } - - @Override - @DB - public boolean prepare(final Network network, final NicProfile nic, final VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - - if (!isTypeSupported(vm.getType())) { - logger.info("GloboDNS only manages records for VMs of type User, ConsoleProxy and DomainRouter. VM " + vm + " is " + vm.getType()); - return false; - } - - Long zoneId = network.getDataCenterId(); - final DataCenter zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new CloudRuntimeException("Could not find zone associated to this network"); - } - - /* Create new A record in GloboDNS */ - // We allow only lower case names in DNS, so force lower case names for VMs - String vmName = vm.getHostName(); - String vmHostname = hostNameOfVirtualMachine(vm); - if (!vmName.equals(vmHostname) && vm.getType() == VirtualMachine.Type.User) { - throw new InvalidParameterValueException("VM name should contain only lower case letters and digits: " + vmName + " - " + vm); - } - - CreateOrUpdateRecordAndReverseCommand cmd = new CreateOrUpdateRecordAndReverseCommand(vmHostname, nic.getIPv4Address(), network.getNetworkDomain(), - GloboDNSTemplateId.value(), GloboDNSOverride.value()); - callCommand(cmd, zoneId); - return true; - } - - @Override - @DB - public boolean release(final Network network, NicProfile nic, final VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - - if (!isTypeSupported(vm.getType())) { - logger.info("GloboDNS only manages records for VMs of type User, ConsoleProxy and DomainRouter. VM " + vm + " is " + vm.getType()); - return false; - } - - Long zoneId = network.getDataCenterId(); - final DataCenter zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new CloudRuntimeException("Could not find zone associated to this network"); - } - - RemoveRecordCommand cmd = new RemoveRecordCommand(hostNameOfVirtualMachine(vm), nic.getIPv4Address(), network.getNetworkDomain(), GloboDNSOverride.value()); - callCommand(cmd, zoneId); - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - return true; - } - - @Override - @DB - public boolean destroy(final Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - Long zoneId = network.getDataCenterId(); - final DataCenter zone = _dcDao.findById(zoneId); - if (zone == null) { - throw new CloudRuntimeException("Could not find zone associated to this network"); - } - - RemoveDomainCommand cmd = new RemoveDomainCommand(network.getNetworkDomain(), GloboDNSOverride.value()); - callCommand(cmd, zoneId); - return true; - } - - ///////// Provider control methods //////////// - private Answer callCommand(Command cmd, Long zoneId) { - - HostVO globoDnsHost = getGloboDnsHost(zoneId); - if (globoDnsHost == null) { - throw new CloudRuntimeException("Could not find the GloboDNS resource"); - } - - Answer answer = _agentMgr.easySend(globoDnsHost.getId(), cmd); - if (answer == null || !answer.getResult()) { - String msg = "Error executing command " + cmd; - msg = answer == null ? msg : answer.getDetails(); - throw new CloudRuntimeException(msg); - } - - return answer; - } - - @Override - public Map> getCapabilities() { - return capabilities; - } - - private static Map> setCapabilities() { - Map> caps = new HashMap>(); - Map dnsCapabilities = new HashMap(); - // FIXME - dnsCapabilities.put(Capability.AllowDnsSuffixModification, "true"); - caps.put(Service.Dns, dnsCapabilities); - return caps; - } - - @Override - public Provider getProvider() { - return Provider.GloboDns; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - PhysicalNetwork pNtwk = _physicalNetworkDao.findById(provider.getPhysicalNetworkId()); - Host host = getGloboDnsHost(pNtwk.getDataCenterId()); - if (host != null) { - _resourceMgr.deleteHost(host.getId(), true, false); - } - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - return true; - } - - ////// Configurable methods ///////////// - @Override - public String getConfigComponentName() { - return GloboDnsElement.class.getSimpleName(); - } - - @Override - public ConfigKey[] getConfigKeys() { - return new ConfigKey[] {GloboDNSTemplateId, GloboDNSOverride}; - } - - ////////// Resource/Host methods //////////// - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddGloboDnsHostCmd.class); - return cmdList; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - return null; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - if (!(startup[0] instanceof StartupCommand && resource instanceof GloboDnsResource)) { - return null; - } - host.setType(Host.Type.L2Networking); - return host; - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (!(host.getType() == Host.Type.L2Networking)) { - return null; - } - return new DeleteHostAnswer(true); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(name, this); - return true; - } - - private HostVO getGloboDnsHost(Long zoneId) { - return _hostDao.findByTypeNameAndZoneId(zoneId, Provider.GloboDns.getName(), Type.L2Networking); - } - - @Override - @DB - public Host addGloboDnsHost(Long physicalNetworkId, final String username, final String password, String url) { - - if (username == null || username.trim().isEmpty()) { - throw new InvalidParameterValueException("Invalid username: " + username); - } - - if (password == null || password.trim().isEmpty()) { - throw new InvalidParameterValueException("Invalid password: " + password); - } - - if (url == null || url.trim().isEmpty()) { - throw new InvalidParameterValueException("Invalid url: " + url); - } - - // validate physical network and zone - // Check if physical network exists - PhysicalNetwork pNtwk = null; - if (physicalNetworkId != null) { - pNtwk = _physicalNetworkDao.findById(physicalNetworkId); - if (pNtwk == null) { - throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id"); - } - } else { - throw new InvalidParameterValueException("Invalid physicalNetworkId: " + physicalNetworkId); - } - - final Long zoneId = pNtwk.getDataCenterId(); - - final Map params = new HashMap(); - params.put("guid", "globodns-" + String.valueOf(zoneId)); - params.put("zoneId", String.valueOf(zoneId)); - params.put("name", Provider.GloboDns.getName()); - - params.put("url", url); - params.put("username", username); - params.put("password", password); - - final Map hostDetails = new HashMap(); - hostDetails.putAll(params); - - Host host = Transaction.execute(new TransactionCallbackWithException() { - - @Override - public Host doInTransaction(TransactionStatus status) throws CloudRuntimeException { - try { - GloboDnsResource resource = new GloboDnsResource(); - resource.configure(Provider.GloboDns.getName(), hostDetails); - - Host host = _resourceMgr.addHost(zoneId, resource, resource.getType(), params); - - if (host == null) { - throw new CloudRuntimeException("Failed to add GloboDNS host"); - } - - // Validate username and password by logging in - SignInCommand cmd = new SignInCommand(username, password); - Answer answer = callCommand(cmd, zoneId); - if (answer == null || !answer.getResult()) { - // Could not sign in on GloboDNS - throw new ConfigurationException("Could not sign in on GloboDNS. Please verify URL, username and password."); - } - - return host; - } catch (ConfigurationException e) { - throw new CloudRuntimeException(e); - } - } - }); - - return host; - } -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElementService.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElementService.java deleted file mode 100644 index c141ad1c8e4a..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/element/GloboDnsElementService.java +++ /dev/null @@ -1,25 +0,0 @@ -// 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.globo.globodns.cloudstack.element; - -import com.cloud.host.Host; -import com.cloud.utils.component.PluggableService; - -public interface GloboDnsElementService extends PluggableService { - - public Host addGloboDnsHost(Long pNtwkId, String username, String password, String url); -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/resource/GloboDnsResource.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/resource/GloboDnsResource.java deleted file mode 100644 index 1aaa74507d5c..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/resource/GloboDnsResource.java +++ /dev/null @@ -1,454 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.resource; - -import java.util.List; -import java.util.Map; - -import javax.naming.ConfigurationException; - - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.host.Host; -import com.cloud.host.Host.Type; -import com.cloud.resource.ServerResource; -import com.cloud.utils.component.ManagerBase; -import com.globo.globodns.client.GloboDns; -import com.globo.globodns.client.GloboDnsException; -import com.globo.globodns.client.model.Authentication; -import com.globo.globodns.client.model.Domain; -import com.globo.globodns.client.model.Export; -import com.globo.globodns.client.model.Record; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateDomainCommand; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateRecordAndReverseCommand; -import com.globo.globodns.cloudstack.commands.RemoveDomainCommand; -import com.globo.globodns.cloudstack.commands.RemoveRecordCommand; -import com.globo.globodns.cloudstack.commands.SignInCommand; - -public class GloboDnsResource extends ManagerBase implements ServerResource { - private String _zoneId; - - private String _guid; - - private String _name; - - private String _username; - - private String _url; - - private String _password; - - protected GloboDns _globoDns; - - private static final String IPV4_RECORD_TYPE = "A"; - private static final String REVERSE_RECORD_TYPE = "PTR"; - private static final String REVERSE_DOMAIN_SUFFIX = "in-addr.arpa"; - private static final String DEFAULT_AUTHORITY_TYPE = "M"; - - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - - _zoneId = (String)params.get("zoneId"); - if (_zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - _guid = (String)params.get("guid"); - if (_guid == null) { - throw new ConfigurationException("Unable to find guid"); - } - - _name = (String)params.get("name"); - if (_name == null) { - throw new ConfigurationException("Unable to find name"); - } - - _url = (String)params.get("url"); - if (_url == null) { - throw new ConfigurationException("Unable to find url"); - } - - _username = (String)params.get("username"); - if (_username == null) { - throw new ConfigurationException("Unable to find username"); - } - - _password = (String)params.get("password"); - if (_password == null) { - throw new ConfigurationException("Unable to find password"); - } - - _globoDns = GloboDns.buildHttpApi(_url, _username, _password); - - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public Type getType() { - return Host.Type.L2Networking; - } - - @Override - public StartupCommand[] initialize() { - logger.trace("initialize called"); - StartupCommand cmd = new StartupCommand(getType()); - cmd.setName(_name); - cmd.setGuid(_guid); - cmd.setDataCenter(_zoneId); - cmd.setPod(""); - cmd.setPrivateIpAddress(""); - cmd.setStorageIpAddress(""); - cmd.setVersion(GloboDnsResource.class.getPackage().getImplementationVersion()); - return new StartupCommand[] {cmd}; - } - - @Override - public PingCommand getCurrentStatus(long id) { - return new PingCommand(getType(), id); - } - - @Override - public void disconnected() { - return; - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - return; - } - - @Override - public Answer executeRequest(Command cmd) { - if (cmd instanceof ReadyCommand) { - return new ReadyAnswer((ReadyCommand)cmd); - } else if (cmd instanceof MaintainCommand) { - return new MaintainAnswer((MaintainCommand)cmd); - } else if (cmd instanceof SignInCommand) { - return execute((SignInCommand)cmd); - } else if (cmd instanceof RemoveDomainCommand) { - return execute((RemoveDomainCommand)cmd); - } else if (cmd instanceof RemoveRecordCommand) { - return execute((RemoveRecordCommand)cmd); - } else if (cmd instanceof CreateOrUpdateDomainCommand) { - return execute((CreateOrUpdateDomainCommand)cmd); - } else if (cmd instanceof CreateOrUpdateRecordAndReverseCommand) { - return execute((CreateOrUpdateRecordAndReverseCommand)cmd); - } - return Answer.createUnsupportedCommandAnswer(cmd); - } - - public Answer execute(SignInCommand cmd) { - try { - Authentication auth = _globoDns.getAuthAPI().signIn(cmd.getEmail(), cmd.getPassword()); - if (auth != null) { - return new Answer(cmd, true, "Signed in successfully"); - } else { - return new Answer(cmd, false, "Unable to sign in on GloboDNS"); - } - } catch (GloboDnsException e) { - return new Answer(cmd, false, e.getMessage()); - } - } - - public Answer execute(RemoveDomainCommand cmd) { - try { - Domain domain = searchDomain(cmd.getNetworkDomain(), false); - if (domain != null) { - if (!cmd.isOverride()) { - for (Record record : _globoDns.getRecordAPI().listAll(domain.getId())) { - if (record.getTypeNSRecordAttributes().getId() == null) { - logger.warn("There are records in domain " + cmd.getNetworkDomain() + " and override is not enable. I will not delete this domain."); - return new Answer(cmd, true, "Domain keeped"); - } - } - } - _globoDns.getDomainAPI().removeDomain(domain.getId()); - scheduleExportChangesToBind(); - } else { - logger.warn("Domain " + cmd.getNetworkDomain() + " already been deleted."); - } - - return new Answer(cmd, true, "Domain removed"); - } catch (GloboDnsException e) { - return new Answer(cmd, false, e.getMessage()); - } - } - - public Answer execute(RemoveRecordCommand cmd) { - boolean needsExport = false; - try { - if (removeRecord(cmd.getRecordName(), cmd.getRecordIp(), cmd.getNetworkDomain(), false, cmd.isOverride())) { - needsExport = true; - } - - // remove reverse - String reverseGloboDnsName = generateReverseDomainNameFromNetworkIp(cmd.getRecordIp()); - String reverseRecordName = generateReverseRecordNameFromNetworkIp(cmd.getRecordIp()); - String reverseRecordContent = cmd.getRecordName() + '.' + cmd.getNetworkDomain(); - - if (removeRecord(reverseRecordName, reverseRecordContent, reverseGloboDnsName, true, cmd.isOverride())) { - needsExport = true; - } - - return new Answer(cmd, true, "Record removed"); - } catch (GloboDnsException e) { - return new Answer(cmd, false, e.getMessage()); - } finally { - if (needsExport) { - scheduleExportChangesToBind(); - } - } - } - - public Answer execute(CreateOrUpdateRecordAndReverseCommand cmd) { - boolean needsExport = false; - try { - Domain domain = searchDomain(cmd.getNetworkDomain(), false); - if (domain == null) { - domain = _globoDns.getDomainAPI().createDomain(cmd.getNetworkDomain(), cmd.getReverseTemplateId(), DEFAULT_AUTHORITY_TYPE); - logger.warn("Domain " + cmd.getNetworkDomain() + " doesn't exist, maybe someone removed it. It was automatically created with Template " - + cmd.getReverseTemplateId()); - } - - boolean created = createOrUpdateRecord(domain.getId(), cmd.getRecordName(), cmd.getRecordIp(), IPV4_RECORD_TYPE, cmd.isOverride()); - if (!created) { - String msg = "Unable to create record " + cmd.getRecordName() + " at " + cmd.getNetworkDomain(); - if (!cmd.isOverride()) { - msg += ". Override record option is false, maybe record already exist."; - } - return new Answer(cmd, false, msg); - } else { - needsExport = true; - } - - String reverseRecordContent = cmd.getRecordName() + '.' + cmd.getNetworkDomain(); - if (createOrUpdateReverse(cmd.getRecordIp(), reverseRecordContent, cmd.getReverseTemplateId(), cmd.isOverride())) { - needsExport = true; - } else { - if (!cmd.isOverride()) { - String msg = "Unable to create reverse record " + cmd.getRecordName() + " for IP " + cmd.getRecordIp(); - msg += ". Override record option is false, maybe record already exist."; - return new Answer(cmd, false, msg); - } - } - - return new Answer(cmd); - } catch (GloboDnsException e) { - return new Answer(cmd, false, e.getMessage()); - } finally { - if (needsExport) { - scheduleExportChangesToBind(); - } - } - } - - protected boolean createOrUpdateReverse(String networkIp, String reverseRecordContent, Long templateId, boolean override) { - String reverseDomainName = generateReverseDomainNameFromNetworkIp(networkIp); - Domain reverseDomain = searchDomain(reverseDomainName, true); - if (reverseDomain == null) { - reverseDomain = _globoDns.getDomainAPI().createReverseDomain(reverseDomainName, templateId, DEFAULT_AUTHORITY_TYPE); - logger.info("Created reverse domain " + reverseDomainName + " with Template " + templateId); - } - - // create reverse - String reverseRecordName = generateReverseRecordNameFromNetworkIp(networkIp); - return createOrUpdateRecord(reverseDomain.getId(), reverseRecordName, reverseRecordContent, REVERSE_RECORD_TYPE, override); - } - - public Answer execute(CreateOrUpdateDomainCommand cmd) { - - boolean needsExport = false; - try { - Domain domain = searchDomain(cmd.getDomainName(), false); - if (domain == null) { - // create - domain = _globoDns.getDomainAPI().createDomain(cmd.getDomainName(), cmd.getTemplateId(), DEFAULT_AUTHORITY_TYPE); - logger.info("Created domain " + cmd.getDomainName() + " with Template " + cmd.getTemplateId()); - if (domain == null) { - return new Answer(cmd, false, "Unable to create domain " + cmd.getDomainName()); - } else { - needsExport = true; - } - } else { - logger.warn("Domain " + cmd.getDomainName() + " already exist."); - } - return new Answer(cmd); - } catch (GloboDnsException e) { - return new Answer(cmd, false, e.getMessage()); - } finally { - if (needsExport) { - scheduleExportChangesToBind(); - } - } - } - - /** - * Try to remove a record from bindZoneName. If record was removed returns true. - * @param recordName - * @param bindZoneName - * @return true if record exists and was removed. - */ - protected boolean removeRecord(String recordName, String recordValue, String bindZoneName, boolean reverse, boolean override) { - Domain domain = searchDomain(bindZoneName, reverse); - if (domain == null) { - logger.warn("Domain " + bindZoneName + " doesn't exists in GloboDNS. Record " + recordName + " has already been removed."); - return false; - } - Record record = searchRecord(recordName, domain.getId()); - if (record == null) { - logger.warn("Record " + recordName + " in domain " + bindZoneName + " has already been removed."); - return false; - } else { - if (!override && !record.getContent().equals(recordValue)) { - logger.warn("Record " + recordName + " in domain " + bindZoneName + " have different value from " + recordValue - + " and override is not enable. I will not delete it."); - return false; - } - _globoDns.getRecordAPI().removeRecord(record.getId()); - } - - return true; - } - - /** - * Create a new record in Zone, or update it if record has been exists. - * @param domainId - * @param name - * @param ip - * @param type - * @return if record was created or updated. - */ - private boolean createOrUpdateRecord(Long domainId, String name, String ip, String type, boolean override) { - Record record = this.searchRecord(name, domainId); - if (record == null) { - // Create new record - record = _globoDns.getRecordAPI().createRecord(domainId, name, ip, type); - logger.info("Created record " + record.getName() + " in domain " + domainId); - } else { - if (!ip.equals(record.getContent())) { - if (Boolean.TRUE.equals(override)) { - // ip is incorrect. Fix. - _globoDns.getRecordAPI().updateRecord(record.getId(), domainId, name, ip); - } else { - return false; - } - } - } - return true; - } - - /** - * GloboDns export all changes to Bind server. - */ - public void scheduleExportChangesToBind() { - try { - Export export = _globoDns.getExportAPI().scheduleExport(); - if (export != null) { - logger.info("GloboDns Export: " + export.getResult()); - } - } catch (GloboDnsException e) { - logger.warn("Error on scheduling export. Although everything was persist, someone need to manually force export in GloboDns", e); - } - } - - /** - * Try to find bindZoneName in GloboDns. - * @param name - * @return Domain object or null if domain not exists. - */ - private Domain searchDomain(String name, boolean reverse) { - if (name == null) { - return null; - } - List candidates; - if (reverse) { - candidates = _globoDns.getDomainAPI().listReverseByQuery(name); - } else { - candidates = _globoDns.getDomainAPI().listByQuery(name); - } - for (Domain candidate : candidates) { - if (name.equals(candidate.getName())) { - return candidate; - } - } - return null; - } - - /** - * Find recordName in domain. - * @param recordName - * @param domainId Id of BindZoneName. Maybe you need use searchDomain before to use BindZoneName. - * @return Record or null if not exists. - */ - private Record searchRecord(String recordName, Long domainId) { - if (recordName == null || domainId == null) { - return null; - } - List candidates = _globoDns.getRecordAPI().listByQuery(domainId, recordName); - // GloboDns search name in name and content. We need to iterate to check if recordName exists only in name - for (Record candidate : candidates) { - if (recordName.equalsIgnoreCase(candidate.getName())) { - logger.debug("Record " + recordName + " in domain id " + domainId + " found in GloboDNS"); - return candidate; - } - } - logger.debug("Record " + recordName + " in domain id " + domainId + " not found in GloboDNS"); - return null; - } - - /** - * Generate reverseBindZoneName of network. We ALWAYS use /24. - * @param networkIp - * @return Bind Zone Name reverse of network specified by networkIp - */ - private String generateReverseDomainNameFromNetworkIp(String networkIp) { - String[] octets = networkIp.split("\\."); - String reverseDomainName = octets[2] + '.' + octets[1] + '.' + octets[0] + '.' + REVERSE_DOMAIN_SUFFIX; - return reverseDomainName; - } - - private String generateReverseRecordNameFromNetworkIp(String networkIp) { - String[] octets = networkIp.split("\\."); - String reverseRecordName = octets[3]; - return reverseRecordName; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainListResponse.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainListResponse.java deleted file mode 100644 index 7bddab8a7aa3..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainListResponse.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.response; - -import java.util.List; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.globo.globodns.client.model.Domain; - -public class GloboDnsDomainListResponse extends Answer { - - private List domainList; - - public GloboDnsDomainListResponse(Command command, List domainList) { - super(command, true, null); - this.domainList = domainList; - } - - public List getDomainList() { - return domainList; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainResponse.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainResponse.java deleted file mode 100644 index 2a571ca8db94..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsDomainResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.response; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.globo.globodns.client.model.Domain; - -public class GloboDnsDomainResponse extends Answer { - - private Domain domain; - - public GloboDnsDomainResponse(Command command, Domain domain) { - super(command, true, null); - this.domain = domain; - } - - public Domain getDomain() { - return domain; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsExportResponse.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsExportResponse.java deleted file mode 100644 index a51f540c49f1..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsExportResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.response; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.globo.globodns.client.model.Export; - -public class GloboDnsExportResponse extends Answer { - - private Export export; - - public GloboDnsExportResponse(Command command, Export export) { - super(command, true, null); - this.export = export; - } - - public Export getExport() { - return export; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordListResponse.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordListResponse.java deleted file mode 100644 index edd1bb7daefd..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordListResponse.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.response; - -import java.util.List; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.globo.globodns.client.model.Record; - -public class GloboDnsRecordListResponse extends Answer { - - private List recordList; - - public GloboDnsRecordListResponse(Command command, List recordList) { - super(command, true, null); - this.recordList = recordList; - } - - public List getRecordList() { - return recordList; - } - -} diff --git a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordResponse.java b/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordResponse.java deleted file mode 100644 index 9236d11ec798..000000000000 --- a/plugins/network-elements/globodns/src/main/java/com/globo/globodns/cloudstack/response/GloboDnsRecordResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.response; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.globo.globodns.client.model.Record; - -public class GloboDnsRecordResponse extends Answer { - - private Record record; - - public GloboDnsRecordResponse(Command command, Record record) { - super(command, true, null); - this.record = record; - } - - public Record getRecord() { - return record; - } - -} diff --git a/plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/module.properties b/plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/module.properties deleted file mode 100644 index cd6bc776451b..000000000000 --- a/plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=globodns -parent=network diff --git a/plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/spring-globodns-context.xml b/plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/spring-globodns-context.xml deleted file mode 100644 index 45aabada6373..000000000000 --- a/plugins/network-elements/globodns/src/main/resources/META-INF/cloudstack/globodns/spring-globodns-context.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/element/GloboDnsElementTest.java b/plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/element/GloboDnsElementTest.java deleted file mode 100644 index 77a737a35cfe..000000000000 --- a/plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/element/GloboDnsElementTest.java +++ /dev/null @@ -1,266 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.element; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import javax.inject.Inject; - -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.test.utils.SpringUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ComponentScan.Filter; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.core.type.filter.TypeFilter; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host.Type; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.Network; -import com.cloud.network.Network.Provider; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.resource.ResourceManager; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.UserVO; -import com.cloud.utils.component.ComponentContext; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.ReservationContextImpl; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachineProfile; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateRecordAndReverseCommand; -import com.globo.globodns.cloudstack.commands.RemoveRecordCommand; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader = AnnotationConfigContextLoader.class) -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class GloboDnsElementTest { - - private static long zoneId = 5L; - private static long globoDnsHostId = 7L; - private static long domainId = 10L; - private AccountVO acct = null; - private UserVO user = null; - - @Inject - DataCenterDao _datacenterDao; - - @Inject - GloboDnsElement _globodnsElement; - - @Inject - HostDao _hostDao; - - @Inject - AgentManager _agentMgr; - - @Inject - AccountManager _acctMgr; - - @Before - public void setUp() throws Exception { - ComponentContext.initComponentsLifeCycle(); - - acct = new AccountVO(200L); - acct.setType(Account.Type.NORMAL); - acct.setAccountName("user"); - acct.setDomainId(domainId); - - user = new UserVO(); - user.setUsername("user"); - user.setAccountId(acct.getAccountId()); - - CallContext.register(user, acct); - when(_acctMgr.getSystemAccount()).thenReturn(this.acct); - when(_acctMgr.getSystemUser()).thenReturn(this.user); - } - - @After - public void tearDown() throws Exception { - CallContext.unregister(); - acct = null; - } - - @Test(expected = InvalidParameterValueException.class) - public void testUpperCaseCharactersAreNotAllowed() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - Network network = mock(Network.class); - when(network.getDataCenterId()).thenReturn(zoneId); - when(network.getId()).thenReturn(1l); - NicProfile nic = new NicProfile(); - VirtualMachineProfile vm = mock(VirtualMachineProfile.class); - when(vm.getHostName()).thenReturn("UPPERCASENAME"); - when(vm.getType()).thenReturn(VirtualMachine.Type.User); - when(_datacenterDao.findById(zoneId)).thenReturn(mock(DataCenterVO.class)); - DeployDestination dest = new DeployDestination(); - ReservationContext context = new ReservationContextImpl(null, null, user); - _globodnsElement.prepare(network, nic, vm, dest, context); - } - - @Test - public void testPrepareMethodCallGloboDnsToRegisterHostName() throws Exception { - Network network = mock(Network.class); - when(network.getDataCenterId()).thenReturn(zoneId); - when(network.getId()).thenReturn(1l); - NicProfile nic = new NicProfile(); - nic.setIPv4Address("10.11.12.13"); - VirtualMachineProfile vm = mock(VirtualMachineProfile.class); - when(vm.getHostName()).thenReturn("vm-name"); - when(vm.getType()).thenReturn(VirtualMachine.Type.User); - DataCenterVO dataCenterVO = mock(DataCenterVO.class); - when(dataCenterVO.getId()).thenReturn(zoneId); - when(_datacenterDao.findById(zoneId)).thenReturn(dataCenterVO); - DeployDestination dest = new DeployDestination(); - ReservationContext context = new ReservationContextImpl(null, null, user); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(globoDnsHostId); - when(_hostDao.findByTypeNameAndZoneId(eq(zoneId), eq(Provider.GloboDns.getName()), eq(Type.L2Networking))).thenReturn(hostVO); - - when(_agentMgr.easySend(eq(globoDnsHostId), isA(CreateOrUpdateRecordAndReverseCommand.class))).then(new org.mockito.stubbing.Answer() { - - @Override - public Answer answer(InvocationOnMock invocation) throws Throwable { - Command cmd = (Command)invocation.getArguments()[1]; - return new Answer(cmd); - } - }); - - _globodnsElement.prepare(network, nic, vm, dest, context); - verify(_agentMgr, times(1)).easySend(eq(globoDnsHostId), isA(CreateOrUpdateRecordAndReverseCommand.class)); - } - - @Test - public void testReleaseMethodCallResource() throws Exception { - Network network = mock(Network.class); - when(network.getDataCenterId()).thenReturn(zoneId); - when(network.getId()).thenReturn(1l); - NicProfile nic = new NicProfile(); - nic.setIPv4Address("10.11.12.13"); - VirtualMachineProfile vm = mock(VirtualMachineProfile.class); - when(vm.getHostName()).thenReturn("vm-name"); - when(vm.getType()).thenReturn(VirtualMachine.Type.User); - DataCenterVO dataCenterVO = mock(DataCenterVO.class); - when(dataCenterVO.getId()).thenReturn(zoneId); - when(_datacenterDao.findById(zoneId)).thenReturn(dataCenterVO); - ReservationContext context = new ReservationContextImpl(null, null, user); - - HostVO hostVO = mock(HostVO.class); - when(hostVO.getId()).thenReturn(globoDnsHostId); - when(_hostDao.findByTypeNameAndZoneId(eq(zoneId), eq(Provider.GloboDns.getName()), eq(Type.L2Networking))).thenReturn(hostVO); - - when(_agentMgr.easySend(eq(globoDnsHostId), isA(RemoveRecordCommand.class))).then(new org.mockito.stubbing.Answer() { - - @Override - public Answer answer(InvocationOnMock invocation) throws Throwable { - Command cmd = (Command)invocation.getArguments()[1]; - return new Answer(cmd); - } - }); - - _globodnsElement.release(network, nic, vm, context); - verify(_agentMgr, times(1)).easySend(eq(globoDnsHostId), isA(RemoveRecordCommand.class)); - } - - @Configuration - @ComponentScan(basePackageClasses = {GloboDnsElement.class}, includeFilters = {@Filter(value = TestConfiguration.Library.class, type = FilterType.CUSTOM)}, useDefaultFilters = false) - public static class TestConfiguration extends SpringUtils.CloudStackTestConfiguration { - - @Bean - public HostDao hostDao() { - return mock(HostDao.class); - } - - @Bean - public DataCenterDao dataCenterDao() { - return mock(DataCenterDao.class); - } - - @Bean - public PhysicalNetworkDao physicalNetworkDao() { - return mock(PhysicalNetworkDao.class); - } - - @Bean - public NetworkDao networkDao() { - return mock(NetworkDao.class); - } - - @Bean - public ConfigurationDao configurationDao() { - return mock(ConfigurationDao.class); - } - - @Bean - public AgentManager agentManager() { - return mock(AgentManager.class); - } - - @Bean - public ResourceManager resourceManager() { - return mock(ResourceManager.class); - } - - @Bean - public AccountManager accountManager() { - return mock(AccountManager.class); - } - - public static class Library implements TypeFilter { - - @Override - public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { - ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class); - return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs); - } - } - } -} diff --git a/plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/resource/GloboDnsResourceTest.java b/plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/resource/GloboDnsResourceTest.java deleted file mode 100644 index 74b270d61d33..000000000000 --- a/plugins/network-elements/globodns/src/test/java/com/globo/globodns/cloudstack/resource/GloboDnsResourceTest.java +++ /dev/null @@ -1,456 +0,0 @@ -/* -* 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.globo.globodns.cloudstack.resource; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.any; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InOrder; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; - -import com.cloud.agent.api.Answer; -import com.globo.globodns.client.GloboDns; -import com.globo.globodns.client.api.DomainAPI; -import com.globo.globodns.client.api.ExportAPI; -import com.globo.globodns.client.api.RecordAPI; -import com.globo.globodns.client.model.Domain; -import com.globo.globodns.client.model.Record; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateDomainCommand; -import com.globo.globodns.cloudstack.commands.CreateOrUpdateRecordAndReverseCommand; -import com.globo.globodns.cloudstack.commands.RemoveDomainCommand; -import com.globo.globodns.cloudstack.commands.RemoveRecordCommand; - -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class GloboDnsResourceTest { - - private GloboDnsResource _globoDnsResource; - - private GloboDns _globoDnsApi; - private DomainAPI _domainApi; - private RecordAPI _recordApi; - private ExportAPI _exportApi; - - private static final Long TEMPLATE_ID = 1l; - - private static long sequenceId = 10l; - - @Before - public void setUp() throws Exception { - - String name = "GloboDNS"; - Map params = new HashMap(); - params.put("zoneId", "1"); - params.put("guid", "globodns"); - params.put("name", name); - params.put("url", "http://example.com"); - params.put("username", "username"); - params.put("password", "password"); - - _globoDnsResource = new GloboDnsResource(); - _globoDnsResource.configure(name, params); - - _globoDnsApi = spy(_globoDnsResource._globoDns); - _globoDnsResource._globoDns = _globoDnsApi; - - _domainApi = mock(DomainAPI.class); - when(_globoDnsApi.getDomainAPI()).thenReturn(_domainApi); - - _recordApi = mock(RecordAPI.class); - when(_globoDnsApi.getRecordAPI()).thenReturn(_recordApi); - - _exportApi = mock(ExportAPI.class); - when(_globoDnsApi.getExportAPI()).thenReturn(_exportApi); - } - - @After - public void tearDown() throws Exception { - } - - /////////////////////// - // Auxiliary Methods // - /////////////////////// - - private Domain generateFakeDomain(String domainName, boolean reverse) { - Domain domain = new Domain(); - domain.getDomainAttributes().setId(sequenceId++); - domain.getDomainAttributes().setName(domainName); - List domainList = new ArrayList(); - domainList.add(domain); - if (reverse) { - when(_domainApi.listReverseByQuery(eq(domainName))).thenReturn(domainList); - } else { - when(_domainApi.listByQuery(eq(domainName))).thenReturn(domainList); - } - return domain; - } - - private Record generateFakeRecord(Domain domain, String recordName, String recordContent, boolean reverse) { - Record record = new Record(); - if (reverse) { - record.getTypePTRRecordAttributes().setName(recordName); - record.getTypePTRRecordAttributes().setContent(recordContent); - record.getTypePTRRecordAttributes().setDomainId(domain.getId()); - record.getTypePTRRecordAttributes().setId(sequenceId++); - } else { - record.getTypeARecordAttributes().setName(recordName); - record.getTypeARecordAttributes().setContent(recordContent); - record.getTypeARecordAttributes().setDomainId(domain.getId()); - record.getTypeARecordAttributes().setId(sequenceId++); - } - List recordList = new ArrayList(); - recordList.add(record); - when(_recordApi.listByQuery(eq(domain.getId()), eq(recordName))).thenReturn(recordList); - return record; - } - - ///////////////////////// - // Create Domain tests // - ///////////////////////// - - @Test - public void testCreateDomainWithSuccessWhenDomainDoesntExistAndOverrideIsTrue() throws Exception { - String domainName = "domain.name.com"; - - Domain domain = new Domain(); - domain.getDomainAttributes().setId(sequenceId++); - domain.getDomainAttributes().setName(domainName); - - when(_domainApi.createDomain(eq(domain.getName()), eq(TEMPLATE_ID), eq("M"))).thenReturn(domain); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateDomainCommand(domainName, TEMPLATE_ID)); - assertNotNull(answer); - assertEquals(true, answer.getResult()); - verify(_exportApi, times(1)).scheduleExport(); - } - - @Test - @SuppressWarnings("unused") - public void testCreateDomainWillSucceedWhenDomainAlreadyExistsAndOverrideIsFalse() throws Exception { - String domainName = "domain.name.com"; - - Domain domain = generateFakeDomain(domainName, false); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateDomainCommand(domainName, TEMPLATE_ID)); - assertNotNull(answer); - assertEquals(true, answer.getResult()); - } - - ///////////////////////// - // Create Record tests // - ///////////////////////// - - @Test - @SuppressWarnings("unused") - public void testCreateRecordAndReverseWithSuccessWhenDomainExistsAndRecordDoesntExistAndOverrideIsTrue() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - String reverseRecordContent = recordName + "." + domainName; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, recordIp, false); - Domain reverseDomain = generateFakeDomain(reverseDomainName, true); - Record reverseRecord = generateFakeRecord(reverseDomain, reverseRecordName, reverseRecordContent, true); - - when(_recordApi.createRecord(eq(domain.getId()), eq(recordName), eq(recordIp), eq("A"))).thenReturn(record); - when(_recordApi.createRecord(eq(reverseDomain.getId()), eq(reverseRecordName), eq(reverseRecordContent), eq("PTR"))).thenReturn(record); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateRecordAndReverseCommand(recordName, recordIp, domainName, TEMPLATE_ID, true)); - assertNotNull(answer); - assertEquals(true, answer.getResult()); - verify(_exportApi, times(1)).scheduleExport(); - } - - @Test - @SuppressWarnings("unused") - public void testCreateRecordAndReverseWillFailWhenRecordAlreadyExistsAndOverrideIsFalse() throws Exception { - String recordName = "recordname"; - String newIp = "40.30.20.10"; - String oldIp = "50.40.30.20"; - String domainName = "domain.name.com"; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, oldIp, false); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateRecordAndReverseCommand(recordName, newIp, domainName, TEMPLATE_ID, false)); - assertNotNull(answer); - assertEquals(false, answer.getResult()); - } - - @Test - @SuppressWarnings("unused") - public void testCreateRecordAndReverseWillFailWhenReverseRecordAlreadyExistsAndOverrideIsFalse() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, recordIp, false); - Domain reverseDomain = generateFakeDomain(reverseDomainName, true); - Record reverseRecord = generateFakeRecord(reverseDomain, reverseRecordName, "X", true); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateRecordAndReverseCommand(recordName, recordIp, domainName, TEMPLATE_ID, false)); - assertNotNull(answer); - assertEquals(false, answer.getResult()); - } - - @Test - public void testCreateRecordAndReverseWhenDomainDoesNotExist() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - String reverseRecordContent = recordName + "." + domainName; - - Domain domain = new Domain(); - domain.getDomainAttributes().setId(sequenceId++); - Domain reverseDomain = new Domain(); - reverseDomain.getDomainAttributes().setId(sequenceId++); - - Record record = new Record(); - - when(_domainApi.listByQuery(domainName)).thenReturn(new ArrayList()); - when(_domainApi.createDomain(eq(domainName), eq(TEMPLATE_ID), eq("M"))).thenReturn(domain); - when(_recordApi.createRecord(eq(domain.getId()), eq(recordName), eq(recordIp), eq("A"))).thenReturn(record); - when(_domainApi.createReverseDomain(eq(reverseDomainName), eq(TEMPLATE_ID), eq("M"))).thenReturn(reverseDomain); - when(_recordApi.createRecord(eq(reverseDomain.getId()), eq(reverseRecordName), eq(reverseRecordContent), eq("PTR"))).thenReturn(record); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateRecordAndReverseCommand(recordName, recordIp, domainName, TEMPLATE_ID, true)); - assertNotNull(answer); - assertEquals(true, answer.getResult()); - verify(_exportApi, times(1)).scheduleExport(); - } - - @Test - public void testCreateRecordAndReverseWhenDomainDoesNotExistAndOverrideIsFalse() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - String reverseRecordContent = recordName + "." + domainName; - - Domain domain = new Domain(); - domain.getDomainAttributes().setId(sequenceId++); - Domain reverseDomain = new Domain(); - reverseDomain.getDomainAttributes().setId(sequenceId++); - - Record record = new Record(); - - when(_domainApi.listByQuery(domainName)).thenReturn(new ArrayList()); - when(_domainApi.createDomain(eq(domainName), eq(TEMPLATE_ID), eq("M"))).thenReturn(domain); - when(_recordApi.createRecord(eq(domain.getId()), eq(recordName), eq(recordIp), eq("A"))).thenReturn(record); - when(_domainApi.createReverseDomain(eq(reverseDomainName), eq(TEMPLATE_ID), eq("M"))).thenReturn(reverseDomain); - when(_recordApi.createRecord(eq(reverseDomain.getId()), eq(reverseRecordName), eq(reverseRecordContent), eq("PTR"))).thenReturn(record); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateRecordAndReverseCommand(recordName, recordIp, domainName, TEMPLATE_ID, false)); - assertNotNull(answer); - assertEquals(true, answer.getResult()); - verify(_exportApi, times(1)).scheduleExport(); - } - - ///////////////////////// - // Update Record tests // - ///////////////////////// - - @Test - public void testUpdateRecordAndReverseWhenDomainExistsAndOverrideIsTrue() throws Exception { - String recordName = "recordname"; - String oldRecordIp = "40.30.20.10"; - String newRecordIp = "50.40.30.20"; - String domainName = "domain.name.com"; - String reverseDomainName = "30.40.50.in-addr.arpa"; - String reverseRecordName = "20"; - String reverseRecordContent = recordName + "." + domainName; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, oldRecordIp, false); - Domain reverseDomain = generateFakeDomain(reverseDomainName, true); - Record reverseRecord = generateFakeRecord(reverseDomain, reverseRecordName, "X", true); - - Answer answer = _globoDnsResource.execute(new CreateOrUpdateRecordAndReverseCommand(recordName, newRecordIp, domainName, TEMPLATE_ID, true)); - - // ensure calls in sequence to ensure this call are the only ones. - InOrder inOrder = inOrder(_recordApi); - inOrder.verify(_recordApi, times(1)).updateRecord(eq(record.getId()), eq(domain.getId()), eq(recordName), eq(newRecordIp)); - inOrder.verify(_recordApi, times(1)).updateRecord(eq(reverseRecord.getId()), eq(reverseDomain.getId()), eq(reverseRecordName), eq(reverseRecordContent)); - - assertNotNull(answer); - assertEquals(true, answer.getResult()); - verify(_exportApi, times(1)).scheduleExport(); - } - - ///////////////////////// - // Remove Record tests // - ///////////////////////// - - @Test - public void testRemoveRecordWhenRecordExists() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - String reverseRecordContent = recordName + "." + domainName; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, recordIp, false); - Domain reverseDomain = generateFakeDomain(reverseDomainName, true); - Record reverseRecord = generateFakeRecord(reverseDomain, reverseRecordName, reverseRecordContent, true); - - Answer answer = _globoDnsResource.execute(new RemoveRecordCommand(recordName, recordIp, domainName, true)); - - assertNotNull(answer); - assertEquals(true, answer.getResult()); - verify(_recordApi, times(1)).removeRecord(eq(record.getId())); - verify(_recordApi, times(1)).removeRecord(eq(reverseRecord.getId())); - verify(_exportApi, times(1)).scheduleExport(); - } - - @Test - public void testRemoveRecordWithSuccessAndReverseRecordNotRemovedWhenReverseRecordExistsWithDifferentValueAndOverrideIsFalse() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, recordIp, false); - Domain reverseDomain = generateFakeDomain(reverseDomainName, true); - Record reverseRecord = generateFakeRecord(reverseDomain, reverseRecordName, "X", true); - - Answer answer = _globoDnsResource.execute(new RemoveRecordCommand(recordName, recordIp, domainName, false)); - - assertEquals(true, answer.getResult()); - verify(_recordApi, times(1)).removeRecord(eq(record.getId())); - verify(_recordApi, never()).removeRecord(eq(reverseRecord.getId())); - verify(_exportApi, times(1)).scheduleExport(); - } - - @Test - public void testRemoveReverseRecordButNotRemoveRecordWhenRecordExistsWithDifferentValueAndOverrideIsFalse() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - String reverseDomainName = "20.30.40.in-addr.arpa"; - String reverseRecordName = "10"; - String reverseRecordContent = recordName + "." + domainName; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, "X", false); - Domain reverseDomain = generateFakeDomain(reverseDomainName, true); - Record reverseRecord = generateFakeRecord(reverseDomain, reverseRecordName, reverseRecordContent, true); - - Answer answer = _globoDnsResource.execute(new RemoveRecordCommand(recordName, recordIp, domainName, false)); - - assertEquals(true, answer.getResult()); - verify(_recordApi, never()).removeRecord(eq(record.getId())); - verify(_recordApi, times(1)).removeRecord(eq(reverseRecord.getId())); - verify(_exportApi, times(1)).scheduleExport(); - } - - ///////////////////////// - // Remove Domain tests // - ///////////////////////// - - @Test - public void testRemoveDomainWithSuccessButDomainKeptWhenDomainExistsAndThereAreRecordsAndOverrideIsFalse() throws Exception { - String recordName = "recordname"; - String recordIp = "40.30.20.10"; - String domainName = "domain.name.com"; - - Domain domain = generateFakeDomain(domainName, false); - Record record = generateFakeRecord(domain, recordName, "X", false); - when(_recordApi.listAll(domain.getId())).thenReturn(Arrays.asList(record)); - - Answer answer = _globoDnsResource.execute(new RemoveRecordCommand(recordName, recordIp, domainName, false)); - - assertEquals(true, answer.getResult()); - verify(_domainApi, never()).removeDomain(any(Long.class)); - verify(_exportApi, never()).scheduleExport(); - } - - @Test - public void testRemoveDomainWithSuccessWhenDomainExistsAndThereAreOnlyNSRecordsAndOverrideIsFalse() throws Exception { - String domainName = "domain.name.com"; - - Domain domain = generateFakeDomain(domainName, false); - List recordList = new ArrayList(); - for (int i = 0; i < 10; i++) { - Record record = new Record(); - record.getTypeNSRecordAttributes().setDomainId(domain.getId()); - record.getTypeNSRecordAttributes().setId(sequenceId++); - record.getTypeNSRecordAttributes().setType("NS"); - recordList.add(record); - } - when(_recordApi.listAll(domain.getId())).thenReturn(recordList); - - Answer answer = _globoDnsResource.execute(new RemoveDomainCommand(domainName, false)); - - assertEquals(true, answer.getResult()); - verify(_domainApi, times(1)).removeDomain(eq(domain.getId())); - verify(_exportApi, times(1)).scheduleExport(); - } - - @Test - public void testRemoveDomainWithSuccessWhenDomainExistsAndThereAreRecordsAndOverrideIsTrue() throws Exception { - String domainName = "domain.name.com"; - - Domain domain = generateFakeDomain(domainName, false); - List recordList = new ArrayList(); - for (int i = 0; i < 10; i++) { - Record record = new Record(); - record.getTypeNSRecordAttributes().setDomainId(domain.getId()); - record.getTypeNSRecordAttributes().setId(sequenceId++); - record.getTypeNSRecordAttributes().setType(new String[] {"A", "NS", "PTR"}[i % 3]); - recordList.add(record); - } - when(_recordApi.listAll(domain.getId())).thenReturn(recordList); - - Answer answer = _globoDnsResource.execute(new RemoveDomainCommand(domainName, true)); - - assertEquals(true, answer.getResult()); - verify(_domainApi, times(1)).removeDomain(eq(domain.getId())); - verify(_exportApi, times(1)).scheduleExport(); - } - -} diff --git a/plugins/network-elements/globodns/src/test/resources/db.properties b/plugins/network-elements/globodns/src/test/resources/db.properties deleted file mode 100644 index f62d76dd7aeb..000000000000 --- a/plugins/network-elements/globodns/src/test/resources/db.properties +++ /dev/null @@ -1,73 +0,0 @@ -# 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. - - -# management server clustering parameters, change cluster.node.IP to the machine IP address -# in which the management server is running -cluster.node.IP=127.0.0.1 -cluster.servlet.port=9090 -region.id=1 - -# CloudStack database settings -db.cloud.username=cloud -db.cloud.password=cloud -db.root.password= -db.cloud.host=localhost -db.cloud.driver=jdbc:mysql -db.cloud.port=3306 -db.cloud.name=cloud - -# CloudStack database tuning parameters -db.cloud.maxActive=250 -db.cloud.maxIdle=30 -db.cloud.maxWait=10000 -db.cloud.autoReconnect=true -db.cloud.validationQuery=SELECT 1 -db.cloud.testOnBorrow=true -db.cloud.testWhileIdle=true -db.cloud.timeBetweenEvictionRunsMillis=40000 -db.cloud.minEvictableIdleTimeMillis=240000 -db.cloud.poolPreparedStatements=false -db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true&prepStmtCacheSqlLimit=4096 - -# usage database settings -db.usage.username=cloud -db.usage.password=cloud -db.usage.host=localhost -# It's not guaranteed that using a different DB provider than the one from the regular cloud DB will work -db.usage.driver=jdbc:mysql -db.usage.port=3306 -db.usage.name=cloud_usage - -# usage database tuning parameters -db.usage.maxActive=100 -db.usage.maxIdle=30 -db.usage.maxWait=10000 -db.usage.autoReconnect=true - -# Simulator database settings -db.simulator.username=cloud -db.simulator.password=cloud -db.simulator.host=localhost -# It's not guaranteed that using a different DB provider than the one from the regular cloud DB will work -db.simulator.driver=jdbc:mysql -db.simulator.port=3306 -db.simulator.name=simulator -db.simulator.maxActive=250 -db.simulator.maxIdle=30 -db.simulator.maxWait=10000 -db.simulator.autoReconnect=true diff --git a/plugins/network-elements/globodns/src/test/resources/log4j.properties b/plugins/network-elements/globodns/src/test/resources/log4j.properties deleted file mode 100644 index 8b1d961f7b63..000000000000 --- a/plugins/network-elements/globodns/src/test/resources/log4j.properties +++ /dev/null @@ -1,33 +0,0 @@ -# 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. - -# Define the root logger with appender file -#log = /var/log/log4j -#log4j.rootLogger = DEBUG, FILE -log4j.rootLogger = DEBUG, stdout - -# File appender -#log4j.appender.FILE=org.apache.log4j.FileAppender -#log4j.appender.FILE.File=${log}/log.out -#log4j.appender.FILE.layout=org.apache.log4j.PatternLayout -#log4j.appender.FILE.layout.conversionPattern=%m%n - -# Stdout appender -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/plugins/network-elements/juniper-contrail/pom.xml b/plugins/network-elements/juniper-contrail/pom.xml deleted file mode 100644 index 6d76cedf8ddb..000000000000 --- a/plugins/network-elements/juniper-contrail/pom.xml +++ /dev/null @@ -1,146 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-contrail - Apache CloudStack Plugin - Network Juniper Contrail - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - org.apache.cloudstack - cloud-api - ${project.version} - - - org.apache.cloudstack - cloud-server - ${project.version} - - - org.apache.cloudstack - cloud-plugin-hypervisor-xenserver - ${project.version} - test - - - org.apache.cloudstack - cloud-plugin-network-internallb - ${project.version} - - - org.apache.cloudstack - cloud-engine-orchestration - ${project.version} - test - - - org.apache.cloudstack - cloud-engine-api - ${project.version} - - - org.apache.cloudstack - cloud-engine-schema - ${project.version} - - - org.apache.cloudstack - cloud-framework-config - ${project.version} - - - org.apache.cloudstack - cloud-framework-events - ${project.version} - - - org.apache.cloudstack - cloud-utils - ${project.version} - - - xml-apis - xml-apis - - - - - org.apache.cloudstack - cloud-framework-spring-lifecycle - ${project.version} - test - - - org.eclipse.jetty - jetty-security - ${cs.jetty.version} - test - - - com.google.guava - guava - - - net.juniper.contrail - juniper-contrail-api - 1.0-SNAPSHOT - - - log4j - log4j - - - - - ch.qos.reload4j - reload4j - - - com.mysql - mysql-connector-j - provided - - - org.apache.commons - commons-exec - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - always - @{argLine} -Xmx1024m - - **/NetworkProviderTest.java - **/PublicNetworkTest.java - - - - - - diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java deleted file mode 100644 index 4c0f29c8c8a8..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/command/CreateServiceInstanceCmd.java +++ /dev/null @@ -1,201 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.api.command; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiCommandResourceType; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCreateCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.DomainResponse; -import org.apache.cloudstack.api.response.NetworkResponse; -import org.apache.cloudstack.api.response.ProjectResponse; -import org.apache.cloudstack.api.response.ServiceOfferingResponse; -import org.apache.cloudstack.api.response.TemplateResponse; -import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; -import org.apache.cloudstack.network.contrail.management.ServiceManager; -import org.apache.cloudstack.network.contrail.management.ServiceVirtualMachine; - -import com.cloud.dc.DataCenter; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.offering.ServiceOffering; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.Account; - -@APICommand(name = "createServiceInstance", - description = "Creates a system virtual-machine that implements network services", - responseObject = ServiceInstanceResponse.class, - requestHasSensitiveInfo = false, - responseHasSensitiveInfo = false) -public class CreateServiceInstanceCmd extends BaseAsyncCreateCmd { - - /// API parameters - @Parameter(name = ApiConstants.ZONE_ID, - type = CommandType.UUID, - entityType = ZoneResponse.class, - required = true, - description = "Availability zone for the service instance") - private Long zoneId; - - //Owner information - @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "An optional account for the virtual machine. Must be used with domainId.") - private String accountName; - - @Parameter(name = ApiConstants.DOMAIN_ID, - type = CommandType.UUID, - entityType = DomainResponse.class, - description = "An optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") - private Long domainId; - - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Project ID for the service instance") - private Long projectId; - - @Parameter(name = "leftnetworkid", - type = CommandType.UUID, - entityType = NetworkResponse.class, - required = true, - description = "The left (inside) network for service instance") - private Long leftNetworkId; - - @Parameter(name = "rightnetworkid", - type = CommandType.UUID, - entityType = NetworkResponse.class, - required = true, - description = "The right (outside) network ID for the service instance") - private Long rightNetworkId; - - @Parameter(name = ApiConstants.TEMPLATE_ID, - type = CommandType.UUID, - entityType = TemplateResponse.class, - required = true, - description = "The template ID that specifies the image for the service appliance") - private Long templateId; - - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, - type = CommandType.UUID, - entityType = ServiceOfferingResponse.class, - required = true, - description = "The service offering ID that defines the resources consumed by the service appliance") - private Long serviceOfferingId; - - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, - required = true, description = "The name of the service instance") - private String name; - - /// Implementation - @Inject - ServiceManager _vrouterService; - - @Override - public void create() throws ResourceAllocationException { - // Parameter validation - try { - DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); - if (zone == null) { - throw new InvalidParameterValueException("Unable to find zone ID " + zoneId); - } - - Account owner = _accountService.getActiveAccountById(getEntityOwnerId()); - - VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId); - if (template == null) { - throw new InvalidParameterValueException("Invalid template ID " + templateId); - } - - ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId); - if (serviceOffering == null) { - throw new InvalidParameterValueException("Invalid service offering ID " + serviceOfferingId); - } - - Network left = _networkService.getNetwork(leftNetworkId); - if (left == null) { - throw new InvalidParameterValueException("Invalid ID for left network " + leftNetworkId); - } - - Network right = _networkService.getNetwork(rightNetworkId); - if (right == null) { - throw new InvalidParameterValueException("Invalid ID for right network " + rightNetworkId); - } - - if (name.isEmpty()) { - throw new InvalidParameterValueException("service instance name is empty"); - } - - ServiceVirtualMachine svm = _vrouterService.createServiceInstance(zone, owner, template, serviceOffering, name, left, right); - if (svm == null) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Unable to create service instance"); - } - setEntityId(svm.getId()); - setEntityUuid(svm.getUuid()); - } catch (Exception ex) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); - } - } - - @Override - public String getEventType() { - return EventTypes.EVENT_VM_CREATE; - } - - @Override - public String getEventDescription() { - return "Create service instance"; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException, NetworkRuleConflictException { - try { - _vrouterService.startServiceInstance(getEntityId()); - ServiceInstanceResponse response = _vrouterService.createServiceInstanceResponse(getEntityId()); - response.setObjectName("serviceinstance"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception ex) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - Long accountId = _accountService.finalizeAccountId(accountName, domainId, projectId, true); - if (accountId == null) { - return CallContext.current().getCallingAccount().getId(); - } - - return accountId; - } - - @Override - public ApiCommandResourceType getApiResourceType() { - return ApiCommandResourceType.SystemVm; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java deleted file mode 100644 index 5bf429854095..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/api/response/ServiceInstanceResponse.java +++ /dev/null @@ -1,99 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.response.ControlledEntityResponse; - -import com.cloud.serializer.Param; - -public class ServiceInstanceResponse extends BaseResponse implements ControlledEntityResponse { - - @SerializedName(ApiConstants.ID) - @Param(description = "The ID of the Instance") - private String id; - - @SerializedName(ApiConstants.NAME) - @Param(description = "The name of the Instance") - private String name; - - @SerializedName("displayname") - @Param(description = "User generated name. The name of the Instance is returned if no displayname exists.") - private String displayName; - - @SerializedName(ApiConstants.ACCOUNT) - @Param(description = "The account associated with the Instance") - private String accountName; - - @SerializedName(ApiConstants.PROJECT_ID) - @Param(description = "The project ID of the Instance") - private String projectId; - - @SerializedName(ApiConstants.PROJECT) - @Param(description = "The project name of the vm") - private String projectName; - - @SerializedName(ApiConstants.DOMAIN_ID) - @Param(description = "The ID of the domain in which the Instance exists") - private String domainId; - - @SerializedName(ApiConstants.DOMAIN) - @Param(description = "The name of the domain in which the Instance exists") - private String domainName; - - @SerializedName(ApiConstants.DOMAIN_PATH) - @Param(description = "Path of the Domain in which the Instance exists", since = "4.19.2.0") - private String domainPath; - - public void setId(String id) { - this.id = id; - } - - @Override - public void setAccountName(String accountName) { - this.accountName = accountName; - } - - @Override - public void setProjectId(String projectId) { - this.projectId = projectId; - } - - @Override - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - @Override - public void setDomainId(String domainId) { - this.domainId = domainId; - } - - @Override - public void setDomainName(String domainName) { - this.domainName = domainName; - } - - @Override - public void setDomainPath(String domainPath) { - this.domainPath = domainPath; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElement.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElement.java deleted file mode 100644 index 28680dfb8fd5..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElement.java +++ /dev/null @@ -1,28 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import com.cloud.utils.component.PluggableService; - -// Network Provider plugin -public interface ContrailElement extends PluggableService { - /** - * TODO: - * define APIs to configure the Network Virtualization service. - */ -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java deleted file mode 100644 index 7d02a1d54970..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailElementImpl.java +++ /dev/null @@ -1,384 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; - -import org.apache.cloudstack.network.contrail.api.command.CreateServiceInstanceCmd; -import org.apache.cloudstack.network.contrail.model.InstanceIpModel; -import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; -import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; -import org.springframework.stereotype.Component; - -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.IpAddress; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.element.DhcpServiceProvider; -import com.cloud.network.element.IpDeployer; -import com.cloud.network.element.SourceNatServiceProvider; -import com.cloud.network.element.StaticNatServiceProvider; -import com.cloud.network.rules.StaticNat; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.server.ConfigurationServer; -import com.cloud.server.ConfigurationServerImpl; -import com.cloud.utils.component.AdapterBase; -import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.NicDao; - - -@Component - -public class ContrailElementImpl extends AdapterBase - implements ContrailElement, StaticNatServiceProvider, IpDeployer, SourceNatServiceProvider, DhcpServiceProvider { - private final Map> _capabilities = InitCapabilities(); - - @Inject - ResourceManager _resourceMgr; - @Inject - ConfigurationServer _configServer; - @Inject - NetworkDao _networksDao; - @Inject - ContrailManager _manager; - @Inject - NicDao _nicDao; - @Inject - ServerDBSync _dbSync; - - // PluggableService - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(CreateServiceInstanceCmd.class); - return cmdList; - } - - // NetworkElement API - @Override - public Provider getProvider() { - return Provider.JuniperContrailRouter; - } - - private static Map> InitCapabilities() { - Map> capabilities = new HashMap>(); - capabilities.put(Service.Connectivity, null); - capabilities.put(Service.Dhcp, new HashMap()); - capabilities.put(Service.StaticNat, null); - capabilities.put(Service.SourceNat, null); - - return capabilities; - } - - @Override - public Map> getCapabilities() { - return _capabilities; - } - - /** - * Network add/update. - */ - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - logger.debug(String.format("NetworkElement implement: %s, traffic type: %s", network, network.getTrafficType())); - if (network.getTrafficType() == TrafficType.Guest) { - logger.debug(String.format("ignore network %s", network)); - return true; - } - VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - - if (vnModel == null) { - vnModel = new VirtualNetworkModel(network, network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - vnModel.setProperties(_manager.getModelController(), network); - } - try { - if (!vnModel.verify(_manager.getModelController())) { - vnModel.update(_manager.getModelController()); - } - _manager.getDatabase().getVirtualNetworks().add(vnModel); - } catch (Exception ex) { - logger.warn("virtual-network update: ", ex); - } - return true; - } - - @Override - public boolean prepare(Network network, NicProfile nicProfile, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - - logger.debug(String.format("NetworkElement prepare: %s, traffic type: %s", network, network.getTrafficType())); - - if (network.getTrafficType() == TrafficType.Guest) { - logger.debug(String.format("ignore network %s", network)); - return true; - } - - VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - - if (vnModel == null) { - // There is no notification after a physical network is associated with the VRouter NetworkOffering - // this may be the first time we see this network. - return false; - } - - VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); - if (vmModel == null) { - VMInstanceVO vmVo = (VMInstanceVO)vm.getVirtualMachine(); - vmModel = new VirtualMachineModel(vmVo, vm.getUuid()); - vmModel.setProperties(_manager.getModelController(), vmVo); - } - - NicVO nic = _nicDao.findById(nicProfile.getId()); - assert nic != null; - - VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); - if (vmiModel == null) { - vmiModel = new VMInterfaceModel(nic.getUuid()); - vmiModel.addToVirtualMachine(vmModel); - vmiModel.addToVirtualNetwork(vnModel); - } - - try { - vmiModel.build(_manager.getModelController(), (VMInstanceVO)vm.getVirtualMachine(), nic); - } catch (IOException ex) { - logger.warn("vm interface set", ex); - return false; - } - - InstanceIpModel ipModel = vmiModel.getInstanceIp(); - if (ipModel == null) { - ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId()); - ipModel.addToVMInterface(vmiModel); - } - ipModel.setAddress(nicProfile.getIPv4Address()); - - try { - vmModel.update(_manager.getModelController()); - } catch (Exception ex) { - logger.warn("virtual-machine-update", ex); - return false; - } - _manager.getDatabase().getVirtualMachines().add(vmModel); - - return true; - } - - @Override - public boolean release(Network network, NicProfile nicProfile, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - if (network.getTrafficType() == TrafficType.Guest) { - return true; - } else if (!_manager.isManagedPhysicalNetwork(network)) { - logger.debug(String.format("release ignore network %s", network)); - return true; - } - - NicVO nic = _nicDao.findById(nicProfile.getId()); - assert nic != null; - - VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); - if (vmModel == null) { - logger.debug(String.format("vm %s not in local database", vm)); - return true; - } - VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); - if (vmiModel != null) { - try { - vmiModel.destroy(_manager.getModelController()); - } catch (IOException ex) { - logger.warn("virtual-machine-interface delete", ex); - } - vmModel.removeSuccessor(vmiModel); - } - - if (!vmModel.hasDescendents()) { - _manager.getDatabase().getVirtualMachines().remove(vmModel); - try { - vmModel.delete(_manager.getModelController()); - } catch (IOException e) { - return false; - } - } - - return true; - } - - /** - * Network disable - */ - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - logger.debug("NetworkElement shutdown"); - return true; - } - - /** - * Network delete - */ - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - logger.debug("NetworkElement destroy"); - return true; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - Map serviceMap = ((ConfigurationServerImpl)_configServer).getServicesAndProvidersForNetwork( _manager.getRouterOffering().getId()); - List types = new ArrayList(); - types.add(TrafficType.Control); - types.add(TrafficType.Management); - types.add(TrafficType.Storage); - List systemNets = _manager.findSystemNetworks(types); - if (systemNets != null && !systemNets.isEmpty()) { - for (NetworkVO net: systemNets) { - logger.debug(String.format("update system network service: %s; service provider: %s", net, serviceMap)); - _networksDao.update(net.getId(), net, serviceMap); - } - } else { - logger.debug("no system networks created yet"); - } - serviceMap = ((ConfigurationServerImpl)_configServer).getServicesAndProvidersForNetwork( _manager.getPublicRouterOffering().getId()); - types = new ArrayList(); - types.add(TrafficType.Public); - systemNets = _manager.findSystemNetworks(types); - if (systemNets != null && !systemNets.isEmpty()) { - for (NetworkVO net: systemNets) { - logger.debug(String.format("update system network service: %s; service provider: %s", net, serviceMap)); - _networksDao.update(net.getId(), net, serviceMap); - } - } else { - logger.debug("no system networks created yet"); - } - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - logger.debug("NetworkElement shutdown ProviderInstances"); - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - // TODO Auto-generated method stub - logger.debug("NetworkElement verifyServices"); - logger.debug("Services: " + services); - return true; - } - - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } - - @Override - public boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException { - - for (PublicIpAddress ip : ipAddress) { - if (ip.isSourceNat()) { - continue; - } - if (isFloatingIpCreate(ip)) { - if (_manager.createFloatingIp(ip)) { - logger.debug("Successfully created floating IP: " + ip.getAddress().addr()); - } - } else { - if (_manager.deleteFloatingIp(ip)) { - logger.debug("Successfully deleted floating IP: " + ip.getAddress().addr()); - } - } - } - return true; - } - - @Override - public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { - return true; - } - - private boolean isFloatingIpCreate(PublicIpAddress ip) { - if (ip.getState() == IpAddress.State.Allocated && ip.getAssociatedWithVmId() != null && !ip.isSourceNat()) { - return true; - } - return false; - } - - @Override - public boolean addDhcpEntry(Network network, NicProfile nic, - VirtualMachineProfile vm, - DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, InsufficientCapacityException, - ResourceUnavailableException { - return false; - } - - @Override - public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, - VirtualMachineProfile vm, - DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, InsufficientCapacityException, - ResourceUnavailableException { - return false; - } - - @Override - public boolean removeDhcpSupportForSubnet(Network network) - throws ResourceUnavailableException { - return false; - } - - @Override - public boolean setExtraDhcpOptions(Network network, long nicId, Map dhcpOptions) { - return false; - } - - @Override - public boolean removeDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile vmProfile) { - return false; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailGuru.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailGuru.java deleted file mode 100644 index 82c7415f80fd..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailGuru.java +++ /dev/null @@ -1,392 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.net.URI; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.network.contrail.model.InstanceIpModel; -import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; -import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; - -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkProfile; -import com.cloud.network.Networks.AddressFormat; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.Mode; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.guru.NetworkGuru; -import com.cloud.offering.NetworkOffering; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.Nic.ReservationStrategy; -import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.NicDao; - -import net.juniper.contrail.api.types.MacAddressesType; -import net.juniper.contrail.api.types.VirtualMachineInterface; - -public class ContrailGuru extends AdapterBase implements NetworkGuru { - @Inject - NetworkDao _networkDao; - @Inject - ContrailManager _manager; - @Inject - NicDao _nicDao; - @Inject - IPAddressDao _ipAddressDao; - @Inject - AccountManager _accountMgr; - @Inject - IpAddressManager _ipAddrMgr; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - DataCenterDao _dcDao; - - private static final TrafficType[] TrafficTypes = {TrafficType.Guest}; - - private boolean canHandle(NetworkOffering offering, NetworkType networkType, PhysicalNetwork physicalNetwork) { - if (physicalNetwork == null) { - // Physical network can be false for system network during initial setup of CloudStack - return false; - } - - if (_manager.getRouterOffering() == null || _manager.getVpcRouterOffering() == null) { - // FIXME The resource is apparently not configured, we need another way to check this. - return false; - } - - if (networkType == NetworkType.Advanced - && (offering.getId() == _manager.getRouterOffering().getId() || offering.getId() == _manager.getVpcRouterOffering().getId()) - && isMyTrafficType(offering.getTrafficType()) - && offering.getGuestType() == Network.GuestType.Isolated - && physicalNetwork.getIsolationMethods().contains("L3VPN")) - return true; - - return false; - } - - @Override - public String getName() { - return "ContrailGuru"; - } - - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, String name, Long vpcId, Account owner) { - // Check of the isolation type of the related physical network is L3VPN - PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); - DataCenter dc = _dcDao.findById(plan.getDataCenterId()); - if (!canHandle(offering, dc.getNetworkType(),physnet)) { - logger.debug("Refusing to design this network"); - return null; - } - NetworkVO network = - new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, offering.getId(), State.Allocated, plan.getDataCenterId(), - plan.getPhysicalNetworkId(), offering.isRedundantRouter()); - if (userSpecified.getCidr() != null) { - network.setCidr(userSpecified.getCidr()); - network.setGateway(userSpecified.getGateway()); - } - logger.debug("Allocated network {}{}", userSpecified, network.getCidr() == null ? "" : " subnet: " + network.getCidr()); - return network; - } - - @Override - public void setup(Network network, long networkId) { - // do nothing - } - - @Override - public Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException { - logger.debug("Implement network: {}, traffic type: {}", network, network.getTrafficType()); - - VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - if (vnModel == null) { - vnModel = new VirtualNetworkModel(network, network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - vnModel.setProperties(_manager.getModelController(), network); - } - - try { - if (!vnModel.verify(_manager.getModelController())) { - vnModel.update(_manager.getModelController()); - } - } catch (Exception ex) { - logger.warn("virtual-network update: ", ex); - return network; - } - _manager.getDatabase().getVirtualNetworks().add(vnModel); - - if (network.getVpcId() != null) { - List ips = _ipAddressDao.listByAssociatedVpc(network.getVpcId(), true); - if (ips.isEmpty()) { - logger.debug("Creating a source nat ip for network " + network); - Account owner = _accountMgr.getAccount(network.getAccountId()); - try { - PublicIp publicIp = _ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network); - IPAddressVO ip = publicIp.ip(); - ip.setVpcId(network.getVpcId()); - _ipAddressDao.acquireInLockTable(ip.getId()); - _ipAddressDao.update(ip.getId(), ip); - _ipAddressDao.releaseFromLockTable(ip.getId()); - } catch (Exception e) { - logger.error("Unable to allocate source NAT IP: " + e); - } - } - } - - return network; - } - - /** - * Allocate the NicProfile object. - * At this point the UUID of the nic is not yet known. We defer allocating the VMI and instance-ip objects - * until the reserve API is called because of this reason. - */ - @Override - public NicProfile allocate(Network network, NicProfile profile, VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapacityException, - InsufficientAddressCapacityException, ConcurrentOperationException { - logger.debug(String.format("allocate NicProfile on %s", network)); - - if (profile != null && profile.getRequestedIPv4() != null) { - throw new CloudRuntimeException("Does not support custom ip allocation at this time: " + profile); - } - if (profile == null) { - profile = new NicProfile(ReservationStrategy.Create, null, null, null, null); - } - - profile.setReservationStrategy(ReservationStrategy.Start); - URI broadcastUri = null; - try { - broadcastUri = new URI("vlan://untagged"); - } catch (Exception e) { - logger.warn("unable to instantiate broadcast URI: " + e); - } - profile.setBroadcastUri(broadcastUri); - - return profile; - } - - /** - * Allocate the ip address (and mac) for the specified VM device. - */ - @Override - public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException { - logger.debug("reserve NicProfile on network: " + network); - logger.debug(String.format("nic: %s deviceId: %d", nic, nic.getDeviceId())); - - NicVO nicVO = _nicDao.findById(nic.getId()); - assert nicVO != null; - - VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - /* Network must have been implemented */ - assert vnModel != null; - - VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); - if (vmModel == null) { - VMInstanceVO vmVo = (VMInstanceVO)vm.getVirtualMachine(); - vmModel = new VirtualMachineModel(vmVo, vm.getUuid()); - vmModel.setProperties(_manager.getModelController(), vmVo); - } - - VMInterfaceModel vmiModel = vmModel.getVMInterface(nicVO.getUuid()); - if (vmiModel == null) { - vmiModel = new VMInterfaceModel(nicVO.getUuid()); - vmiModel.addToVirtualMachine(vmModel); - vmiModel.addToVirtualNetwork(vnModel); - } - try { - vmiModel.build(_manager.getModelController(), (VMInstanceVO)vm.getVirtualMachine(), nicVO); - vmiModel.setActive(); - } catch (IOException ex) { - logger.error("virtual-machine-interface set", ex); - return; - } - - InstanceIpModel ipModel = vmiModel.getInstanceIp(); - if (ipModel == null) { - ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId()); - ipModel.addToVMInterface(vmiModel); - } else { - logger.debug("Reuse existing instance-ip object on " + ipModel.getName()); - } - if (nic.getIPv4Address() != null) { - logger.debug("Nic using existing IP address " + nic.getIPv4Address()); - ipModel.setAddress(nic.getIPv4Address()); - } - - try { - vmModel.update(_manager.getModelController()); - } catch (Exception ex) { - logger.warn("virtual-machine update", ex); - return; - } - - _manager.getDatabase().getVirtualMachines().add(vmModel); - - VirtualMachineInterface vmi = vmiModel.getVMInterface(); - // allocate mac address - if (nic.getMacAddress() == null) { - MacAddressesType macs = vmi.getMacAddresses(); - if (macs == null) { - logger.debug(String.format("no mac address is allocated for Nic %s", nicVO)); - } else { - logger.info("VMI " + _manager.getVifNameByVmUuid(vm.getUuid(), nicVO.getDeviceId()) + " got mac address: " + macs.getMacAddress().get(0)); - nic.setMacAddress(macs.getMacAddress().get(0)); - } - } - - if (nic.getIPv4Address() == null) { - logger.debug("Allocated IP address " + ipModel.getAddress()); - nic.setIPv4Address(ipModel.getAddress()); - if (network.getCidr() != null) { - nic.setIPv4Netmask(NetUtils.cidr2Netmask(network.getCidr())); - } - nic.setIPv4Gateway(network.getGateway()); - nic.setFormat(AddressFormat.Ip4); - } - } - - /** - * When a VM is stopped this API is called to release transient resources. - */ - @Override - public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { - - logger.debug(String.format("release NicProfile %s", nic)); - - return true; - } - - /** - * Release permanent resources of a Nic (VMI and addresses). - */ - @Override - public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) { - logger.debug(String.format("deallocate NicProfile %s on %s", nic, network.getName())); - NicVO nicVO = _nicDao.findById(nic.getId()); - assert nicVO != null; - - VirtualMachineModel vmModel = _manager.getDatabase().lookupVirtualMachine(vm.getUuid()); - if (vmModel == null) { - return; - } - VMInterfaceModel vmiModel = vmModel.getVMInterface(nicVO.getUuid()); - if (vmiModel == null) { - return; - } - try { - vmiModel.destroy(_manager.getModelController()); - } catch (IOException ex) { - return; - } - vmModel.removeSuccessor(vmiModel); - - if (!vmModel.hasDescendents()) { - _manager.getDatabase().getVirtualMachines().remove(vmModel); - try { - vmModel.delete(_manager.getModelController()); - } catch (IOException ex) { - logger.warn("virtual-machine delete", ex); - return; - } - } - - } - - @Override - public void updateNicProfile(NicProfile profile, Network network) { - // TODO Auto-generated method stub - logger.debug(String.format("update NicProfile %s on %s", profile, network)); - } - - @Override - public void shutdown(NetworkProfile network, NetworkOffering offering) { - logger.debug("NetworkGuru shutdown"); - VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - if (vnModel == null) { - return; - } - try { - _manager.getDatabase().getVirtualNetworks().remove(vnModel); - vnModel.delete(_manager.getModelController()); - } catch (IOException e) { - logger.warn("virtual-network delete", e); - } - } - - @Override - public boolean trash(Network network, NetworkOffering offering) { - // TODO Auto-generated method stub - logger.debug("NetworkGuru trash"); - return true; - } - - @Override - public void updateNetworkProfile(NetworkProfile networkProfile) { - // TODO Auto-generated method stub - logger.debug("NetworkGuru updateNetworkProfile"); - } - - @Override - public TrafficType[] getSupportedTrafficType() { - return TrafficTypes; - } - - @Override - public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : TrafficTypes) { - if (t == type) { - return true; - } - } - return false; - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManager.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManager.java deleted file mode 100644 index 1fe13035fb16..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManager.java +++ /dev/null @@ -1,143 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.util.List; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.types.FloatingIp; -import net.juniper.contrail.api.types.NetworkPolicy; -import net.juniper.contrail.api.types.VirtualNetwork; - -import org.apache.cloudstack.network.contrail.model.ModelController; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; - -import com.cloud.domain.DomainVO; -import com.cloud.network.Network; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.offering.NetworkOffering; -import com.cloud.projects.ProjectVO; -import com.cloud.network.vpc.NetworkACLVO; -import com.cloud.network.vpc.VpcOffering; -import com.cloud.network.vpc.VpcVO; - -public interface ContrailManager { - public static final String routerOfferingName = "Juniper Contrail Network Offering"; - public static final String routerOfferingDisplayText = "Juniper Contrail Network Offering"; - public static final String routerPublicOfferingName = "Juniper Contrail Public Network Offering"; - public static final String routerPublicOfferingDisplayText = "Juniper Contrail Public Network Offering"; - public static final String vpcRouterOfferingName = "Juniper Contrail VPC Network Offering"; - public static final String vpcRouterOfferingDisplayText = "Juniper Contrail VPC Network Offering"; - public static final String juniperVPCOfferingName = "Juniper Contrail VPC Offering"; - public static final String juniperVPCOfferingDisplayText = "Juniper Contrail VPC Offering"; - - public static final int DB_SYNC_INTERVAL_DEFAULT = 600000; - public static final String VNC_ROOT_DOMAIN = "default-domain"; - public static final String VNC_DEFAULT_PROJECT = "default-project"; - public static final String managementNetworkName = "ip-fabric"; - - public NetworkOffering getRouterOffering(); - public NetworkOffering getPublicRouterOffering(); - public NetworkOffering getVpcRouterOffering(); - public VpcOffering getVpcOffering(); - - public void syncNetworkDB(short syncMode) throws IOException; - - public boolean isManagedPhysicalNetwork(Network network); - - /** - * Lookup the virtual network that implements the CloudStack network object. - * @param net_id internal identifier of the NetworkVO object. - * @return the uuid of the virtual network that corresponds to the - * specified CloudStack network. - */ - public String findVirtualNetworkId(Network net) throws IOException; - - public void findInfrastructureNetworks(PhysicalNetworkVO phys, List dbList); - - public String getPhysicalNetworkName(PhysicalNetworkVO physNet); - - public String getCanonicalName(Network net); - - public String getDomainCanonicalName(DomainVO domain); - - public String getProjectCanonicalName(ProjectVO project); - - public String getFQN(Network net); - - public String getDomainName(long domainId); - - public String getProjectName(long accountId); - - public String getDefaultPublicNetworkFQN(); - - public String getProjectId(long domainId, long accountId) throws IOException; - - public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException; - - public net.juniper.contrail.api.types.Project getDefaultVncProject() throws IOException; - - public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain vnc); - - public boolean isSystemRootDomain(DomainVO domain); - - public boolean isSystemDefaultProject(net.juniper.contrail.api.types.Project project); - - public boolean isSystemDefaultProject(ProjectVO project); - - public boolean isSystemDefaultNetwork(VirtualNetwork vnet); - - public boolean isSystemDefaultNetwork(NetworkVO dbNet); - - public String getVifNameByVmName(String vmName, Integer deviceId); - - public String getVifNameByVmUuid(String vmUuid, Integer deviceId); - - public ApiConnector getApiConnector(); - - public ModelDatabase getDatabase(); - - public ModelController getModelController(); - - public List findManagedNetworks(List types); - - public List findSystemNetworks(List types); - - public List findManagedPublicIps(); - - public List findManagedVpcs(); - - public List findManagedACLs(); - - public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException; - - public List getFloatingIps(); - - public VirtualNetworkModel lookupPublicNetworkModel(); - - public boolean createFloatingIp(PublicIpAddress ip); - - public boolean deleteFloatingIp(PublicIpAddress ip); - - public boolean isSystemDefaultNetworkPolicy(NetworkPolicy policy); -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java deleted file mode 100644 index 8badb916eeda..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailManagerImpl.java +++ /dev/null @@ -1,1018 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.cloudstack.network.contrail.model.FloatingIpModel; -import org.apache.cloudstack.network.contrail.model.FloatingIpPoolModel; -import org.apache.cloudstack.network.contrail.model.ModelController; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; - -import com.cloud.configuration.ConfigurationManager; -import com.cloud.configuration.ConfigurationService; -import com.cloud.dc.DataCenter; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.VlanDao; -import com.cloud.domain.Domain; -import com.cloud.domain.DomainVO; -import com.cloud.domain.dao.DomainDao; -import com.cloud.network.Network; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.vpc.NetworkACLVO; -import com.cloud.network.vpc.VpcOffering; -import com.cloud.network.vpc.VpcOfferingVO; -import com.cloud.network.vpc.VpcProvisioningService; -import com.cloud.network.vpc.VpcVO; -import com.cloud.network.vpc.dao.NetworkACLDao; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.network.vpc.dao.VpcOfferingDao; -import com.cloud.offering.NetworkOffering; -import com.cloud.offering.NetworkOffering.Availability; -import com.cloud.offerings.NetworkOfferingVO; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.projects.ProjectVO; -import com.cloud.projects.dao.ProjectDao; -import com.cloud.server.ConfigurationServer; -import com.cloud.user.Account; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.ManagerBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.VMInstanceDao; -import com.google.common.collect.ImmutableList; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorFactory; -import net.juniper.contrail.api.ApiPropertyBase; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.FloatingIp; -import net.juniper.contrail.api.types.FloatingIpPool; -import net.juniper.contrail.api.types.NetworkPolicy; -import net.juniper.contrail.api.types.VirtualNetwork; - -public class ContrailManagerImpl extends ManagerBase implements ContrailManager { - @Inject - public ConfigurationService _configService; - @Inject - ConfigurationServer _configServer; - @Inject - NetworkOfferingDao _networkOfferingDao; - @Inject - DomainDao _domainDao; - @Inject - NetworkDao _networksDao; - @Inject - VMInstanceDao _vmInstanceDao; - @Inject - ProjectDao _projectDao; - @Inject - AccountDao _accountDao; - @Inject - DataCenterDao _dcDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physProviderDao; - @Inject - NicDao _nicDao; - @Inject - ServerDBSync _dbSync; - @Inject - ServerEventHandler _eventHandler; - @Inject - IPAddressDao _ipAddressDao; - @Inject - VlanDao _vlanDao; - @Inject - UserVmDao _vmDao; - @Inject - VpcOfferingDao _vpcOffDao; - @Inject - VpcProvisioningService _vpcProvSvc; - @Inject - VpcDao _vpcDao; - @Inject - NetworkACLDao _networkAclDao; - - - private ApiConnector _api; - - private NetworkOffering _offering; - private NetworkOffering _routerOffering; - private NetworkOffering _routerPublicOffering; - private NetworkOffering _vpcRouterOffering; - private VpcOffering _vpcOffering; - - private Timer _dbSyncTimer; - private int _dbSyncInterval = DB_SYNC_INTERVAL_DEFAULT; - private final String configuration = "contrail.properties"; - private final ModelDatabase _database; - private ModelController _controller; - - ContrailManagerImpl() { - _database = new ModelDatabase(); - } - - @Override - public boolean start() { - if (_api == null) { - return true; - } - /* Start background task */ - _dbSyncTimer = new Timer("DBSyncTimer"); - try { - _dbSyncTimer.schedule(new DBSyncTask(), 0, _dbSyncInterval); - } catch (Exception ex) { - logger.debug("Unable to start DB Sync timer " + ex.getMessage()); - logger.debug("timer start", ex); - } - return true; - } - - @Override - public boolean stop() { - if (_dbSyncTimer != null) { - _dbSyncTimer.cancel(); - } - return true; - } - - @Override - public ModelDatabase getDatabase() { - return _database; - } - - private NetworkOffering locatePublicNetworkOffering(String offeringName, - String offeringDisplayText, Provider provider) { - List offerList = _configService.listNetworkOfferings(TrafficType.Public, false); - for (NetworkOffering offer: offerList) { - if (offer.getName().equals(offeringName)) { - if (offer.getState() != NetworkOffering.State.Enabled) { - return EnableNetworkOffering(offer.getId()); - } - return offer; - } - } - Map> serviceProviderMap = new HashMap>(); - Set providerSet = new HashSet(); - providerSet.add(provider); - final Service[] services = { - Service.Connectivity, - Service.Dhcp, - Service.NetworkACL, - Service.StaticNat, - Service.SourceNat - }; - for (Service svc: services) { - serviceProviderMap.put(svc, providerSet); - } - ConfigurationManager configMgr = (ConfigurationManager) _configService; - NetworkOfferingVO voffer = configMgr.createNetworkOffering(offeringName, offeringDisplayText, - TrafficType.Public, null, true, Availability.Optional, null, serviceProviderMap, true, - Network.GuestType.Shared, false, null, false, null, true, false, null, true, null, false, false, false, false, false, null, null, null, true, null, null, false); - long id = voffer.getId(); - _networkOfferingDao.update(id, voffer); - return _networkOfferingDao.findById(id); - } - - private NetworkOffering locateNetworkOffering(String offeringName, - String offeringDisplayText, Provider provider) { - List offerList = _configService.listNetworkOfferings(TrafficType.Guest, false); - for (NetworkOffering offer : offerList) { - if (offer.getName().equals(offeringName)) { - if (offer.getState() != NetworkOffering.State.Enabled) { - return EnableNetworkOffering(offer.getId()); - } - return offer; - } - } - Map> serviceProviderMap = new HashMap>(); - Set providerSet = new HashSet(); - providerSet.add(provider); - final Service[] services = {Service.Connectivity, Service.Dhcp, Service.NetworkACL, Service.StaticNat, Service.SourceNat, Service.Lb}; - for (Service svc : services) { - if (svc == Service.Lb) { - if(offeringName.equals(vpcRouterOfferingName)) { - Set lbProviderSet = new HashSet(); - lbProviderSet.add(Provider.InternalLbVm); - serviceProviderMap.put(svc, lbProviderSet); - } - continue; - } - serviceProviderMap.put(svc, providerSet); - } - ConfigurationManager configMgr = (ConfigurationManager)_configService; - NetworkOfferingVO voffer = - configMgr.createNetworkOffering(offeringName, offeringDisplayText, TrafficType.Guest, null, false, Availability.Optional, null, serviceProviderMap, true, - Network.GuestType.Isolated, false, null, false, null, false, true, null, true, null, false, offeringName.equals(vpcRouterOfferingName), false, false, false, null, null, null, true, null, null, false); - if (offeringName.equals(vpcRouterOfferingName)) { - voffer.setInternalLb(true); - } - long id = voffer.getId(); - _networkOfferingDao.update(id, voffer); - return _networkOfferingDao.findById(id); - } - - private VpcOffering locateVpcOffering() { - VpcOffering vpcOffer = _vpcOffDao.findByUniqueName(juniperVPCOfferingName); - if (vpcOffer != null) { - if (((VpcOfferingVO)vpcOffer).getState() == VpcOffering.State.Enabled) { - return vpcOffer; - } - ((VpcOfferingVO)vpcOffer).setState(VpcOffering.State.Enabled); - long id = vpcOffer.getId(); - _vpcOffDao.update(id, (VpcOfferingVO)vpcOffer); - return vpcOffer; - } - Map> serviceProviderMap = new HashMap>(); - List providerSet = new ArrayList(); - providerSet.add(Provider.JuniperContrailVpcRouter.getName()); - final List services = new ArrayList(); - services.add(Service.Connectivity.getName()); - services.add(Service.Dhcp.getName()); - services.add(Service.NetworkACL.getName()); - services.add(Service.StaticNat.getName()); - services.add(Service.SourceNat.getName()); - services.add(Service.Gateway.getName()); - services.add(Service.Lb.getName()); - - for (String svc: services) { - if (svc.equals(Service.Lb.getName())) { - List lbProviderSet = new ArrayList(); - lbProviderSet.add(Provider.InternalLbVm.getName()); - serviceProviderMap.put(svc, lbProviderSet); - continue; - } - serviceProviderMap.put(svc, providerSet); - } - vpcOffer = _vpcProvSvc.createVpcOffering(juniperVPCOfferingName, juniperVPCOfferingDisplayText, services, serviceProviderMap, null, null, null, null, null, null, null, VpcOffering.State.Enabled, null, false, false); - long id = vpcOffer.getId(); - _vpcOffDao.update(id, (VpcOfferingVO)vpcOffer); - return _vpcOffDao.findById(id); - } - - private NetworkOffering EnableNetworkOffering(long id) { - NetworkOfferingVO offering = _networkOfferingDao.createForUpdate(id); - offering.setState(NetworkOffering.State.Enabled); - _networkOfferingDao.update(id, offering); - return _networkOfferingDao.findById(id); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - - File configFile = PropertiesUtil.findConfigFile(configuration); - FileInputStream fileStream = null; - try { - String hostname = null; - int port = 0; - if (configFile == null) { - return false; - } else { - final Properties configProps = new Properties(); - fileStream = new FileInputStream(configFile); - configProps.load(fileStream); - - String value = configProps.getProperty("management.db_sync_interval"); - if (value != null) { - _dbSyncInterval = Integer.parseInt(value); - } - hostname = configProps.getProperty("api.hostname"); - String portStr = configProps.getProperty("api.port"); - if (portStr != null && portStr.length() > 0) { - port = Integer.parseInt(portStr); - } - } - _api = ApiConnectorFactory.build(hostname, port); - } catch (IOException ex) { - logger.warn("Unable to read " + configuration, ex); - throw new ConfigurationException(); - } catch (Exception ex) { - logger.debug("Exception in configure: " + ex); - ex.printStackTrace(); - throw new ConfigurationException(); - } finally { - IOUtils.closeQuietly(fileStream); - } - - _controller = new ModelController(this, _api, _vmDao, _networksDao, _nicDao, _vlanDao, _ipAddressDao); - try { - _routerOffering = locateNetworkOffering(routerOfferingName, routerOfferingDisplayText, - Provider.JuniperContrailRouter); - _routerPublicOffering = locatePublicNetworkOffering(routerPublicOfferingName, routerPublicOfferingDisplayText, - Provider.JuniperContrailRouter); - _vpcRouterOffering = locateNetworkOffering(vpcRouterOfferingName, vpcRouterOfferingDisplayText, - Provider.JuniperContrailVpcRouter); - _vpcOffering = locateVpcOffering(); - }catch (Exception ex) { - logger.debug("Exception in locating network offerings: " + ex); - ex.printStackTrace(); - throw new ConfigurationException(); - } - - _eventHandler.subscribe(); - - initializeDefaultVirtualNetworkModels(); - - return true; - } - - @Override - public NetworkOffering getPublicRouterOffering() { - return _routerPublicOffering; - } - - @Override - public NetworkOffering getRouterOffering() { - return _routerOffering; - } - - @Override - public NetworkOffering getVpcRouterOffering() { - return _vpcRouterOffering; - } - - @Override - public VpcOffering getVpcOffering() { - return _vpcOffering; - } - - @Override - public String getPhysicalNetworkName(PhysicalNetworkVO physNet) { - String physname = physNet.getName(); - physname = physname.replaceAll("\\s", "").replace("_", ""); - return physname; - } - - @Override - public String getDomainCanonicalName(DomainVO domain) { - if (domain.getId() == Domain.ROOT_DOMAIN) { - return VNC_ROOT_DOMAIN; - } - return domain.getName(); - } - - @Override - public String getProjectCanonicalName(ProjectVO project) { - return project.getName(); - } - - @Override - public String getCanonicalName(Network net) { - String netname; - if (net.getTrafficType() == TrafficType.Guest) { - return net.getName(); - } else if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage) { - return managementNetworkName; - } else if (net.getTrafficType() == TrafficType.Control) { - return "__link_local__"; - } else { - DataCenter zone = _dcDao.findById(net.getDataCenterId()); - String zonename = zone.getName(); - zonename = zonename.replaceAll("\\s", ""); - zonename = zonename.replace("-", "_"); - netname = "__" + zonename + "_" + net.getTrafficType().toString() + "__"; - } - return netname; - } - - @Override - public String getDomainName(long domainId) { - if (domainId != Domain.ROOT_DOMAIN) { - DomainVO domain = _domainDao.findById(domainId); - return domain.getName(); - } - return VNC_ROOT_DOMAIN; - } - - @Override - public String getProjectName(long accountId) { - Account account = _accountDao.findById(accountId); - if (account.getType() == Account.Type.PROJECT) { - ProjectVO project = _projectDao.findByProjectAccountId(account.getId()); - if (project != null) { - return project.getName(); - } - } - return VNC_DEFAULT_PROJECT; - } - - @Override - public String getDefaultPublicNetworkFQN() { - String name = VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT + ":" + "__default_Public__"; - return name; - } - - private ProjectVO getProject(long accountId) { - Account account = _accountDao.findById(accountId); - if (account.getType() == Account.Type.PROJECT) { - return _projectDao.findByProjectAccountId(account.getId()); - } - return null; - } - - @Override - public String getProjectId(long domainId, long accountId) throws IOException { - ProjectVO project = getProject(accountId); - if (project != null) { - return project.getUuid(); - } - DomainVO domain = _domainDao.findById(domainId); - if (domain.getId() != Domain.ROOT_DOMAIN) { - net.juniper.contrail.api.types.Domain vncDomain = - (net.juniper.contrail.api.types.Domain)_api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid()); - return _api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, VNC_DEFAULT_PROJECT); - } - return null; - } - - @Override - public net.juniper.contrail.api.types.Project getVncProject(long domainId, long accountId) throws IOException { - String projectId = getProjectId(domainId, accountId); - if (projectId == null) { - return getDefaultVncProject(); - } - return (net.juniper.contrail.api.types.Project)_api.findById(net.juniper.contrail.api.types.Project.class, projectId); - } - - @Override - public net.juniper.contrail.api.types.Project getDefaultVncProject() throws IOException { - net.juniper.contrail.api.types.Project project = null; - project = (net.juniper.contrail.api.types.Project)_api.findByFQN(net.juniper.contrail.api.types.Project.class, VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT); - return project; - } - - @Override - public String getFQN(Network net) { - // domain, project, name - String fqname = getDomainName(net.getDomainId()); - fqname += ":" + getProjectName(net.getAccountId()) + ":"; - return fqname + getCanonicalName(net); - } - - @Override - public void findInfrastructureNetworks(PhysicalNetworkVO phys, List dbList) { - final TrafficType[] ttypes = {TrafficType.Control, // maps to __link_local__ - TrafficType.Management, // maps to ip-fabric - TrafficType.Public, TrafficType.Storage // maps to ip-fabric - }; - - for (int i = 0; i < ttypes.length; i++) { - List phys_nets; - phys_nets = _networksDao.listByZoneAndTrafficType(phys.getDataCenterId(), ttypes[i]); - dbList.addAll(phys_nets); - } - - } - - @Override - public void syncNetworkDB(short syncMode) throws IOException { - if (_dbSync.syncAll(syncMode) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) { - if (syncMode == DBSyncGeneric.SYNC_MODE_CHECK) { - logger.info("# Cloudstack DB & VNC are out of sync #"); - } else { - logger.info("# Cloudstack DB & VNC were out of sync, performed re-sync operation #"); - } - } else { - logger.info("# Cloudstack DB & VNC are in sync #"); - } - } - - public class DBSyncTask extends TimerTask { - private short _syncMode = DBSyncGeneric.SYNC_MODE_UPDATE; - - @Override - public void run() { - try { - logger.debug("DB Sync task is running"); - syncNetworkDB(_syncMode); - // Change to check mode - _syncMode = DBSyncGeneric.SYNC_MODE_CHECK; - } catch (Exception ex) { - logger.debug(ex); - logger.info("Unable to sync network db"); - } - } - } - - @Override - public boolean isManagedPhysicalNetwork(Network network) { - List net_list = _physicalNetworkDao.listByZone(network.getDataCenterId()); - for (PhysicalNetworkVO phys : net_list) { - if(_physProviderDao.findByServiceProvider(phys.getId(), Provider.JuniperContrailRouter.getName()) != null || - _physProviderDao.findByServiceProvider(phys.getId(), Provider.JuniperContrailVpcRouter.getName()) != null || - _physProviderDao.findByServiceProvider(phys.getId(), Provider.InternalLbVm.getName()) != null) { - return true; - } - } - return false; - } - - @Override - public String findVirtualNetworkId(Network net) throws IOException { - if (net.getTrafficType() == TrafficType.Guest) { - return net.getUuid(); - } - String netname = getDomainName(net.getDomainId()) + ":" + getProjectName(net.getAccountId()) + ":"; - - if (net.getTrafficType() == TrafficType.Control) { - netname += "__link_local__"; - } else if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage) { - netname += managementNetworkName; - } else { - netname = getFQN(net); - } - List fqn = ImmutableList.copyOf(StringUtils.split(netname, ':')); - return _api.findByName(VirtualNetwork.class, fqn); - } - - @Override - public List findSystemNetworks(List types) { - SearchBuilder searchBuilder = _networksDao.createSearchBuilder(); - searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN); - SearchCriteria sc = searchBuilder.create(); - if (types == null || types.isEmpty()) { - types = new ArrayList(); - types.add(TrafficType.Control); - types.add(TrafficType.Management); - types.add(TrafficType.Public); - types.add(TrafficType.Storage); - } - sc.setParameters("trafficType", types.toArray()); - List dbNets = _networksDao.search(sc, null); - if (dbNets == null) { - logger.debug("no system networks for the given traffic types: " + types.toString()); - dbNets = new ArrayList(); - } - - List phys_list = _physicalNetworkDao.listAll(); - final String provider = Provider.JuniperContrailRouter.getName(); - for (Iterator iter = phys_list.iterator(); iter.hasNext(); ) { - PhysicalNetworkVO phys = iter.next(); - if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null) { - List infraNets = new ArrayList(); - findInfrastructureNetworks(phys, infraNets); - for (NetworkVO net:infraNets) { - if (types == null || types.isEmpty()) { - if (!dbNets.contains(net)) { - dbNets.add(net); - } - continue; - } - for(TrafficType type:types) { - if (net.getTrafficType() == type) { - if (!dbNets.contains(net)) { - dbNets.add(net); - } - break; - } - } - } - } - } - return dbNets; - } - - @Override - public VirtualNetwork findDefaultVirtualNetwork(TrafficType trafficType) throws IOException { - if (trafficType == TrafficType.Guest || trafficType == TrafficType.Public) { - return null; - } - String netname = VNC_ROOT_DOMAIN + ":" + VNC_DEFAULT_PROJECT + ":"; - if (trafficType == TrafficType.Control) { - netname += "__link_local__"; - } else if (trafficType == TrafficType.Management || trafficType == TrafficType.Storage) { - netname += managementNetworkName; - } - return (VirtualNetwork)_api.findByFQN(VirtualNetwork.class, netname); - } - - /* - * Returns list of networks managed by Juniper VRouter filtered by traffic types - */ - @Override - public List findManagedNetworks(List types) { - - SearchBuilder searchBuilder = _networksDao.createSearchBuilder(); - searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.IN); - searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.IN); - - SearchCriteria sc = searchBuilder.create(); - List offerings = new ArrayList(); - offerings.add(getRouterOffering().getId()); - offerings.add(getVpcRouterOffering().getId()); - offerings.add(getPublicRouterOffering().getId()); - sc.setParameters("networkOfferingId", offerings.toArray()); - - if (types == null || types.isEmpty()) { - types = new ArrayList(); - types.add(TrafficType.Control); - types.add(TrafficType.Management); - types.add(TrafficType.Public); - types.add(TrafficType.Storage); - types.add(TrafficType.Guest); - } - sc.setParameters("trafficType", types.toArray()); - - List dbNets = _networksDao.search(sc, null); - if (dbNets == null) { - logger.debug("no juniper managed networks for the given traffic types: " + types.toString()); - dbNets = new ArrayList(); - } - - List phys_list = _physicalNetworkDao.listAll(); - final String provider = Network.Provider.JuniperContrailRouter.getName(); - final String vpcProvider = Provider.JuniperContrailVpcRouter.getName(); - for (Iterator iter = phys_list.iterator(); iter.hasNext();) { - PhysicalNetworkVO phys = iter.next(); - if (_physProviderDao.findByServiceProvider(phys.getId(), provider) != null || - _physProviderDao.findByServiceProvider(phys.getId(), vpcProvider) != null) { - List infraNets = new ArrayList(); - findInfrastructureNetworks(phys, infraNets); - for (NetworkVO net : infraNets) { - if (types == null || types.isEmpty()) { - if (!dbNets.contains(net)) { - dbNets.add(net); - } - continue; - } - for (TrafficType type : types) { - if (net.getTrafficType() == type) { - if (!dbNets.contains(net)) { - dbNets.add(net); - } - break; - } - } - } - } - } - return dbNets; - } - - @Override - public List findManagedVpcs() { - SearchBuilder searchBuilder = _vpcDao.createSearchBuilder(); - searchBuilder.and("vpcOffering", searchBuilder.entity().getVpcOfferingId(), Op.EQ); - SearchCriteria sc = searchBuilder.create(); - sc.setParameters("vpcOffering", getVpcOffering().getId()); - List vpcs = _vpcDao.search(sc, null); - if (vpcs == null || vpcs.size() == 0) { - logger.debug("no vpcs found"); - return null; - } - return vpcs; - } - - @Override - public List findManagedACLs() { - List vpcs = findManagedVpcs(); - if (vpcs == null || vpcs.isEmpty()) { - return null; - } - List vpcIds = new ArrayList(); - /* default-allow, default-deny ACLs will be under vpcId '0', so include it*/ - vpcIds.add((long)0); - for (VpcVO vpc:vpcs) { - vpcIds.add(vpc.getId()); - } - SearchBuilder searchBuilder = _networkAclDao.createSearchBuilder(); - searchBuilder.and("vpcId", searchBuilder.entity().getVpcId(), Op.IN); - SearchCriteria sc = searchBuilder.create(); - sc.setParameters("vpcId", vpcIds.toArray()); - List acls = _networkAclDao.search(sc, null); - if (acls == null || acls.size() == 0) { - logger.debug("no acls found"); - return null; - } - /* only return if acl is associated to any network */ - List jnprAcls = new ArrayList(); - for (NetworkACLVO acl:acls) { - List nets = _networksDao.listByAclId(acl.getId()); - if (nets == null || nets.isEmpty()) { - continue; - } - jnprAcls.add(acl); - } - return jnprAcls; - } - - /* - * Returns list of public ip addresses managed by Juniper VRouter - */ - @Override - public List findManagedPublicIps() { - - List dbNets = findManagedNetworks(null); - - if (dbNets == null || dbNets.isEmpty()) { - logger.debug("Juniper managed networks is empty"); - return null; - } - - SearchBuilder searchBuilder = _ipAddressDao.createSearchBuilder(); - searchBuilder.and("sourceNat", searchBuilder.entity().isSourceNat(), Op.EQ); - searchBuilder.and("network", searchBuilder.entity().getAssociatedWithNetworkId(), Op.IN); - searchBuilder.and("oneToOneNat", searchBuilder.entity().isOneToOneNat(), Op.EQ); - searchBuilder.and("associatedWithVmId", searchBuilder.entity().getAssociatedWithVmId(), Op.NNULL); - - List netIds = new ArrayList(); - for (NetworkVO net : dbNets) { - netIds.add(net.getId()); - } - - SearchCriteria sc = searchBuilder.create(); - sc.setParameters("oneToOneNat", true); - sc.setParameters("sourceNat", false); - sc.setParameters("network", netIds.toArray()); - - List publicIps = _ipAddressDao.search(sc, null); - if (publicIps == null) { - logger.debug("no public ips"); - return null; - } - - return publicIps; - } - - private void initializeDefaultVirtualNetworkModels() { - List types = new ArrayList(); - types.add(TrafficType.Management); - types.add(TrafficType.Storage); - types.add(TrafficType.Control); - - List dbNets = findManagedNetworks(types); - for (NetworkVO net : dbNets) { - - VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(null, getCanonicalName(net), net.getTrafficType()); - if (vnModel == null) { - vnModel = new VirtualNetworkModel(net, null, getCanonicalName(net), net.getTrafficType()); - vnModel.build(getModelController(), net); - try { - if (!vnModel.verify(getModelController())) { - vnModel.update(getModelController()); - } - } catch (Exception ex) { - logger.warn("virtual-network update: ", ex); - } - getDatabase().getVirtualNetworks().add(vnModel); - } - } - } - - @Override - public boolean isSystemDefaultNetwork(VirtualNetwork vnet) { - List fqn = vnet.getQualifiedName(); - if (fqn.size() < 3) { - return false; - } - List default_parent = vnet.getDefaultParent(); - int index = 0; - for (Iterator iter = default_parent.iterator(); iter.hasNext(); index++) { - String piece = iter.next(); - if (!piece.equals(fqn.get(index))) { - return false; - } - } - List default_networks = ImmutableList.of("__link_local__", "default-virtual-network", managementNetworkName); - for (Iterator iter = default_networks.iterator(); iter.hasNext();) { - String name = iter.next(); - if (name.equals(fqn.get(index))) { - return true; - } - } - return false; - } - - @Override - public boolean isSystemDefaultNetwork(NetworkVO net) { - if (net.getTrafficType() == TrafficType.Management || net.getTrafficType() == TrafficType.Storage || net.getTrafficType() == TrafficType.Control) { - return true; - } - return false; - } - - @Override - public boolean isSystemRootDomain(net.juniper.contrail.api.types.Domain domain) { - if (domain.getName().compareTo(VNC_ROOT_DOMAIN) == 0) { - return true; - } - return false; - } - - @Override - public boolean isSystemRootDomain(DomainVO domain) { - if (domain.getId() == Domain.ROOT_DOMAIN || domain.getName().compareTo("ROOT") == 0 || domain.getParent() == null) { - return true; - } - return false; - } - - @Override - public boolean isSystemDefaultProject(net.juniper.contrail.api.types.Project project) { - if (project.getName().compareTo(VNC_DEFAULT_PROJECT) == 0) { - return true; - } - return false; - } - - @Override - public boolean isSystemDefaultProject(ProjectVO project) { - return false; - } - - @Override - public String getVifNameByVmName(String vmName, Integer deviceId) { - String vif_name = vmName + "-" + deviceId.toString(); - return vif_name; - } - - @Override - public String getVifNameByVmUuid(String vmUuid, Integer deviceId) { - VMInstanceVO vm = _vmInstanceDao.findByUuid(vmUuid); - if (vm != null) { - return vm.getInstanceName() + "-" + deviceId.toString(); - } - return null; - } - - @Override - public ModelController getModelController() { - return _controller; - } - - @Override - public ApiConnector getApiConnector() { - return _api; - } - - @Override - public VirtualNetworkModel lookupPublicNetworkModel() { - List types = new ArrayList(); - types.add(TrafficType.Public); - List dbNets = findManagedNetworks(types); - if (dbNets == null) { - return null; - } - NetworkVO net = dbNets.get(0); - - VirtualNetworkModel vnModel = getDatabase().lookupVirtualNetwork(net.getUuid(), getCanonicalName(net), TrafficType.Public); - if (vnModel == null) { - vnModel = new VirtualNetworkModel(net, net.getUuid(), - getCanonicalName(net), net.getTrafficType()); - vnModel.setProperties(getModelController(), net); - } - try { - if (!vnModel.verify(getModelController())) { - vnModel.update(getModelController()); - } - getDatabase().getVirtualNetworks().add(vnModel); - } catch (Exception ex) { - logger.warn("virtual-network update: ", ex); - } - return vnModel; - } - - @Override - public boolean createFloatingIp(PublicIpAddress ip) { - VirtualNetworkModel vnModel = lookupPublicNetworkModel(); - assert vnModel != null : "public network vn model is null"; - FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel(); - - /* create only, no updates */ - if (fipPoolModel == null) { - fipPoolModel = new FloatingIpPoolModel(); - fipPoolModel.addToVirtualNetwork(vnModel); - fipPoolModel.build(getModelController()); - try { - fipPoolModel.update(getModelController()); - vnModel.setFipPoolModel(fipPoolModel); - } catch (Exception ex) { - logger.warn("floating-ip-pool create: ", ex); - return false; - } - } - - FloatingIpModel fipModel = fipPoolModel.getFloatingIpModel(ip.getUuid()); - /* create only, no updates*/ - if (fipModel == null) { - fipModel = new FloatingIpModel(ip.getUuid()); - fipModel.addToFloatingIpPool(fipPoolModel); - fipModel.build(getModelController(), ip); - try { - fipModel.update(getModelController()); - } catch (Exception ex) { - logger.warn("floating-ip create: ", ex); - return false; - } - } - return true; - } - - @Override - public boolean deleteFloatingIp(PublicIpAddress ip) { - VirtualNetworkModel vnModel = lookupPublicNetworkModel(); - assert vnModel != null : "public network model is null"; - FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel(); - FloatingIpModel fipModel = fipPoolModel.getFloatingIpModel(ip.getUuid()); - if (fipModel != null) { - try { - fipModel.destroy(getModelController()); - } catch (IOException ex) { - logger.warn("floating ip delete", ex); - return false; - } - fipPoolModel.removeSuccessor(fipModel); - if (!fipPoolModel.hasDescendents()) { - try { - fipPoolModel.delete(getModelController()); - vnModel.setFipPoolModel(null); - } catch (IOException e) { - return false; - } - } - } - return true; - } - - @SuppressWarnings("unchecked") - @Override - public List getFloatingIps() { - String fipPoolName = getDefaultPublicNetworkFQN() + ":PublicIpPool"; - FloatingIpPool fipPool = null; - try { - fipPool = (FloatingIpPool)_api.findByFQN(FloatingIpPool.class, fipPoolName); - } catch (Exception ex) { - logger.debug(ex); - } - if (fipPool == null) { - return null; - } - List> ips = fipPool.getFloatingIps(); - if (ips != null) { - try { - return (List)_api.getObjects(FloatingIp.class, ips); - } catch (IOException ex) { - logger.debug(ex); - return null; - } - } - return null; - } - - @Override - public boolean isSystemDefaultNetworkPolicy(NetworkPolicy policy) { - if (policy.getName().equals("default-network-policy")) { - return true; - } - return false; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailVpcElementImpl.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailVpcElementImpl.java deleted file mode 100644 index d5060443c9e8..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ContrailVpcElementImpl.java +++ /dev/null @@ -1,204 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; -import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel; - -import org.springframework.stereotype.Component; - -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.IpAddress; -import com.cloud.network.Network; -import com.cloud.network.Network.Provider; -import com.cloud.network.element.NetworkACLServiceProvider; -import com.cloud.network.element.VpcProvider; -import com.cloud.network.vpc.NetworkACLItem; -import com.cloud.network.vpc.NetworkACLVO; -import com.cloud.network.vpc.PrivateGateway; -import com.cloud.network.vpc.StaticRouteProfile; -import com.cloud.network.vpc.Vpc; -import com.cloud.network.vpc.dao.NetworkACLDao; -import com.cloud.vm.ReservationContext; - -@Component -public class ContrailVpcElementImpl extends ContrailElementImpl implements NetworkACLServiceProvider, VpcProvider { - - @Inject - NetworkACLDao _networkACLDao; - - // NetworkElement API - @Override - public Provider getProvider() { - return Provider.JuniperContrailVpcRouter; - } - - @Override - public boolean implementVpc(Vpc vpc, DeployDestination dest, - ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - // TODO Auto-generated method stub - logger.debug("NetworkElement implementVpc"); - return true; - } - - @Override - public boolean shutdownVpc(Vpc vpc, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - logger.debug("NetworkElement shutdownVpc"); - return true; - } - - @Override - public boolean createPrivateGateway(PrivateGateway gateway) - throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - logger.debug("NetworkElement createPrivateGateway"); - return false; - } - - @Override - public boolean deletePrivateGateway(PrivateGateway privateGateway) - throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - logger.debug("NetworkElement deletePrivateGateway"); - return false; - } - - @Override - public boolean applyStaticRoutes(Vpc vpc, List routes) - throws ResourceUnavailableException { - // TODO Auto-generated method stub - logger.debug("NetworkElement applyStaticRoutes"); - return true; - } - - @Override - public boolean applyNetworkACLs(Network net, - List rules) - throws ResourceUnavailableException { - logger.debug("NetworkElement applyNetworkACLs"); - if (rules == null || rules.isEmpty()) { - logger.debug("no rules to apply"); - return true; - } - - Long aclId = rules.get(0).getAclId(); - NetworkACLVO acl = _networkACLDao.findById(aclId); - NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid()); - if (policyModel == null) { - /* - * For the first time, when a CS ACL applied to a network, create a network-policy in VNC - * and when there are no networks associated to CS ACL, delete it from VNC. - */ - policyModel = new NetworkPolicyModel(acl.getUuid(), acl.getName()); - net.juniper.contrail.api.types.Project project; - try { - project = _manager.getVncProject(net.getDomainId(), net.getAccountId()); - if (project == null) { - project = _manager.getDefaultVncProject(); - } - } catch (IOException ex) { - logger.warn("read project", ex); - return false; - } - policyModel.setProject(project); - } - - VirtualNetworkModel vnModel = _manager.getDatabase().lookupVirtualNetwork(net.getUuid(), - _manager.getCanonicalName(net), net.getTrafficType()); - NetworkPolicyModel oldPolicyModel = null; - /* this method is called when network is destroyed too, hence vn model might have been deleted already */ - if (vnModel != null) { - oldPolicyModel = vnModel.getNetworkPolicyModel(); - vnModel.addToNetworkPolicy(policyModel); - } - - try { - policyModel.build(_manager.getModelController(), rules); - } catch (Exception e) { - logger.error(e); - e.printStackTrace(); - return false; - } - - try { - if (!policyModel.verify(_manager.getModelController())) { - policyModel.update(_manager.getModelController()); - } - _manager.getDatabase().getNetworkPolicys().add(policyModel); - } catch (Exception ex) { - logger.error("network-policy update: ", ex); - ex.printStackTrace(); - return false; - } - - if (!policyModel.hasPolicyRules()) { - try { - policyModel.delete(_manager.getModelController()); - _manager.getDatabase().getNetworkPolicys().remove(policyModel); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - /* - * if no other VNs are associated with the old policy, - * we could delete it from the Contrail VNC - */ - if (policyModel != oldPolicyModel && oldPolicyModel != null && !oldPolicyModel.hasDescendents()) { - try { - oldPolicyModel.delete(_manager.getModelController()); - _manager.getDatabase().getNetworkPolicys().remove(oldPolicyModel); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - return true; - } - - @Override - public boolean reorderAclRules(Vpc vpc, List networks, List networkACLItems) { - return true; - } - - @Override - public boolean applyACLItemsToPrivateGw(PrivateGateway privateGateway, - List rules) - throws ResourceUnavailableException { - // TODO Auto-generated method stub - logger.debug("NetworkElement applyACLItemsToPrivateGw"); - return true; - } - - @Override - public boolean updateVpcSourceNatIp(Vpc vpc, IpAddress address) { - return true; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java deleted file mode 100644 index 7cb47224ed72..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/DBSyncGeneric.java +++ /dev/null @@ -1,333 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; - -import net.juniper.contrail.api.ApiObjectBase; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.apache.cloudstack.api.Identity; - -public class DBSyncGeneric { - - protected Logger logger = LogManager.getLogger(getClass()); - - /* for each synchronization VNC class, following methods - * needs to be defined. - * For e.q : VirtualNetwork class should have createMethodPrefix+"VirtualNetwork" etc - */ - private final String createMethodPrefix = "create"; - private final String deleteMethodPrefix = "delete"; - private final String compareMethodPrefix = "compare"; - private final String filterMethodPrefix = "filter"; - private final String equalMethodPrefix = "equal"; - private final String syncMethodPrefix = "sync"; - /* default db, vnc comparators are implemented based on uuid values, - * if user defined comparators are required, then only add these methods - */ - private final String dbComparatorMethodPrefix = "dbComparator"; - private final String vncComparatorMethodPrefix = "vncComparator"; - - /* sync methods implementation object, if implemented in separate class - * set the scope object - */ - private Object _scope; - private HashMap _methodMap; - private short _syncMode; - - public static final short SYNC_MODE_UPDATE = 0; - public static final short SYNC_MODE_CHECK = 1; - - public DBSyncGeneric(Object scope) { - this._scope = scope; - this._syncMode = SYNC_MODE_UPDATE; - setMethodMap(); - } - - public DBSyncGeneric() { - this._scope = this; - this._syncMode = SYNC_MODE_UPDATE; - setMethodMap(); - } - - public void setSyncMode(short mode) { - this._syncMode = mode; - } - - public short getSyncMode() { - return this._syncMode; - } - - public void setScope(Object scope) { - this._scope = scope; - setMethodMap(); - } - - public void setMethodMap() { - _methodMap = new HashMap(); - Method methods[] = _scope.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { - _methodMap.put(methods[i].getName(), methods[i]); - } - } - - public static String getClassName(Class cls) { - String clsname = cls.getName(); - int loc = clsname.lastIndexOf('.'); - if (loc > 0) { - clsname = clsname.substring(loc + 1); - } - return clsname; - } - - /* - * This API can be used to sync a particular vnc class - */ - public Boolean sync(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String syncMethod = syncMethodPrefix + getClassName(cls); - Method method = _methodMap.get(syncMethod); - if (method == null) - throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + syncMethod); - return (Boolean)method.invoke(_scope, parameters); - } - - private void create(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String createMethod = createMethodPrefix + getClassName(cls); - Method method = _methodMap.get(createMethod); - if (method == null) - throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + createMethod); - method.invoke(_scope, parameters); - } - - private void delete(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String deleteMethod = deleteMethodPrefix + getClassName(cls); - Method method = _methodMap.get(deleteMethod); - if (method == null) - throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + deleteMethod); - method.invoke(_scope, parameters); - } - - private Integer compare(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String compareMethod = compareMethodPrefix + getClassName(cls); - Method method = _methodMap.get(compareMethod); - if (method == null) - throw new NoSuchMethodException(getClassName(_scope.getClass()) + ":" + compareMethod); - return (Integer)method.invoke(_scope, parameters); - } - - private Boolean filter(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String filterMethod = filterMethodPrefix + getClassName(cls); - Method method = _methodMap.get(filterMethod); - if (method == null) { - logger.debug("Method not implemented: " + getClassName(_scope.getClass()) + ":" + filterMethod); - return false; - } - return (Boolean)method.invoke(_scope, parameters); - } - - private Boolean equal(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String equalMethod = equalMethodPrefix + getClassName(cls); - Method method = _methodMap.get(equalMethod); - if (method == null) { - logger.debug("Method not implemented: " + getClassName(_scope.getClass()) + ":" + equalMethod); - return true; - } - return (Boolean)method.invoke(_scope, parameters); - } - - @SuppressWarnings("rawtypes") - private Comparator dbComparator(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String dbComparatorMethod = dbComparatorMethodPrefix + getClassName(cls); - Method method = _methodMap.get(dbComparatorMethod); - if (method == null) - return dbComparatorDefault(); - return (Comparator)method.invoke(_scope, parameters); - } - - @SuppressWarnings("rawtypes") - private Comparator vncComparator(Class cls, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { - String vncComparatorMethod = vncComparatorMethodPrefix + getClassName(cls); - Method method = _methodMap.get(vncComparatorMethod); - if (method == null) - return vncComparatorDefault(); - return (Comparator)method.invoke(_scope, parameters); - } - - @SuppressWarnings("rawtypes") - public Comparator dbComparatorDefault() { - Comparator comparator = new Comparator() { - @Override - public int compare(Identity u1, Identity u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - @SuppressWarnings("rawtypes") - public Comparator vncComparatorDefault() { - Comparator comparator = new Comparator() { - @Override - public int compare(ApiObjectBase u1, ApiObjectBase u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public static class SyncStats { - public int create; - public int delete; - public int equal; - public int diff; - public int filter; - public StringBuffer logMsg; - - SyncStats() { - logMsg = new StringBuffer(); - } - - void log(String str) { - logMsg.append(str); - logMsg.append('\n'); - } - - public boolean isSynchronized() { - return create == 0 && delete == 0 && diff == 0; - } - - @Override - public String toString() { - StringBuffer str = new StringBuffer(); - str.append("create: " + create); - str.append(", delete: " + delete); - if (filter > 0) { - str.append(", filter: " + filter); - } - str.append(", equal: " + equal); - str.append(", diff:" + diff); - return str.toString(); - } - } - - public void syncCollections(Class cls, Collection lhsList, Collection rhsList, boolean modifyMode, SyncStats stats) throws InvocationTargetException, - IllegalAccessException, NoSuchMethodException { - java.util.Iterator lhsIter = lhsList.iterator(); - java.util.Iterator rhsIter = rhsList.iterator(); - - Object lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; - Object rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; - - while (lhsItem != null && rhsItem != null) { - Integer cmp = this.compare(cls, lhsItem, rhsItem, stats.logMsg); - if (cmp < 0) { - // Create - if (modifyMode) { - this.create(cls, lhsItem, stats.logMsg); - } - stats.create++; - lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; - } else if (cmp > 0) { - // Delete - if (!this.filter(cls, rhsItem, stats.logMsg)) { - if (modifyMode) { - this.delete(cls, rhsItem, stats.logMsg); - } - stats.delete++; - } else { - stats.filter++; - } - rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; - } else { - // Equal - if (this.equal(cls, lhsItem, rhsItem, stats.logMsg)) { - stats.equal++; - } else { - stats.diff++; - } - lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; - rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; - } - } - - while (lhsItem != null) { - // Create - if (modifyMode) { - this.create(cls, lhsItem, stats.logMsg); - } - stats.create++; - lhsItem = lhsIter.hasNext() ? lhsIter.next() : null; - } - - while (rhsItem != null) { - // Delete - if (!this.filter(cls, rhsItem, stats.logMsg)) { - if (modifyMode) { - this.delete(cls, rhsItem, stats.logMsg); - } - stats.delete++; - } else { - stats.filter++; - } - rhsItem = rhsIter.hasNext() ? rhsIter.next() : null; - } - } - - @SuppressWarnings("unchecked") - public boolean syncGeneric(Class cls, List dbList, List vncList) throws Exception { - SyncStats stats = new SyncStats(); - stats.log("Sync log for <" + getClassName(cls) + ">"); - - logger.debug("Generic db sync : " + getClassName(cls)); - - java.util.Collections.sort(dbList, this.dbComparator(cls)); - java.util.Collections.sort(vncList, this.vncComparator(cls)); - - syncCollections(cls, dbList, vncList, _syncMode != SYNC_MODE_CHECK, stats); - - if (_syncMode != SYNC_MODE_CHECK) { - logger.debug("Sync stats<" + getClassName(cls) + ">: " + stats.toString()); - logger.debug(stats.logMsg); - logger.debug("Generic db sync : " + getClassName(cls) + " done"); - } else { - logger.debug("Sync state checking stats<" + getClassName(cls) + ">: " + stats.toString()); - if (!stats.isSynchronized()) { - logger.debug("DB and VNC objects out of sync is detected : " + getClassName(cls)); - logger.debug("Log message: \n" + stats.logMsg); - } else { - logger.debug("DB and VNC objects are in sync : " + getClassName(cls)); - } - } - - /* return value of this method indicates state of the db & vnc before sync - * false: out of sync, true: in sync; - * it does not indicate whether sync operation is performed or not; - * Actual sync is done only if _syncMode is UPDATE - */ - return stats.isSynchronized(); - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/EventUtils.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/EventUtils.java deleted file mode 100644 index 338caca1fbe8..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/EventUtils.java +++ /dev/null @@ -1,180 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.framework.events.EventDistributor; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.stereotype.Component; - -import com.cloud.event.ActionEvent; -import com.cloud.event.ActionEvents; -import com.cloud.event.Event; -import com.cloud.event.EventCategory; -import com.cloud.event.EventTypes; -import com.cloud.server.ManagementService; -import com.cloud.utils.component.ComponentContext; -import com.cloud.utils.component.ComponentMethodInterceptor; - - -@Component -public class EventUtils { - protected static Logger LOGGER = LogManager.getLogger(EventUtils.class); - - private static EventDistributor eventDistributor; - - private static final String MODULE_TOP_LEVEL_PACKAGE = - EventUtils.class.getPackage().getName().substring(0, - EventUtils.class.getPackage().getName().lastIndexOf('.')); - - public EventUtils() { - } - - public static void setEventDistributor(EventDistributor eventDistributorImpl) { - eventDistributor = eventDistributorImpl; - } - - private static void publishOnMessageBus(String eventCategory, String eventType, String details, Event.State state) { - - if (state != com.cloud.event.Event.State.Completed) { - return; - } - - try { - setEventDistributor(ComponentContext.getComponent(EventDistributor.class)); - } catch (NoSuchBeanDefinitionException nbe) { - return; // no provider is configured to provide events bus, so just return - } - - org.apache.cloudstack.framework.events.Event event = - new org.apache.cloudstack.framework.events.Event(ManagementService.Name, eventCategory, eventType, EventTypes.getEntityForEvent(eventType), null); - - Map eventDescription = new HashMap<>(); - eventDescription.put("event", eventType); - eventDescription.put("status", state.toString()); - eventDescription.put("details", details); - event.setDescription(eventDescription); - eventDistributor.publish(event); - } - - public static class EventInterceptor implements ComponentMethodInterceptor, MethodInterceptor { - - protected Logger LOGGER = LogManager.getLogger(getClass()); - - public EventInterceptor() { - - } - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - Method m = invocation.getMethod(); - Object target = invocation.getThis(); - - if ( getActionEvents(m).size() == 0 ) { - /* Look for annotation on impl class */ - m = target.getClass().getMethod(m.getName(), m.getParameterTypes()); - } - - Object interceptorData = null; - - boolean success = true; - try { - interceptorData = interceptStart(m, target); - - Object result = invocation.proceed(); - success = true; - - return result; - } finally { - if ( success ) { - interceptComplete(m, target, interceptorData); - } else { - interceptException(m, target, interceptorData); - } - } - } - - protected List getActionEvents(Method m) { - List result = new ArrayList<>(); - - ActionEvents events = m.getAnnotation(ActionEvents.class); - - if ( events != null ) { - for ( ActionEvent e : events.value() ) { - result.add(e); - } - } - - ActionEvent e = m.getAnnotation(ActionEvent.class); - - if ( e != null ) { - result.add(e); - } - - return result; - } - - @Override - public Object interceptStart(Method method, Object target) { - return null; - } - - @Override - public void interceptComplete(Method method, Object target, Object event) { - ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); - boolean sameModule = false; - if (target != null && target.getClass().getPackage() != null) { - sameModule = target.getClass().getPackage().getName().startsWith(MODULE_TOP_LEVEL_PACKAGE); - } - if (!sameModule) { - return; - } - if (actionEvent != null) { - CallContext ctx = CallContext.current(); - if (!actionEvent.create()) { - publishOnMessageBus(EventCategory.ACTION_EVENT.getName(), actionEvent.eventType(), ctx.getEventDetails(), com.cloud.event.Event.State.Completed); - } - } - } - - @Override - public void interceptException(Method method, Object target, Object event) { - LOGGER.debug("interceptException"); - } - - @Override - public boolean needToIntercept(Method method) { - ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); - if (actionEvent != null) { - return true; - } - - return false; - } - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java deleted file mode 100644 index 29d0b3a51e8e..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ManagementNetworkGuru.java +++ /dev/null @@ -1,128 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import static com.cloud.utils.AutoCloseableUtil.closeAutoCloseable; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; -import java.util.Properties; - -import javax.naming.ConfigurationException; - -import org.springframework.stereotype.Component; - -import com.cloud.deploy.DeploymentPlan; -import com.cloud.network.Network; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.Mode; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkVO; -import com.cloud.offering.NetworkOffering; -import com.cloud.user.Account; -import com.cloud.utils.PropertiesUtil; -/** - * ManagementNetworkGuru - * - * Replace the default management network strategy (PodBasedNetworkGuru) by using a Isolated network for management - * traffic. - */ -@Component -public class ManagementNetworkGuru extends ContrailGuru { - private static final TrafficType[] TrafficTypes = {TrafficType.Management}; - - private final String configuration = "contrail.properties"; - private String _mgmtCidr; - private String _mgmtGateway; - - @Override - public String getName() { - return "ManagementNetworkGuru"; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - File configFile = PropertiesUtil.findConfigFile(configuration); - FileInputStream inputFile = null; - - try { - if (null == configFile) { - throw new FileNotFoundException("Configuration file was not found!"); - } - inputFile = new FileInputStream(configFile); - } catch (FileNotFoundException e) { - logger.error(e.getMessage()); - throw new ConfigurationException(e.getMessage()); - } - - final Properties configProps = new Properties(); - try { - configProps.load(inputFile); - } catch (IOException e) { - logger.error(e.getMessage()); - throw new ConfigurationException(e.getMessage()); - } finally { - closeAutoCloseable(inputFile, "error closing config file"); - } - _mgmtCidr = configProps.getProperty("management.cidr"); - _mgmtGateway = configProps.getProperty("management.gateway"); - logger.info("Management network " + _mgmtCidr + " gateway: " + _mgmtGateway); - return true; - } - - @Override - public TrafficType[] getSupportedTrafficType() { - return TrafficTypes; - } - - @Override - public boolean isMyTrafficType(TrafficType type) { - for (TrafficType t : TrafficTypes) { - if (t == type) { - return true; - } - } - return false; - } - - private boolean canHandle(NetworkOffering offering) { - TrafficType type = offering.getTrafficType(); - return (isMyTrafficType(type)); - } - - @Override - public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, String name, Long vpcId, Account owner) { - - if (!canHandle(offering)) { - return null; - } - NetworkVO network = - new NetworkVO(offering.getTrafficType(), Mode.Dhcp, BroadcastDomainType.Lswitch, offering.getId(), Network.State.Allocated, plan.getDataCenterId(), - plan.getPhysicalNetworkId(), offering.isRedundantRouter()); - if (_mgmtCidr != null) { - network.setCidr(_mgmtCidr); - network.setGateway(_mgmtGateway); - } - logger.debug("Allocated network " + userSpecified + (network.getCidr() == null ? "" : " subnet: " + network.getCidr())); - return network; - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ModelDatabase.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ModelDatabase.java deleted file mode 100644 index 66fad7097b8a..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ModelDatabase.java +++ /dev/null @@ -1,104 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.util.TreeSet; - -import org.apache.cloudstack.network.contrail.model.ModelObjectBase; -import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel; -import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; -import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; - -import com.cloud.network.Networks.TrafficType; - -public class ModelDatabase { - TreeSet _serviceInstanceTable; - TreeSet _vmTable; - TreeSet _vnTable; - TreeSet _policyTable; - - public ModelDatabase() { - initDb(); - } - - public void initDb() { - _serviceInstanceTable = new TreeSet(new ModelObjectBase.UuidComparator()); - _vmTable = new TreeSet(new ModelObjectBase.UuidComparator()); - _vnTable = new TreeSet(new ModelObjectBase.UuidComparator()); - _policyTable = new TreeSet(new ModelObjectBase.UuidComparator()); - } - - public TreeSet getServiceInstances() { - return _serviceInstanceTable; - } - - public ServiceInstanceModel lookupServiceInstance(String fqn) { - ServiceInstanceModel siKey = new ServiceInstanceModel(fqn); - ServiceInstanceModel current = _serviceInstanceTable.ceiling(siKey); - if (current != null && current.getQualifiedName().equals(fqn)) { - return current; - } - return null; - } - - public TreeSet getVirtualMachines() { - return _vmTable; - } - - public VirtualMachineModel lookupVirtualMachine(String uuid) { - VirtualMachineModel vmKey = new VirtualMachineModel(null, uuid); - VirtualMachineModel current = _vmTable.ceiling(vmKey); - if (current != null && current.getUuid().equals(uuid)) { - return current; - } - return null; - } - - public TreeSet getVirtualNetworks() { - return _vnTable; - } - - public VirtualNetworkModel lookupVirtualNetwork(String uuid, String name, TrafficType ttype) { - VirtualNetworkModel vnKey = new VirtualNetworkModel(null, uuid, name, ttype); - VirtualNetworkModel current = _vnTable.ceiling(vnKey); - if (current != null) { - if (ttype == TrafficType.Management || ttype == TrafficType.Storage || ttype == TrafficType.Control) { - if (current.getName().equals(name)) { - return current; - } - } else if (current.getUuid().equals(uuid)) { - return current; - } - } - return null; - } - - public TreeSet getNetworkPolicys() { - return _policyTable; - } - - public NetworkPolicyModel lookupNetworkPolicy(String uuid) { - NetworkPolicyModel vmKey = new NetworkPolicyModel(uuid, null); - NetworkPolicyModel current = _policyTable.ceiling(vmKey); - if (current != null && current.getUuid().equals(uuid)) { - return current; - } - return null; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSync.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSync.java deleted file mode 100644 index 4333ac5b374e..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSync.java +++ /dev/null @@ -1,42 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; - -import com.cloud.domain.DomainVO; -import com.cloud.projects.ProjectVO; - -public interface ServerDBSync { - - public final static short SYNC_STATE_IN_SYNC = 0; - public final static short SYNC_STATE_OUT_OF_SYNC = 1; - public final static short SYNC_STATE_UNKNOWN = -1; - - /* - * API for syncing all classes of vnc objects with cloudstack - * Sync cloudstack and vnc objects. - */ - public short syncAll(short syncMode); - - public void syncClass(Class cls); - - public void createProject(ProjectVO project, StringBuffer syncLogMesg) throws IOException; - - public void createDomain(DomainVO domain, StringBuffer logMesg) throws IOException; -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java deleted file mode 100644 index 2955a790b8a8..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerDBSyncImpl.java +++ /dev/null @@ -1,1178 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.locks.ReentrantLock; - -import javax.inject.Inject; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiObjectBase; -import net.juniper.contrail.api.ApiPropertyBase; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.FloatingIp; -import net.juniper.contrail.api.types.FloatingIpPool; -import net.juniper.contrail.api.types.NetworkPolicy; -import net.juniper.contrail.api.types.InstanceIp; -import net.juniper.contrail.api.types.ServiceInstance; -import net.juniper.contrail.api.types.VirtualMachine; -import net.juniper.contrail.api.types.VirtualMachineInterface; -import net.juniper.contrail.api.types.VirtualNetwork; - -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.network.contrail.model.FloatingIpModel; -import org.apache.cloudstack.network.contrail.model.FloatingIpPoolModel; -import org.apache.cloudstack.network.contrail.model.NetworkPolicyModel; -import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; -import org.apache.cloudstack.network.contrail.model.VMInterfaceModel; -import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; - -import com.cloud.dc.dao.VlanDao; -import com.cloud.domain.DomainVO; -import com.cloud.domain.dao.DomainDao; -import com.cloud.exception.InternalErrorException; -import com.cloud.network.IpAddress; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.vpc.NetworkACLItemDao; -import com.cloud.network.vpc.NetworkACLItemVO; -import com.cloud.network.vpc.NetworkACLVO; -import com.cloud.network.vpc.dao.NetworkACLDao; -import com.cloud.network.vpc.VpcVO; -import com.cloud.network.vpc.dao.VpcDao; -import com.cloud.projects.ProjectVO; -import com.cloud.projects.dao.ProjectDao; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.VMInstanceDao; - -@Component -public class ServerDBSyncImpl implements ServerDBSync { - - @Inject - DomainDao _domainDao; - @Inject - ProjectDao _projectDao; - @Inject - NetworkDao _networksDao; - @Inject - VMInstanceDao _vmInstanceDao; - @Inject - NicDao _nicDao; - @Inject - VlanDao _vlanDao; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physProviderDao; - @Inject - ContrailManager _manager; - @Inject - VpcDao _vpcDao; - @Inject - NetworkACLItemDao _networkACLItemDao; - @Inject - NetworkACLDao _networkACLDao; - - DBSyncGeneric _dbSync; - Class[] _vncClasses; - // Read-Write (true) or Read-Only mode. - boolean _rwMode; - private final ReentrantLock _lockSyncMode = new ReentrantLock(); - - ServerDBSyncImpl() { - _vncClasses = - new Class[] {net.juniper.contrail.api.types.Domain.class, net.juniper.contrail.api.types.Project.class, NetworkPolicy.class, VirtualNetwork.class, - VirtualMachine.class, ServiceInstance.class, FloatingIp.class}; - _dbSync = new DBSyncGeneric(this); - } - - protected Logger logger = LogManager.getLogger(getClass()); - - /* - * API for syncing all classes of vnc objects with cloudstack - * - * Sync cloudstack and vnc objects. - * Order has to be maintained - */ - @Override - public short syncAll(short syncMode) { - short syncState = SYNC_STATE_IN_SYNC; - - /* vnc classes need to be synchronized with cloudstack */ - logger.debug("syncing cloudstack db with vnc"); - try { - for (Class cls : _vncClasses) { - - /* lock the sync mode*/ - _lockSyncMode.lock(); - _rwMode = syncMode == DBSyncGeneric.SYNC_MODE_UPDATE; - _dbSync.setSyncMode(syncMode); - - if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { - logger.debug("sync check start: " + DBSyncGeneric.getClassName(cls)); - } else { - logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); - } - - if (_dbSync.sync(cls) == false) { - if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { - logger.info("out of sync detected: " + DBSyncGeneric.getClassName(cls)); - } else { - logger.info("out of sync detected and re-synced: " + DBSyncGeneric.getClassName(cls)); - } - syncState = SYNC_STATE_OUT_OF_SYNC; - } - if (_dbSync.getSyncMode() == DBSyncGeneric.SYNC_MODE_CHECK) { - logger.debug("sync check finish: " + DBSyncGeneric.getClassName(cls)); - } else { - logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); - } - /* unlock the sync mode */ - _lockSyncMode.unlock(); - } - } catch (Exception ex) { - logger.warn("DB Synchronization", ex); - syncState = SYNC_STATE_UNKNOWN; - if (_lockSyncMode.isLocked()) { - _lockSyncMode.unlock(); - } - } - - return syncState; - } - - @Override - public void syncClass(Class cls) { - - logger.debug("syncClass: " + cls.getName()); - try { - logger.debug("sync start: " + DBSyncGeneric.getClassName(cls)); - _lockSyncMode.lock(); - _dbSync.setSyncMode(DBSyncGeneric.SYNC_MODE_UPDATE); - _dbSync.sync(cls); - _lockSyncMode.unlock(); - logger.debug("sync finish: " + DBSyncGeneric.getClassName(cls)); - } catch (Exception ex) { - logger.warn("Sync error: " + cls.getName(), ex); - if (_lockSyncMode.isLocked()) { - _lockSyncMode.unlock(); - } - } - } - - public void deleteChildren(List> childs, Class childCls, StringBuffer syncLogMesg) throws Exception { - final ApiConnector api = _manager.getApiConnector(); - if (childs == null) { - syncLogMesg.append("no children of type: " + childCls.getName() + "\n"); - return; - } - - syncLogMesg.append("delete children of type : " + DBSyncGeneric.getClassName(childCls) + "\n"); - String deleteChildMethod = "delete" + DBSyncGeneric.getClassName(childCls); - Method method = null; - Method methods[] = this.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equalsIgnoreCase(deleteChildMethod)) { - method = methods[i]; - break; - } - } - int count = 0; - for (ObjectReference childRef : childs) { - @SuppressWarnings("unchecked") - ApiObjectBase child = api.findById((Class)childCls, childRef.getUuid()); - if (method != null) { - method.invoke(this, child, syncLogMesg); - } else { - deleteDefault(child, childCls, syncLogMesg); - } - count++; - } - syncLogMesg.append("deleted children count : " + count + "\n"); - } - - public void deleteDefault(ApiObjectBase vnc, Class cls, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - api.delete(vnc); - syncLogMesg.append(cls.getCanonicalName() + "# VNC: " + vnc.getName() + " deleted\n"); - } - - /* - * Domain Synchronization methods - */ - public boolean syncDomain() throws Exception { - final ApiConnector api = _manager.getApiConnector(); - try { - List dbList = _domainDao.listAll(); - @SuppressWarnings("unchecked") - List vncList = api.list(net.juniper.contrail.api.types.Domain.class, null); - return _dbSync.syncGeneric(net.juniper.contrail.api.types.Domain.class, dbList, vncList); - } catch (Exception ex) { - logger.warn("syncDomain", ex); - throw ex; - } - } - - @Override - public void createDomain(DomainVO db, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - net.juniper.contrail.api.types.Domain vnc = new net.juniper.contrail.api.types.Domain(); - vnc.setName(db.getName()); - vnc.setUuid(db.getUuid()); - if (!api.create(vnc)) { - logger.error("Unable to create domain " + vnc.getName()); - syncLogMesg.append("Error: Virtual domain# VNC : Unable to create domain: " + vnc.getName() + "\n"); - return; - } - syncLogMesg.append("Domain# VNC: " + vnc.getName() + " created \n"); - } - - public void deleteDomain(net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - api.read(vnc); - syncLogMesg.append("Domain# DB: none; VNC: " + vnc.getName() + "(" + vnc.getUuid() + "); action: delete\n"); - - /* delete all projects under this domain */ - try { - deleteChildren(vnc.getProjects(), net.juniper.contrail.api.types.Project.class, syncLogMesg); - } catch (Exception ex) { - logger.warn("deleteDomain", ex); - } - - api.delete(vnc); - syncLogMesg.append("Domain# VNC: " + vnc.getName() + " deleted\n"); - } - - public Integer compareDomain(DomainVO db, net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) { - if (_manager.isSystemRootDomain(db) && _manager.isSystemRootDomain(vnc)) { - return _manager.getDomainCanonicalName(db).compareTo(vnc.getName()); - } else if (_manager.isSystemRootDomain(db)) { - return -1; - } else if (_manager.isSystemRootDomain(vnc)) { - return 1; - } - return db.getUuid().compareTo(vnc.getUuid()); - } - - public Boolean filterDomain(net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) { - if (_manager.isSystemRootDomain(vnc)) { - return true; - } - return false; - } - - public Boolean equalDomain(DomainVO db, net.juniper.contrail.api.types.Domain vnc, StringBuffer syncLogMesg) { - syncLogMesg.append("Domain# DB: " + db.getName() + "; VNC: " + vnc.getName() + "; action: equal, no action\n"); - return true; - } - - public Comparator dbComparatorDomain() { - Comparator comparator = new Comparator() { - @Override - public int compare(DomainVO u1, DomainVO u2) { - if (_manager.isSystemRootDomain(u1)) { - return -1; - } - if (_manager.isSystemRootDomain(u2)) { - return 1; - } - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Comparator vncComparatorDomain() { - Comparator comparator = new Comparator() { - @Override - public int compare(net.juniper.contrail.api.types.Domain u1, net.juniper.contrail.api.types.Domain u2) { - if (_manager.isSystemRootDomain(u1)) { - return -1; - } - if (_manager.isSystemRootDomain(u2)) { - return 1; - } - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - /* - * Project Synchronization methods - */ - @SuppressWarnings("unchecked") - public boolean syncProject() throws Exception { - final ApiConnector api = _manager.getApiConnector(); - try { - List dbList = _projectDao.listAll(); - List vncList = api.list(net.juniper.contrail.api.types.Project.class, null); - return _dbSync.syncGeneric(net.juniper.contrail.api.types.Project.class, dbList, vncList); - } catch (Exception ex) { - logger.warn("syncProject", ex); - throw ex; - } - } - - @Override - public void createProject(ProjectVO db, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - net.juniper.contrail.api.types.Project vnc = new net.juniper.contrail.api.types.Project(); - vnc.setName(db.getName()); - vnc.setUuid(db.getUuid()); - if (!api.create(vnc)) { - logger.error("Unable to create project: " + vnc.getName()); - syncLogMesg.append("Error: Virtual project# VNC : Unable to create project: " + vnc.getName() + "\n"); - return; - } - syncLogMesg.append("Project# VNC: " + vnc.getName() + " created \n"); - } - - public void deleteProject(net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - api.read(vnc); - syncLogMesg.append("Project# DB: none; VNC: " + vnc.getName() + "(" + vnc.getUuid() + "); action: delete\n"); - - try { - deleteChildren(vnc.getVirtualNetworks(), VirtualNetwork.class, syncLogMesg); - deleteChildren(vnc.getSecurityGroups(), net.juniper.contrail.api.types.SecurityGroup.class, syncLogMesg); - deleteChildren(vnc.getNetworkIpams(), net.juniper.contrail.api.types.NetworkIpam.class, syncLogMesg); - deleteChildren(vnc.getNetworkPolicys(), net.juniper.contrail.api.types.NetworkPolicy.class, syncLogMesg); - } catch (Exception ex) { - logger.warn("deleteProject", ex); - } - - api.delete(vnc); - syncLogMesg.append("Project# VNC: " + vnc.getName() + " deleted\n"); - } - - public Integer compareProject(ProjectVO db, net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) { - if (_manager.isSystemDefaultProject(db) && _manager.isSystemDefaultProject(vnc)) { - return _manager.getProjectCanonicalName(db).compareTo(vnc.getName()); - } else if (_manager.isSystemDefaultProject(db)) { - return -1; - } else if (_manager.isSystemDefaultProject(vnc)) { - return 1; - } - return db.getUuid().compareTo(vnc.getUuid()); - } - - public Boolean filterProject(net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) { - if (_manager.isSystemDefaultProject(vnc)) { - syncLogMesg.append("VNC: " + vnc.getName() + " filtered; action: don't delete\n"); - return true; - } - return false; - } - - public Boolean equalProject(ProjectVO db, net.juniper.contrail.api.types.Project vnc, StringBuffer syncLogMesg) { - syncLogMesg.append("Project# DB: " + db.getName() + "; VNC: " + vnc.getName() + "; action: equal, no action\n"); - return true; - } - - public Comparator dbComparatorProject() { - Comparator comparator = new Comparator() { - @Override - public int compare(ProjectVO u1, ProjectVO u2) { - if (_manager.isSystemDefaultProject(u1)) { - return -1; - } - if (_manager.isSystemDefaultProject(u2)) { - return 1; - } - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Comparator vncComparatorProject() { - Comparator comparator = new Comparator() { - @Override - public int compare(net.juniper.contrail.api.types.Project u1, net.juniper.contrail.api.types.Project u2) { - if (_manager.isSystemDefaultProject(u1)) { - return -1; - } - if (_manager.isSystemDefaultProject(u2)) { - return 1; - } - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - /* - * Security Groups - */ - - public void deleteSecurityGroup(net.juniper.contrail.api.types.SecurityGroup vnc, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - api.delete(vnc); - syncLogMesg.append("SecurityGroup# VNC: " + vnc.getName() + " deleted\n"); - } - - /* - * Virtual Network Synchronization methods - */ - @SuppressWarnings({"unchecked"}) - public boolean syncVirtualNetwork() throws Exception { - final ApiConnector api = _manager.getApiConnector(); - try { - - List types = new ArrayList(); - types.add(TrafficType.Public); - types.add(TrafficType.Guest); - List dbNets = _manager.findManagedNetworks(types); - - List vList = (List)api.list(VirtualNetwork.class, null); - List vncList = new ArrayList(); - for (VirtualNetwork vn : vList) { - if (!_manager.isSystemDefaultNetwork(vn)) { - vncList.add(vn); - } - } - logger.debug("sync VN - DB size: " + dbNets.size() + " VNC Size: " + vncList.size()); - return _dbSync.syncGeneric(VirtualNetwork.class, dbNets, vncList); - } catch (Exception ex) { - logger.warn("sync virtual-networks", ex); - throw ex; - } - } - - public Comparator dbComparatorVirtualNetwork() { - Comparator comparator = new Comparator() { - @Override - public int compare(NetworkVO u1, NetworkVO u2) { - if (_manager.isSystemDefaultNetwork(u1) && _manager.isSystemDefaultNetwork(u2)) { - return _manager.getCanonicalName(u1).compareTo(_manager.getCanonicalName(u2)); - } else if (_manager.isSystemDefaultNetwork(u1)) { - return -1; - } else if (_manager.isSystemDefaultNetwork(u2)) { - return 1; - } - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Comparator vncComparatorVirtualNetwork() { - Comparator comparator = new Comparator() { - @Override - public int compare(VirtualNetwork u1, VirtualNetwork u2) { - if (_manager.isSystemDefaultNetwork(u1) && _manager.isSystemDefaultNetwork(u2)) { - return u1.getName().compareTo(u2.getName()); - } else if (_manager.isSystemDefaultNetwork(u1)) { - return -1; - } else if (_manager.isSystemDefaultNetwork(u2)) { - return 1; - } - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public void createVirtualNetwork(NetworkVO dbNet, StringBuffer syncLogMesg) throws IOException { - syncLogMesg.append("VN# DB: " + _manager.getCanonicalName(dbNet) + "(" + dbNet.getUuid() + "); VNC: none; action: create\n"); - - if (_manager.getDatabase().lookupVirtualNetwork(dbNet.getUuid(), _manager.getCanonicalName(dbNet), dbNet.getTrafficType()) != null) { - logger.warn("VN model object is already present in DB: " + dbNet.getUuid() + ", name: " + dbNet.getName()); - } - - VirtualNetworkModel vnModel = new VirtualNetworkModel(dbNet, dbNet.getUuid(), _manager.getCanonicalName(dbNet), dbNet.getTrafficType()); - if (dbNet.getTrafficType() == TrafficType.Guest && dbNet.getNetworkACLId() != null) { - NetworkACLVO acl = _networkACLDao.findById(dbNet.getNetworkACLId()); - NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid()); - if (policyModel == null) { - logger.error("Network(" + dbNet.getName() + ") has ACL but policy model not created: " + - acl.getUuid() + ", name: " + acl.getName()); - } else { - vnModel.addToNetworkPolicy(policyModel); - } - } - vnModel.build(_manager.getModelController(), dbNet); - - if (_rwMode) { - try { - if (!vnModel.verify(_manager.getModelController())) { - vnModel.update(_manager.getModelController()); - } - } catch (InternalErrorException ex) { - logger.warn("create virtual-network", ex); - syncLogMesg.append("Error: VN# VNC : Unable to create network " + dbNet.getName() + "\n"); - return; - } - logger.debug("add model " + vnModel.getName()); - _manager.getDatabase().getVirtualNetworks().add(vnModel); - syncLogMesg.append("VN# VNC: " + dbNet.getUuid() + ", " + vnModel.getName() + " created\n"); - } else { - syncLogMesg.append("VN# VNC: " + vnModel.getName() + " created \n"); - } - } - - public void deleteVirtualNetwork(VirtualNetwork vnet, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - if (_manager.isSystemDefaultNetwork(vnet)) { - syncLogMesg.append("VN# System default virtual Network# VNC: " + vnet.getName() + " can not be deleted\n"); - return; - } - api.read(vnet); - - deleteInstanceIps(vnet.getInstanceIpBackRefs(), syncLogMesg); - - List> fipPools = vnet.getFloatingIpPools(); - if (fipPools != null && !fipPools.isEmpty()) { - FloatingIpPool floatingIpPool = (FloatingIpPool)api.findById(FloatingIpPool.class, fipPools.get(0).getUuid()); - if (floatingIpPool != null) { - deleteFloatingIps(floatingIpPool.getFloatingIps(), syncLogMesg); - } - } - - deleteVirtualMachineInterfaces(vnet.getVirtualMachineInterfaceBackRefs(), syncLogMesg); - - syncLogMesg.append("VN# DB: none; VNC: " + vnet.getName() + "(" + vnet.getUuid() + "); action: delete\n"); - api.delete(vnet); - syncLogMesg.append("VN# VNC: " + vnet.getName() + " deleted\n"); - } - - public Integer compareVirtualNetwork(NetworkVO dbn, VirtualNetwork vnet, StringBuffer syncLogMesg) { - if (_manager.isSystemDefaultNetwork(dbn) && _manager.isSystemDefaultNetwork(vnet)) { - return _manager.getCanonicalName(dbn).compareTo(vnet.getName()); - } else if (_manager.isSystemDefaultNetwork(dbn)) { - return -1; - } else if (_manager.isSystemDefaultNetwork(vnet)) { - return 1; - } - return dbn.getUuid().compareTo(vnet.getUuid()); - } - - public Boolean filterVirtualNetwork(VirtualNetwork vnet, StringBuffer syncLogMesg) { - if (_manager.isSystemDefaultNetwork(vnet)) { - syncLogMesg.append("VN# VNC: " + vnet.getName() + " filtered; action: don't delete\n"); - return true; - } - return false; - } - - public Boolean equalVirtualNetwork(NetworkVO dbn, VirtualNetwork vnet, StringBuffer syncLogMesg) { - syncLogMesg.append("VN# DB: " + _manager.getCanonicalName(dbn) + "; VNC: " + vnet.getName() + "; action: equal\n"); - - VirtualNetworkModel current = _manager.getDatabase().lookupVirtualNetwork(vnet.getUuid(), _manager.getCanonicalName(dbn), dbn.getTrafficType()); - - VirtualNetworkModel vnModel = new VirtualNetworkModel(dbn, vnet.getUuid(), _manager.getCanonicalName(dbn), dbn.getTrafficType()); - if (dbn.getTrafficType() == TrafficType.Guest && dbn.getNetworkACLId() != null) { - NetworkACLVO acl = _networkACLDao.findById(dbn.getNetworkACLId()); - NetworkPolicyModel policyModel = _manager.getDatabase().lookupNetworkPolicy(acl.getUuid()); - if (policyModel == null) { - logger.error("Network(" + dbn.getName() + ") has ACL but policy model not created: " + - acl.getUuid() + ", name: " + acl.getName()); - } else { - vnModel.addToNetworkPolicy(policyModel); - } - } - vnModel.build(_manager.getModelController(), dbn); - - if (_rwMode) { - if (current != null) { - FloatingIpPoolModel fipPoolModel = current.getFipPoolModel(); - if (fipPoolModel != null) { - vnModel.setFipPoolModel(fipPoolModel); - fipPoolModel.addToVirtualNetwork(vnModel); - } - _manager.getDatabase().getVirtualNetworks().remove(current); - } - logger.debug("add model " + vnModel.getName()); - _manager.getDatabase().getVirtualNetworks().add(vnModel); - try { - if (!vnModel.verify(_manager.getModelController())) { - vnModel.update(_manager.getModelController()); - } - } catch (Exception ex) { - logger.warn("update virtual-network", ex); - } - if (current != null) { - NetworkPolicyModel oldPolicyModel = current.getNetworkPolicyModel(); - if (oldPolicyModel != vnModel.getNetworkPolicyModel()) { - /* - * if no other VNs are associated with the old policy, - * we could delete it from the Contrail VNC - */ - if (oldPolicyModel != null && !oldPolicyModel.hasDescendents()) { - try { - oldPolicyModel.delete(_manager.getModelController()); - _manager.getDatabase().getNetworkPolicys().remove(oldPolicyModel); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - } else { - //compare - if (current != null && current.compare(_manager.getModelController(), vnModel) == false) { - syncLogMesg.append("VN# DB: " + _manager.getCanonicalName(dbn) + "; VNC: " + vnet.getName() + "; attributes differ\n"); - return false; - } - } - return true; - } - - /* - * Virtual Machine Synchronization methods - */ - - public boolean syncVirtualMachine() { - final ApiConnector api = _manager.getApiConnector(); - try { - List vmDbList = _vmInstanceDao.listAll(); - @SuppressWarnings("unchecked") - List vncVmList = (List)api.list(VirtualMachine.class, null); - logger.debug("sync VM: CS size: " + vmDbList.size() + " VNC size: " + vncVmList.size()); - return _dbSync.syncGeneric(VirtualMachine.class, vmDbList, vncVmList); - } catch (Exception ex) { - logger.warn("sync virtual-machines", ex); - } - return false; - } - - public Comparator dbComparatorVirtualMachine() { - Comparator comparator = new Comparator() { - @Override - public int compare(VMInstanceVO u1, VMInstanceVO u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Comparator vncComparatorVirtualMachine() { - Comparator comparator = new Comparator() { - @Override - public int compare(VirtualMachine u1, VirtualMachine u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public void createVirtualMachine(VMInstanceVO dbVm, StringBuffer syncLogMesg) throws IOException { - syncLogMesg.append("VM# DB: " + dbVm.getInstanceName() + "/" + dbVm.getUuid() + "; VNC: none; action: create\n"); - VirtualMachineModel vmModel = new VirtualMachineModel(dbVm, dbVm.getUuid()); - vmModel.build(_manager.getModelController(), dbVm); - buildNicResources(vmModel, dbVm, syncLogMesg); - - if (_rwMode) { - try { - vmModel.update(_manager.getModelController()); - } catch (InternalErrorException ex) { - logger.warn("create virtual-machine", ex); - return; - } - _manager.getDatabase().getVirtualMachines().add(vmModel); - syncLogMesg.append("VM# VNC: " + dbVm.getUuid() + " created\n"); - } - } - - private void deleteVirtualMachineInterfaces(List> list, StringBuffer syncLogMesg) throws IOException { - if (list == null) { - return; - } - final ApiConnector api = _manager.getApiConnector(); - for (ObjectReference vmiRef : list) { - VirtualMachineInterface vmi = (VirtualMachineInterface)api.findById(VirtualMachineInterface.class, vmiRef.getUuid()); - deleteInstanceIps(vmi.getInstanceIpBackRefs(), syncLogMesg); - deleteFloatingIps(vmi.getFloatingIpBackRefs(), syncLogMesg); - api.delete(VirtualMachineInterface.class, vmiRef.getUuid()); - syncLogMesg.append("VNC vmi: " + vmi.getUuid() + " deleted\n"); - } - } - - private void deleteInstanceIps(List> list, StringBuffer syncLogMesg) throws IOException { - if (list == null) { - return; - } - final ApiConnector api = _manager.getApiConnector(); - for (ObjectReference instIp : list) { - api.delete(InstanceIp.class, instIp.getUuid()); - syncLogMesg.append("VNC instance IP: " + instIp.getUuid() + " deleted\n"); - } - - } - - private void deleteFloatingIps(List> list, StringBuffer syncLogMesg) throws IOException { - if (list == null) { - return; - } - final ApiConnector api = _manager.getApiConnector(); - for (ObjectReference floatingIp : list) { - api.delete(FloatingIp.class, floatingIp.getUuid()); - syncLogMesg.append("VNC instance IP: " + floatingIp.getUuid() + " deleted\n"); - } - } - - public void deleteVirtualMachine(VirtualMachine vncVm, StringBuffer syncLogMesg) { - final ApiConnector api = _manager.getApiConnector(); - syncLogMesg.append("VM# DB:none; VNC: " + vncVm.getName() + "/" + vncVm.getUuid() + "; action: delete\n"); - if (!_rwMode) { - return; - } - try { - if (!api.read(vncVm)) { - return; - } - deleteVirtualMachineInterfaces(vncVm.getVirtualMachineInterfaces(), syncLogMesg); - api.delete(VirtualMachine.class, vncVm.getUuid()); - } catch (IOException ex) { - logger.warn("delete virtual-machine", ex); - return; - } - syncLogMesg.append("VM# VNC: " + vncVm.getName() + " deleted\n"); - } - - public Integer compareVirtualMachine(VMInstanceVO dbVm, VirtualMachine vncVm, StringBuffer syncLogMesg) { - String dbVmId = dbVm.getUuid(); - String vncVmId = vncVm.getUuid(); - return dbVmId.compareTo(vncVmId); - } - - public boolean filterVirtualMachine(VirtualMachine vncVm, StringBuffer syncLogMesg) { - return false; - } - - private void buildNicResources(VirtualMachineModel vmModel, VMInstanceVO dbVm, StringBuffer syncLogMsg) throws IOException { - List nics = _nicDao.listByVmId(dbVm.getId()); - for (NicVO nic : nics) { - VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); - if (vmiModel == null) { - vmiModel = new VMInterfaceModel(nic.getUuid()); - NetworkVO network = _networksDao.findById(nic.getNetworkId()); - VirtualNetworkModel vnModel = - _manager.getDatabase().lookupVirtualNetwork(network.getUuid(), _manager.getCanonicalName(network), network.getTrafficType()); - if (vnModel == null) { - logger.warn("Unable to locate virtual-network for network id " + network.getId()); - continue; - } - vmiModel.addToVirtualMachine(vmModel); - vmiModel.addToVirtualNetwork(vnModel); - } - vmiModel.build(_manager.getModelController(), dbVm, nic); - } - } - - public Boolean equalVirtualMachine(VMInstanceVO dbVm, VirtualMachine vncVm, StringBuffer syncLogMsg) { - - syncLogMsg.append("VM# DB: " + dbVm.getInstanceName() + "/" + dbVm.getUuid() + "; VNC: " + vncVm.getUuid() + "; action: equal; DB VM State: " + dbVm.getState() + - "\n"); - - VirtualMachineModel vmModel = new VirtualMachineModel(dbVm, dbVm.getUuid()); - vmModel.build(_manager.getModelController(), dbVm); - - if (vmModel.isActive()) { - try { - buildNicResources(vmModel, dbVm, syncLogMsg); - } catch (IOException ex) { - logger.warn("build nic information for " + dbVm.getInstanceName(), ex); - } - } - - VirtualMachineModel current = _manager.getDatabase().lookupVirtualMachine(vncVm.getUuid()); - if (_rwMode) { - if (current != null) { - _manager.getDatabase().getVirtualMachines().remove(current); - } - _manager.getDatabase().getVirtualMachines().add(vmModel); - try { - vmModel.update(_manager.getModelController()); - } catch (Exception ex) { - logger.warn("update virtual-machine", ex); - } - } else { - //compare - if (current != null && current.compare(_manager.getModelController(), vmModel) == false) { - syncLogMsg.append("VM # DB: " + dbVm.getInstanceName() + "; VNC: " + vncVm.getName() + "; attributes differ\n"); - return false; - } - } - return true; - } - - public boolean syncFloatingIp() throws Exception { - - List ipList = _manager.findManagedPublicIps(); - List vncList = _manager.getFloatingIps(); - if (ipList == null) { - ipList = new ArrayList(); - } - if (vncList == null) { - vncList = new ArrayList(); - } - - boolean status = false; - try { - status = _dbSync.syncGeneric(FloatingIp.class, ipList, vncList); - } catch (Exception ex) { - logger.warn("sync floating-ips", ex); - throw ex; - } - return status; - } - - public Comparator dbComparatorFloatingIp() { - Comparator comparator = new Comparator() { - @Override - public int compare(IpAddress u1, IpAddress u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Comparator vncComparatorFloatingIp() { - Comparator comparator = new Comparator() { - @Override - public int compare(FloatingIp u1, FloatingIp u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Integer compareFloatingIp(IpAddress db, FloatingIp vnc, StringBuffer syncLogMesg) { - String dbId = db.getUuid(); - String vncId = vnc.getUuid(); - return dbId.compareTo(vncId); - } - - public void createFloatingIp(IPAddressVO dbIp, StringBuffer syncLogMesg) throws Exception { - - if (dbIp.getState() == IpAddress.State.Releasing) { - /* Don't need to push releasing ip */ - syncLogMesg.append("fip# DB: " + dbIp.getUuid() + ", state releasing, don't create in vnc\n"); - return; - } - syncLogMesg.append("fip# DB: " + dbIp.getAddress().addr() + "; VNC: none; action: create\n"); - if (!_manager.createFloatingIp(PublicIp.createFromAddrAndVlan(dbIp, _vlanDao.findById(dbIp.getVlanId())))) { - syncLogMesg.append("fip# VNC: " + dbIp.getAddress().addr() + " unable to create\n"); - return; - } - syncLogMesg.append("fip# VNC: " + dbIp.getUuid() + " created\n"); - } - - public void deleteFloatingIp(FloatingIp vnc, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - syncLogMesg.append("fip# DB: none; VNC: " + vnc.getAddress() + "(" + vnc.getUuid() + "); action: delete\n"); - api.delete(vnc); - syncLogMesg.append("fip# VNC: " + vnc.getUuid() + " deleted\n"); - } - - public Boolean equalFloatingIp(IPAddressVO db, FloatingIp vnc, StringBuffer syncLogMsg) throws IOException { - - syncLogMsg.append("fip# DB: " + db.getAddress().addr() + "; VNC: " + vnc.getAddress() + "; action: equal" + "\n"); - - VirtualNetworkModel vnModel = _manager.lookupPublicNetworkModel(); - assert vnModel != null : "public network vn model is null"; - - FloatingIpPoolModel fipPoolModel = vnModel.getFipPoolModel(); - if (fipPoolModel == null) { - fipPoolModel = new FloatingIpPoolModel(); - fipPoolModel.addToVirtualNetwork(vnModel); - fipPoolModel.build(_manager.getModelController()); - try { - fipPoolModel.update(_manager.getModelController()); - vnModel.setFipPoolModel(fipPoolModel); - } catch (Exception ex) { - logger.warn("floating-ip-pool create: ", ex); - return false; - } - } - - FloatingIpModel current = fipPoolModel.getFloatingIpModel(db.getUuid()); - if (current == null) { - logger.debug("add model " + db.getAddress().addr()); - FloatingIpModel fipModel = new FloatingIpModel(db.getUuid()); - fipModel.addToFloatingIpPool(fipPoolModel); - fipModel.build(_manager.getModelController(), PublicIp.createFromAddrAndVlan(db, _vlanDao.findById(db.getVlanId()))); - try { - fipModel.update(_manager.getModelController()); - } catch (Exception ex) { - logger.warn("floating-ip create: ", ex); - return false; - } - } - return true; - } - - /* - * Network Policy Synchronization methods - */ - @SuppressWarnings({ "unchecked" }) - public boolean syncNetworkPolicy() throws Exception { - final ApiConnector api = _manager.getApiConnector(); - try { - - List dbAcls = _manager.findManagedACLs(); - if (dbAcls == null) { - dbAcls = new ArrayList(); - } - - List pList = (List) api.list(NetworkPolicy.class, null); - List vncList = new ArrayList(); - - for (NetworkPolicy policy:pList) { - if (!_manager.isSystemDefaultNetworkPolicy(policy)) { - vncList.add(policy); - } - } - logger.debug("sync Network Policy - DB size: " + dbAcls.size() + " VNC Size: " + vncList.size()); - return _dbSync.syncGeneric(NetworkPolicy.class, dbAcls, vncList); - } catch (Exception ex) { - logger.warn("sync network-policys", ex); - throw ex; - } - } - - public Comparator dbComparatorNetworkPolicy() { - Comparator comparator = new Comparator() { - public int compare(NetworkACLVO u1, NetworkACLVO u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public Comparator vncComparatorNetworkPolicy() { - Comparator comparator = new Comparator() { - public int compare(NetworkPolicy u1, NetworkPolicy u2) { - return u1.getUuid().compareTo(u2.getUuid()); - } - }; - return comparator; - } - - public void createNetworkPolicy(NetworkACLVO db, StringBuffer syncLogMesg) throws IOException { - syncLogMesg.append("Policy# DB: " + db.getName() + - "(" + db.getUuid() + "); VNC: none; action: create\n"); - - if (_manager.getDatabase().lookupNetworkPolicy(db.getUuid()) != null) { - logger.warn("Policy model object is already present in DB: " + - db.getUuid() + ", name: " + db.getName()); - } - NetworkPolicyModel policyModel = new NetworkPolicyModel(db.getUuid(), db.getName()); - net.juniper.contrail.api.types.Project project = null; - try { - VpcVO vpc = _vpcDao.findById(db.getVpcId()); - if (vpc != null) { - project = _manager.getVncProject(vpc.getDomainId(), vpc.getAccountId()); - } else { - project = _manager.getDefaultVncProject(); - } - } catch (IOException ex) { - logger.warn("read project", ex); - throw ex; - } - policyModel.setProject(project); - List rules = _networkACLItemDao.listByACL(db.getId()); - try { - policyModel.build(_manager.getModelController(), rules); - } catch (Exception e) { - e.printStackTrace(); - } - - if (_rwMode) { - try { - if (!policyModel.verify(_manager.getModelController())) { - policyModel.update(_manager.getModelController()); - } - } catch (Exception ex) { - logger.warn("create network-policy", ex); - syncLogMesg.append("Error: Policy# VNC : Unable to create network policy " + - db.getName() + "\n"); - return; - } - logger.debug("add model " + policyModel.getName()); - _manager.getDatabase().getNetworkPolicys().add(policyModel); - syncLogMesg.append("Policy# VNC: " + db.getUuid() + ", " + policyModel.getName() + " created\n"); - } else { - syncLogMesg.append("Policy# VNC: " + policyModel.getName() + " created \n"); - } - } - - public void deleteNetworkPolicy(NetworkPolicy policy, StringBuffer syncLogMesg) throws IOException { - final ApiConnector api = _manager.getApiConnector(); - if (_manager.isSystemDefaultNetworkPolicy(policy)) { - syncLogMesg.append("Policy# System default Network Policy# VNC: " + policy.getName() + " can not be deleted\n"); - return; - } - syncLogMesg.append("Policy# DB: none; VNC: " + policy.getName() + "(" + policy.getUuid() + "); action: delete\n"); - api.delete(policy); - syncLogMesg.append("Policy# VNC: " + policy.getName() + " deleted\n"); - } - - public Integer compareNetworkPolicy(NetworkACLVO dbn, NetworkPolicy policy, StringBuffer syncLogMesg) { - if (_manager.isSystemDefaultNetworkPolicy(policy)) { - return 1; - } - return dbn.getUuid().compareTo(policy.getUuid()); - } - - public Boolean filterNetworkPolicy(NetworkPolicy policy, StringBuffer syncLogMesg) { - if (_manager.isSystemDefaultNetworkPolicy(policy)) { - syncLogMesg.append("Policy# VNC: " + policy.getName() + " filtered; action: don't delete\n"); - return true; - } - return false; - } - - public Boolean equalNetworkPolicy(NetworkACLVO db, NetworkPolicy policy, StringBuffer syncLogMesg) { - syncLogMesg.append("Policy# DB: " + db.getName() + - "; VNC: " + policy.getName() + "; action: equal\n"); - NetworkPolicyModel current = _manager.getDatabase().lookupNetworkPolicy(policy.getUuid()); - NetworkPolicyModel policyModel = new NetworkPolicyModel(db.getUuid(), db.getName()); - net.juniper.contrail.api.types.Project project = null; - try { - VpcVO vpc = _vpcDao.findById(db.getVpcId()); - if (vpc != null) { - project = _manager.getVncProject(vpc.getDomainId(), vpc.getAccountId()); - } else { - project = _manager.getDefaultVncProject(); - } - } catch (IOException ex) { - logger.warn("read project", ex); - } - policyModel.setProject(project); - List rules = _networkACLItemDao.listByACL(db.getId()); - try { - policyModel.build(_manager.getModelController(), rules); - } catch (Exception e) { - e.printStackTrace(); - } - if (_rwMode) { - if (current != null) { - _manager.getDatabase().getNetworkPolicys().remove(current); - } - logger.debug("add policy model " + policyModel.getName()); - _manager.getDatabase().getNetworkPolicys().add(policyModel); - try { - if (!policyModel.verify(_manager.getModelController())) { - policyModel.update(_manager.getModelController()); - } - } catch (Exception ex) { - logger.warn("update network-policy", ex); - } - } else { - //compare - if (current != null && current.compare(_manager.getModelController(), policyModel) == false) { - syncLogMesg.append("Policy# DB: " + db.getName() + - "; VNC: " + policy.getName() + "; attributes differ\n"); - return false; - } - } - return true; - } - - public Integer compareServiceInstance(ServiceInstanceModel siModel, ServiceInstance siObj, StringBuffer logMsg) { - String fqn = StringUtils.join(siObj.getQualifiedName(), ':'); - return siModel.getQualifiedName().compareTo(fqn); - } - - /** - * createServiceInstance - * - * This method should never be invoked since the model objects have been installed already when sync is called. - * @param siModel - * @param logMsg - */ - public void createServiceInstance(ServiceInstanceModel siModel, StringBuffer logMsg) { - assert false; - } - - public void deleteServiceInstance(ServiceInstance siObj, StringBuffer logMsg) { - final ApiConnector api = _manager.getApiConnector(); - logger.debug("delete " + siObj.getQualifiedName()); - if (!_rwMode) { - return; - } - try { - api.delete(siObj); - } catch (IOException ex) { - logger.warn("service-instance delete", ex); - } - } - - /** - * equalServiceInstance - * - * @param siModel - * @param siObj - * @param logMsg - */ - public void equalServiceInstance(ServiceInstanceModel siModel, ServiceInstance siObj, StringBuffer logMsg) { - logger.debug("equal " + siModel.getQualifiedName()); - } - - static class ServiceInstanceComparator implements Comparator, Serializable { - @Override - public int compare(ServiceInstance obj1, ServiceInstance obj2) { - String name1 = StringUtils.join(obj1.getQualifiedName(), ':'); - String name2 = StringUtils.join(obj2.getQualifiedName(), ':'); - return name1.compareTo(name2); - } - - } - - /** - * The service-instance model list is build as a result of synchronizing virtual-machines. - * @return - */ - public boolean syncServiceInstance() { - final ApiConnector api = _manager.getApiConnector(); - boolean inSync; - try { - @SuppressWarnings("unchecked") - List siList = (List)api.list(ServiceInstance.class, null); - java.util.Collections.sort(siList, new ServiceInstanceComparator()); - DBSyncGeneric.SyncStats stats = new DBSyncGeneric.SyncStats(); - _dbSync.syncCollections(ServiceInstance.class, _manager.getDatabase().getServiceInstances(), siList, _rwMode, stats); - inSync = stats.create == 0 && stats.delete == 0; - } catch (Exception ex) { - logger.warn("synchronize service-instances", ex); - return false; - } - return inSync; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java deleted file mode 100644 index 7fb94d817312..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -public interface ServerEventHandler { - public void subscribe(); -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java deleted file mode 100644 index 2ddb28ea9f22..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServerEventHandlerImpl.java +++ /dev/null @@ -1,241 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.lang.reflect.Method; -import java.util.HashMap; - -import javax.inject.Inject; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.framework.messagebus.MessageBus; -import org.apache.cloudstack.framework.messagebus.MessageDispatcher; -import org.apache.cloudstack.framework.messagebus.MessageHandler; - -import com.cloud.domain.DomainVO; -import com.cloud.domain.dao.DomainDao; -import com.cloud.event.EventTypes; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.projects.ProjectVO; -import com.cloud.projects.dao.ProjectDao; - -/* - * When an Object is created/deleted in cloudstack DB, it has to be reflected in VNC. - * This class handles create, delete and update events of cloudstack db objects. - * - * - subscribe for interested events - * - create events will have db id of the object and hence db object and its parameters can be retrieved - * - delete events will have db id but the object no longer exists in db and hence complete class needs to be synchronized - * - */ -@Component -public class ServerEventHandlerImpl implements ServerEventHandler { - @Inject - NetworkOfferingDao _networkOfferingDao; - @Inject - DomainDao _domainDao; - @Inject - ProjectDao _projectDao; - @Inject - private MessageBus _messageBus; - @Inject - ServerDBSync _dbSync; - @Inject - ContrailManager _manager; - private HashMap _methodMap; - private HashMap> _classMap; - - protected Logger logger = LogManager.getLogger(getClass()); - - ServerEventHandlerImpl() { - setMethodMap(); - setClassMap(); - } - - private void setMethodMap() { - _methodMap = new HashMap(); - Method methods[] = this.getClass().getMethods(); - for (int i = 0; i < methods.length; i++) { - _methodMap.put(methods[i].getName(), methods[i]); - } - } - - private void setClassMap() { - _classMap = new HashMap>(); - _classMap.put("Domain", net.juniper.contrail.api.types.Domain.class); - _classMap.put("Project", net.juniper.contrail.api.types.Project.class); - } - - @MessageHandler(topic = ".*") - public void defaultMessageHandler(String subject, String topic, Object args) { - logger.info("DB Event Received - topic: " + topic + "; subject: " + subject); - - org.apache.cloudstack.framework.events.Event event = (org.apache.cloudstack.framework.events.Event)args; - - /* Method name should be on for example: onDomainCreate */ - Method method = null; - - try { - /* Only create event needs special implementation */ - if (event.getEventType().contains("CREATE")) { - String methodName = "on" + event.getResourceType() + "Create"; - method = _methodMap.get(methodName); - if (method == null) { - defaultCreateHandler(subject, topic, event); - } else { - method.invoke(this, subject, topic, event); - } - } else if (event.getEventType().contains("DELETE")) { - defaultDeleteHandler(subject, topic, event); - } else { - defaultHandler(subject, topic, event); - } - } catch (Exception e) { - logger.debug(e); - } - } - - /* Default create handler */ - void defaultCreateHandler(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { - - logger.debug("Default handler is invoked for subject: " + subject + "; topic: " + topic); - logger.debug("description: " + event.getDescription()); - logger.debug("category: " + event.getEventCategory()); - logger.debug("type: " + event.getResourceType()); - logger.debug("event-type: " + event.getEventType()); - - Class cls = _classMap.get(event.getResourceType()); - - if (cls != null) { - _dbSync.syncClass(cls); - } - - return; - } - - /* Default handler */ - void defaultDeleteHandler(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { - - logger.debug("Default handler is invoked for subject: " + subject + "; topic: " + topic); - - logger.debug("description: " + event.getDescription()); - logger.debug("category: " + event.getEventCategory()); - logger.debug("type: " + event.getResourceType()); - logger.debug("event-type: " + event.getEventType()); - Class cls = _classMap.get(event.getResourceType()); - if (cls != null) { - _dbSync.syncClass(cls); - } - return; - } - - /* Default handler */ - void defaultHandler(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { - - logger.debug("Default handler is invoked for subject: " + subject + "; topic: " + topic); - - logger.debug("description: " + event.getDescription()); - logger.debug("category: " + event.getEventCategory()); - logger.debug("type: " + event.getResourceType()); - logger.debug("event-type: " + event.getEventType()); - Class cls = _classMap.get(event.getResourceType()); - if (cls != null) { - _dbSync.syncClass(cls); - } - return; - } - - /* Description string contains substring of format "resourceType Id: " for example: "Project id: 35" - * - * example: - * description: {"details":"Successfully completed deleting project. Project Id: 39","status":"Completed","event":"PROJECT.DELETE","account":"3afca502-d83c-11e2-b748-52540076b7ca","user":"3b111406-d83c-11e2-b748-52540076b7ca"} - * - * If the description string format is changed, this code has to be modified - */ - private long parseForId(String resourceType, String description) { - String typeStr = resourceType + " Id:"; - int idIdx = description.indexOf(typeStr) + typeStr.length(); - String idStr = description.substring(idIdx, description.indexOf('"', idIdx)); - long id = 0; - try { - id = Long.parseLong(idStr.trim()); - } catch (Exception e) { - logger.debug("Unable to parse id string<" + idStr.trim() + "> for long value, ignored"); - } - return id; - } - - public void onDomainCreate(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { - logger.info("onDomainCreate; topic: " + topic + "; subject: " + subject); - try { - long id = parseForId(event.getResourceType(), event.getDescription()); - if (id != 0) { - DomainVO domain = _domainDao.findById(id); - if (domain != null) { - logger.info("createDomain for name: " + domain.getName() + "; uuid: " + domain.getUuid()); - StringBuffer logMesg = new StringBuffer(); - _dbSync.createDomain(domain, logMesg); - } else { - /* could not find db record, resync complete class */ - _dbSync.syncClass(net.juniper.contrail.api.types.Domain.class); - } - } else { - /* Unknown id, resync complete class */ - _dbSync.syncClass(net.juniper.contrail.api.types.Domain.class); - } - } catch (Exception e) { - logger.debug(e); - } - } - - public void onProjectCreate(String subject, String topic, org.apache.cloudstack.framework.events.Event event) { - logger.info("onProjectCreate; topic: " + topic + "; subject: " + subject); - try { - long id = parseForId(event.getResourceType(), event.getDescription()); - if (id != 0) { - ProjectVO project = _projectDao.findById(id); - if (project != null) { - logger.info("createProject for name: " + project.getName() + "; uuid: " + project.getUuid()); - StringBuffer logMesg = new StringBuffer(); - _dbSync.createProject(project, logMesg); - } else { - /* could not find db record, resync complete class */ - _dbSync.syncClass(net.juniper.contrail.api.types.Project.class); - } - } else { - /* Unknown id, resync complete class */ - _dbSync.syncClass(net.juniper.contrail.api.types.Project.class); - } - } catch (Exception e) { - logger.info(e); - } - - } - - @Override - public void subscribe() { - /* subscribe to DB events */ - _messageBus.subscribe(EventTypes.EVENT_PROJECT_CREATE, MessageDispatcher.getDispatcher(this)); - _messageBus.subscribe(EventTypes.EVENT_PROJECT_DELETE, MessageDispatcher.getDispatcher(this)); - _messageBus.subscribe(EventTypes.EVENT_DOMAIN_CREATE, MessageDispatcher.getDispatcher(this)); - _messageBus.subscribe(EventTypes.EVENT_DOMAIN_DELETE, MessageDispatcher.getDispatcher(this)); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManager.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManager.java deleted file mode 100644 index e4ef26d4a4d9..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManager.java +++ /dev/null @@ -1,41 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; - -import com.cloud.dc.DataCenter; -import com.cloud.network.Network; -import com.cloud.offering.ServiceOffering; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.Account; - -public interface ServiceManager { - /** - * Create a virtual machine that executes a network service appliance (e.g. vSRX) - * @param left Left or inside network (e.g. project network). - * @param right Right or outside network (e.g. public network). - * @return - */ - public ServiceVirtualMachine createServiceInstance(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - Network left, Network right); - - public void startServiceInstance(long instanceId); - - public ServiceInstanceResponse createServiceInstanceResponse(long instanceId); -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java deleted file mode 100644 index ce30b2281181..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceManagerImpl.java +++ /dev/null @@ -1,253 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.network.contrail.api.response.ServiceInstanceResponse; -import org.apache.cloudstack.network.contrail.model.ServiceInstanceModel; -import org.apache.cloudstack.network.contrail.model.VirtualMachineModel; -import org.apache.cloudstack.network.contrail.model.VirtualNetworkModel; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.api.ApiDBUtils; -import com.cloud.dc.DataCenter; -import com.cloud.deploy.DataCenterDeployment; -import com.cloud.event.ActionEvent; -import com.cloud.event.EventTypes; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.network.Network; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkVO; -import com.cloud.offering.ServiceOffering; -import com.cloud.projects.Project; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.Account; -import com.cloud.user.AccountService; -import com.cloud.user.UserVO; -import com.cloud.user.dao.UserDao; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VirtualMachineManager; -import com.cloud.vm.VirtualMachineName; -import com.cloud.vm.dao.UserVmDao; -import com.google.gson.Gson; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.types.ServiceInstance; - -public class ServiceManagerImpl implements ServiceManager { - protected Logger logger = LogManager.getLogger(getClass()); - - @Inject - UserDao _userDao; - @Inject - UserVmDao _vmDao; - @Inject - VirtualMachineManager _vmManager; - @Inject - NetworkModel _networkModel; - @Inject - AccountService _accountService; - @Inject - ContrailManager _manager; - - /** - * In the case of service instance the primary object is in the contrail API server. This object stores the - * service instance parameters in the database. - * - * @param owner Used to determine the project. - * @param name Service instance name (user specified). - * @param template Image to execute. - * @param serviceOffering - * @param left Inside network. - * @param right Outside network. - * @return - */ - - /** - * create a new ServiceVM object. - * @return - */ - @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "createServiceInstance", create = true) - private ServiceVirtualMachine createServiceVM(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - ServiceInstance siObj, Network left, Network right) { - long id = _vmDao.getNextInSequence(Long.class, "id"); - - DataCenterDeployment plan = new DataCenterDeployment(zone.getId()); - LinkedHashMap> networks = new LinkedHashMap>(); - NetworkVO linklocal = (NetworkVO) _networkModel.getSystemNetworkByZoneAndTrafficType(zone.getId(), - TrafficType.Management); - networks.put(linklocal, new ArrayList()); - networks.put((NetworkVO)left, new ArrayList()); - networks.put((NetworkVO)right, new ArrayList()); - String instanceName = VirtualMachineName.getVmName(id, owner.getId(), "SRV"); - - long userId = CallContext.current().getCallingUserId(); - if (CallContext.current().getCallingAccount().getId() != owner.getId()) { - List userVOs = _userDao.listByAccount(owner.getAccountId()); - if (!userVOs.isEmpty()) { - userId = userVOs.get(0).getId(); - } - } - - ServiceVirtualMachine svm = - new ServiceVirtualMachine(id, instanceName, name, template.getId(), serviceOffering.getId(), template.getHypervisorType(), template.getGuestOSId(), - zone.getId(), owner.getDomainId(), owner.getAccountId(), userId, false); - - // database synchronization code must be able to distinguish service instance VMs. - Map kvmap = new HashMap(); - kvmap.put("service-instance", siObj.getUuid()); - Gson json = new Gson(); - String userData = json.toJson(kvmap); - svm.setUserData(userData); - - try { - _vmManager.allocate(instanceName, template, serviceOffering, networks, plan, template.getHypervisorType(), null, null); - } catch (InsufficientCapacityException ex) { - throw new CloudRuntimeException("Insufficient capacity", ex); - } - CallContext.current().setEventDetails("Vm Id: " + svm.getId()); - return svm; - } - - @Override - public ServiceVirtualMachine createServiceInstance(DataCenter zone, Account owner, VirtualMachineTemplate template, ServiceOffering serviceOffering, String name, - Network left, Network right) { - logger.debug("createServiceInstance by " + owner.getAccountName()); - // TODO: permission model. - // service instances need to be able to access the public network. - if (left.getTrafficType() == TrafficType.Guest) { - _networkModel.checkNetworkPermissions(owner, left); - } - if (right.getTrafficType() == TrafficType.Guest) { - _networkModel.checkNetworkPermissions(owner, right); - } - - final ApiConnector api = _manager.getApiConnector(); - VirtualNetworkModel leftModel = _manager.getDatabase().lookupVirtualNetwork(left.getUuid(), - _manager.getCanonicalName(left), left.getTrafficType()); - if (leftModel == null) { - throw new CloudRuntimeException("Unable to read virtual-network object"); - } - VirtualNetworkModel rightModel = _manager.getDatabase().lookupVirtualNetwork(right.getUuid(), - _manager.getCanonicalName(right), right.getTrafficType()); - if (rightModel == null) { - throw new CloudRuntimeException("Unable to read virtual-network object"); - } - - net.juniper.contrail.api.types.Project project; - try { - project = _manager.getVncProject(owner.getDomainId(), owner.getAccountId()); - } catch (IOException ex) { - logger.warn("read project", ex); - throw new CloudRuntimeException(ex); - } - - try { - final String srvid = api.findByName(ServiceInstance.class, project, name); - if (srvid != null) { - throw new InvalidParameterValueException("service-instance " + name + " already exists uuid=" + srvid); - } - } catch (IOException ex) { - logger.warn("service-instance lookup", ex); - throw new CloudRuntimeException(ex); - } - - // 1. Create service-instance. - ServiceInstanceModel serviceModel = new ServiceInstanceModel(project, name, template, serviceOffering, - leftModel, rightModel); - - try { - serviceModel.update(_manager.getModelController()); - } catch (Exception ex) { - logger.warn("service-instance update", ex); - throw new CloudRuntimeException(ex); - } - - logger.debug("service-instance object created"); - - ServiceInstance siObj; - try { - _manager.getDatabase().getServiceInstances().add(serviceModel); - siObj = serviceModel.getServiceInstance(); - } catch (Exception ex) { - logger.warn("DB add", ex); - throw new CloudRuntimeException(ex); - } - - // 2. Create one virtual-machine. - String svmName = name.replace(" ", "_") + "-1"; - ServiceVirtualMachine svm = createServiceVM(zone, owner, template, serviceOffering, svmName, siObj, left, right); - - logger.debug("created VMInstance " + svm.getUuid()); - - // 3. Create the virtual-machine model and push the update. - VirtualMachineModel instanceModel = new VirtualMachineModel(svm, svm.getUuid()); - _manager.getDatabase().getVirtualMachines().add(instanceModel); - try { - instanceModel.setServiceInstance(_manager.getModelController(), svm, serviceModel); - instanceModel.update(_manager.getModelController()); - } catch (Exception ex) { - logger.warn("service virtual-machine update", ex); - throw new CloudRuntimeException(ex); - } - - return svm; - } - - @Override - public void startServiceInstance(long instanceId) { - logger.debug("start service instance " + instanceId); - - UserVmVO vm = _vmDao.findById(instanceId); - _vmManager.start(vm.getUuid(), null); - } - - @Override - public ServiceInstanceResponse createServiceInstanceResponse(long instanceId) { - logger.debug("ServiceInstance response for id: " + instanceId); - - UserVmVO vm = _vmDao.findById(instanceId); - ServiceInstanceResponse response = new ServiceInstanceResponse(); - response.setId(vm.getUuid()); - Account owner = _accountService.getAccount(vm.getAccountId()); - - if (owner.getType() == Account.Type.PROJECT) { - Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(owner.getAccountId()); - response.setProjectId(project.getUuid()); - response.setProjectName(project.getName()); - } else { - response.setAccountName(owner.getAccountName()); - } - return response; - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java deleted file mode 100644 index ea5e24aa1614..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/management/ServiceVirtualMachine.java +++ /dev/null @@ -1,28 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.vm.UserVmVO; - -public class ServiceVirtualMachine extends UserVmVO { - public ServiceVirtualMachine(long id, String instanceName, String name, long templateId, long serviceOfferingId, HypervisorType hypervisorType, long guestOSId, - long dataCenterId, long domainId, long accountId, long userId, boolean haEnabled) { - super(id, instanceName, name, templateId, hypervisorType, guestOSId, false, false, domainId, accountId, userId, serviceOfferingId, null, null, null, name); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java deleted file mode 100644 index 4a411fa809d1..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpModel.java +++ /dev/null @@ -1,211 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.types.FloatingIp; - - -import org.apache.cloudstack.network.contrail.management.ContrailManager; - -import com.cloud.exception.InternalErrorException; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; - -public class FloatingIpModel extends ModelObjectBase { - - private String _uuid; - private long _id; - private String _name; - private String _addr; - private boolean _initialized; - - /* - * cached API server objects - */ - private FloatingIp _fip; - private FloatingIpPoolModel _fipPoolModel; - - public FloatingIpModel(String uuid) { - _uuid = uuid; - } - - public void addToFloatingIpPool(FloatingIpPoolModel fipPoolModel) { - _fipPoolModel = fipPoolModel; - if (fipPoolModel != null) { - fipPoolModel.addSuccessor(this); - } - } - - public void addToVMInterface(VMInterfaceModel vmiModel) { - if (vmiModel != null) { - vmiModel.addSuccessor(this); - } - } - - /* - * Resynchronize internal state from the cloudstack DB object. - */ - public void build(ModelController controller, PublicIpAddress ip) { - setProperties(controller, ip); - } - - @Override - public int compareTo(ModelObject o) { - FloatingIpModel other; - try { - other = (FloatingIpModel)o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return FloatingIpModel.class.getName().compareTo(clsname); - } - - return _uuid.compareTo(other._uuid); - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - for (ModelObject successor : successors()) { - successor.delete(controller); - } - - try { - api.delete(FloatingIp.class, _uuid); - } catch (IOException ex) { - logger.warn("floating ip delete", ex); - } - } - - @Override - public void destroy(ModelController controller) throws IOException { - delete(controller); - - for (ModelObject successor : successors()) { - successor.destroy(controller); - } - clearSuccessors(); - } - - public String getName() { - return _name; - } - - public String getUuid() { - return _uuid; - } - - public FloatingIp getFloatingIp() { - return _fip; - } - - /** - * Initialize the object properties based on the DB object. - * Common code between plugin calls and DBSync. - */ - public void setProperties(ModelController controller, PublicIpAddress ip) { - _uuid = ip.getUuid(); - _name = Long.toString(ip.getId()); - _addr = ip.getAddress().addr(); - _id = ip.getId(); - assert _fipPoolModel != null : "floating ip uuid is not set"; - _initialized = true; - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - - assert _initialized; - - ApiConnector api = controller.getApiAccessor(); - ContrailManager manager = controller.getManager(); - FloatingIp fip = _fip; - - if (_fip == null) { - _fip = fip = (FloatingIp)controller.getApiAccessor().findById(FloatingIp.class, _uuid); - if (fip == null) { - fip = new FloatingIp(); - fip.setUuid(_uuid); - fip.setAddress(_addr); - fip.setName(_name); - fip.setParent(_fipPoolModel.getFloatingIpPool()); - } - } - - IPAddressVO ipAddrVO = controller.getIPAddressDao().findById(_id); - assert ipAddrVO != null : "can not find address object in db"; - Long vmId = ipAddrVO.getAssociatedWithVmId(); - Long networkId = ipAddrVO.getAssociatedWithNetworkId(); - if (vmId == null || networkId == null) { - logger.debug("Floating ip is not yet associated to either vm or network"); - return; - } - NicVO nic = controller.getNicDao().findByNtwkIdAndInstanceId(networkId, vmId); - assert nic != null : "can not find nic for the given network and vm in db"; - - VMInstanceVO vm = controller.getVmDao().findById(vmId); - assert vm != null : "can not find vm in db"; - - VirtualMachineModel vmModel = manager.getDatabase().lookupVirtualMachine(vm.getUuid()); - assert vmModel != null : "can not find vm model"; - - VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid()); - assert vmiModel != null && vmiModel.getVMInterface() != null : "can not find virtual machine interface"; - - fip.setVirtualMachineInterface(vmiModel.getVMInterface()); - - if (_fip == null) { - try { - api.create(fip); - } catch (Exception ex) { - logger.debug("floating ip create", ex); - throw new CloudRuntimeException("Failed to create floating ip", ex); - } - _fip = fip; - } else { - try { - api.update(fip); - } catch (IOException ex) { - logger.warn("floating ip update", ex); - throw new CloudRuntimeException("Unable to update floating ip object", ex); - } - } - - addToVMInterface(vmiModel); - - for (ModelObject successor : successors()) { - successor.update(controller); - } - } - - @Override - public boolean verify(ModelController controller) { - assert _initialized : "initialized is false"; - return false; - } - - @Override - public boolean compare(ModelController controller, ModelObject o) { - return true; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java deleted file mode 100644 index 1ae7dc924d32..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/FloatingIpPoolModel.java +++ /dev/null @@ -1,169 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; -import java.util.TreeSet; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.types.FloatingIpPool; - - -import org.apache.cloudstack.network.contrail.management.ContrailManager; - -import com.cloud.exception.InternalErrorException; -import com.cloud.utils.exception.CloudRuntimeException; - -public class FloatingIpPoolModel extends ModelObjectBase { - - private String _name; - - /* - * cached API server objects - */ - private FloatingIpPool _fipPool; - private VirtualNetworkModel _vnModel; - - public FloatingIpPoolModel() { - - } - - public void addToVirtualNetwork(VirtualNetworkModel vnModel) { - _vnModel = vnModel; - if (vnModel != null) { - vnModel.addSuccessor(this); - } - } - - public FloatingIpModel getFloatingIpModel(String uuid) { - TreeSet tree = successors(); - FloatingIpModel fipKey = new FloatingIpModel(uuid); - FloatingIpModel current = (FloatingIpModel)tree.ceiling(fipKey); - if (current != null && current.getUuid().equals(uuid)) { - return current; - } - return null; - } - - /* - * Resynchronize internal state from the cloudstack DB object. - */ - public void build(ModelController controller) { - setProperties(controller); - } - - @Override - public int compareTo(ModelObject o) { - /* there can be only one instance */ - return 0; - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - for (ModelObject successor : successors()) { - successor.delete(controller); - } - try { - if (_fipPool != null) { - api.delete(_fipPool); - } - _fipPool = null; - } catch (IOException ex) { - logger.warn("floating ip pool delete", ex); - } - } - - @Override - public void destroy(ModelController controller) throws IOException { - delete(controller); - for (ModelObject successor : successors()) { - successor.destroy(controller); - } - clearSuccessors(); - } - - public String getName() { - return _name; - } - - public FloatingIpPool getFloatingIpPool() { - return _fipPool; - } - - /** - * Initialize the object properties based on the DB object. - * Common code between plugin calls and DBSync. - */ - public void setProperties(ModelController controller) { - _name = "PublicIpPool"; - assert _vnModel != null : "vn nodel is not initialized"; - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - - assert _vnModel != null : "vn model is not set"; - - ApiConnector api = controller.getApiAccessor(); - ContrailManager manager = controller.getManager(); - FloatingIpPool fipPool = _fipPool; - - if (fipPool == null) { - String fipPoolName = manager.getDefaultPublicNetworkFQN() + ":PublicIpPool"; - _fipPool = fipPool = (FloatingIpPool)controller.getApiAccessor().findByFQN(FloatingIpPool.class, fipPoolName); - if (fipPool == null) { - fipPool = new FloatingIpPool(); - fipPool.setName(_name); - fipPool.setParent(_vnModel.getVirtualNetwork()); - } - } - - if (_fipPool == null) { - try { - api.create(fipPool); - } catch (Exception ex) { - logger.debug("floating ip pool create", ex); - throw new CloudRuntimeException("Failed to create floating ip pool", ex); - } - _fipPool = fipPool; - } else { - try { - api.update(fipPool); - } catch (IOException ex) { - logger.warn("floating ip pool update", ex); - throw new CloudRuntimeException("Unable to update floating ip ppol object", ex); - } - } - - for (ModelObject successor : successors()) { - successor.update(controller); - } - } - - @Override - public boolean verify(ModelController controller) { - assert _vnModel != null : "vn model is not set"; - return false; - } - - @Override - public boolean compare(ModelController controller, ModelObject o) { - return true; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java deleted file mode 100644 index 2acc0fb14314..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/InstanceIpModel.java +++ /dev/null @@ -1,170 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.InstanceIp; -import net.juniper.contrail.api.types.VirtualMachineInterface; -import net.juniper.contrail.api.types.VirtualNetwork; - - -import com.cloud.exception.InternalErrorException; - -public class InstanceIpModel extends ModelObjectBase { - - private String _name; - private String _uuid; - - private String _ipAddress; - - private VMInterfaceModel _vmiModel; - - public InstanceIpModel(String vmName, int deviceId) { - _name = vmName + '-' + deviceId; - } - - public void addToVMInterface(VMInterfaceModel vmiModel) { - _vmiModel = vmiModel; - if (vmiModel != null) { - vmiModel.addSuccessor(this); - logger.debug("vmiModel has " + vmiModel.successors().size() + " IP addresses"); - } - } - - @Override - public int compareTo(ModelObject o) { - InstanceIpModel other; - try { - other = (InstanceIpModel)o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return InstanceIpModel.class.getName().compareTo(clsname); - } - return _name.compareTo(other._name); - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - if (_uuid != null) { - api.delete(InstanceIp.class, _uuid); - } - _uuid = null; - } - - @Override - public void destroy(ModelController controller) throws IOException { - } - - public String getAddress() { - return _ipAddress; - } - - public String getName() { - return _name; - } - - public void setAddress(String ipaddress) { - _ipAddress = ipaddress; - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - assert _vmiModel != null; - - ApiConnector api = controller.getApiAccessor(); - VirtualNetworkModel vnModel = _vmiModel.getVirtualNetworkModel(); - assert vnModel != null; - - VirtualMachineInterface vmi = _vmiModel.getVMInterface(); - VirtualNetwork vnet = vnModel.getVirtualNetwork(); - if (vnet == null) { - vnet = (VirtualNetwork)api.findById(VirtualNetwork.class, _vmiModel.getNetworkUuid()); - } - - String ipid = api.findByName(InstanceIp.class, null, _name); - if (ipid == null) { - InstanceIp ip_obj = new InstanceIp(); - ip_obj.setName(_name); - ip_obj.setVirtualNetwork(vnet); - if (_ipAddress != null) { - ip_obj.setAddress(_ipAddress); - } - ip_obj.setVirtualMachineInterface(vmi); - if (!api.create(ip_obj)) { - throw new InternalErrorException("Unable to create instance-ip " + _name); - } - api.read(ip_obj); - _uuid = ip_obj.getUuid(); - if (_ipAddress == null) { - if (!api.read(ip_obj)) { - throw new InternalErrorException("Unable to read instance-ip " + _name); - } - } - _ipAddress = ip_obj.getAddress(); - } else { - // Ensure that the instance-ip has the correct value and is pointing at the VMI. - InstanceIp ip_obj = (InstanceIp)api.findById(InstanceIp.class, ipid); - if (ip_obj == null) { - throw new InternalErrorException("Unable to read instance-ip " + _name); - } - boolean update = false; - String ipnet_id = ObjectReference.getReferenceListUuid(ip_obj.getVirtualNetwork()); - if (ipnet_id == null || !ipnet_id.equals(_vmiModel.getNetworkUuid())) { - ip_obj.setVirtualNetwork(vnet); - update = true; - } - - if (_ipAddress != null && !ip_obj.getAddress().equals(_ipAddress)) { - ip_obj.setAddress(_ipAddress); - update = true; - } - - String vmi_id = ObjectReference.getReferenceListUuid(ip_obj.getVirtualMachineInterface()); - if (vmi_id == null || !vmi_id.equals(_vmiModel.getUuid())) { - if (vmi != null) { - ip_obj.setVirtualMachineInterface(vmi); - update = true; - } - } - - if (update && !api.update(ip_obj)) { - throw new InternalErrorException("Unable to update instance-ip: " + ip_obj.getName()); - } - api.read(ip_obj); - _uuid = ip_obj.getUuid(); - _ipAddress = ip_obj.getAddress(); - } - } - - @Override - public boolean verify(ModelController controller) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean compare(ModelController controller, ModelObject current) { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelController.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelController.java deleted file mode 100644 index 08b8e3456683..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelController.java +++ /dev/null @@ -1,86 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import net.juniper.contrail.api.ApiConnector; - -import org.apache.cloudstack.network.contrail.management.ContrailManager; - -import com.cloud.dc.dao.VlanDao; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.NetworkDao; -import com.cloud.vm.dao.NicDao; -import com.cloud.vm.dao.UserVmDao; - -/** - * Collection of state necessary for model object to update the Contrail API server. - * - */ -public class ModelController { - ApiConnector _api; - ContrailManager _manager; - UserVmDao _vmDao; - NetworkDao _networkDao; - NicDao _nicDao; - VlanDao _vlanDao; - IPAddressDao _ipAddressDao; - - public ModelController(ContrailManager manager, ApiConnector api, UserVmDao vmDao, NetworkDao networkDao, NicDao nicDao, VlanDao vlanDao, IPAddressDao ipAddressDao) { - _manager = manager; - assert api != null; - _api = api; - assert vmDao != null; - _vmDao = vmDao; - assert networkDao != null; - _networkDao = networkDao; - assert nicDao != null; - _nicDao = nicDao; - assert vlanDao != null; - _vlanDao = vlanDao; - assert ipAddressDao != null; - _ipAddressDao = ipAddressDao; - } - - ApiConnector getApiAccessor() { - return _api; - } - - ContrailManager getManager() { - return _manager; - } - - UserVmDao getVmDao() { - return _vmDao; - } - - NetworkDao getNetworkDao() { - return _networkDao; - } - - NicDao getNicDao() { - return _nicDao; - } - - VlanDao getVlanDao() { - return _vlanDao; - } - - IPAddressDao getIPAddressDao() { - return _ipAddressDao; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObject.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObject.java deleted file mode 100644 index fce3a46e2e96..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObject.java +++ /dev/null @@ -1,150 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; -import java.io.Serializable; -import java.lang.ref.WeakReference; -import java.util.TreeSet; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.exception.InternalErrorException; - -/** - * ModelObject - * - * A model object represents the desired state of the system. - * - * The object constructor should set the uuid and the internal id of the cloudstack objects. - * - * The build method reads the primary database (typically cloudstack mysql) and derives the state that - * we wish to reflect in the contrail API. This method should not modify the Contrail API state. - * - * The verify method reads the API server state and compares with cached properties. - * - * The update method pushes updates to the contrail API server. - */ -public interface ModelObject { - - public static class ModelReference implements Comparable, Serializable { - - private static final long serialVersionUID = -2019113974956703526L; - protected Logger logger = LogManager.getLogger(getClass()); - - /* - * WeakReference class is not serializable by definition. So, we cannot enforce its serialization unless we write the implementation of - * methods writeObject() and readObject(). Since the code was already not serializing it, it's been marked as transient. - */ - transient WeakReference reference; - - ModelReference(ModelObject obj) { - reference = new WeakReference(obj); - } - - @Override - public int compareTo(ModelReference other) { - ModelObject lhs = reference.get(); - ModelObject rhs = other.reference.get(); - if (lhs == null) { - if (rhs == null) { - return 0; - } - return -1; - } - - return lhs.compareTo(rhs); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((reference == null) ? 0 : reference.hashCode()); - return result; - } - - @Override - public boolean equals(Object other) { - if (this == other) - return true; - if (other == null) - return false; - try { - ModelReference rhs = (ModelReference)other; - return compareTo(rhs) == 0; - } catch (ClassCastException ex) { - // not this class , so - return false; - } - } - - public ModelObject get() { - return reference.get(); - } - - }; - - public void addSuccessor(ModelObject child); - - public TreeSet ancestors(); - - public void clearSuccessors(); - - public int compareTo(ModelObject o); - - /** - * Delete the object from the API server. - * @param controller - * @throws IOException - */ - public void delete(ModelController controller) throws IOException; - - /** - * Deletes the object from the data model graph. - * - * @param controller - * @throws IOException - */ - public void destroy(ModelController controller) throws IOException; - - public void removeSuccessor(ModelObject child); - - public TreeSet successors(); - - /** - * Push updates to Contrail API server. This API is only valid for objects in the database. - * @param controller - * @throws IOException - * @throws InternalErrorException - */ - public void update(ModelController controller) throws InternalErrorException, IOException; - - /** - * Check that the state of the current object matches the state of the API server. - * @param controller - * @return - */ - public boolean verify(ModelController controller); - - /* - * Compare the state of existing model object with latest model object - */ - public boolean compare(ModelController controller, ModelObject current); -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java deleted file mode 100644 index 0c13951a8aaf..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ModelObjectBase.java +++ /dev/null @@ -1,130 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.TreeSet; - -public abstract class ModelObjectBase implements ModelObject { - protected Logger logger = LogManager.getLogger(getClass()); - public static class UuidComparator implements Comparator, Serializable { - @Override - public int compare(ModelObject lhs, ModelObject rhs) { - if (lhs == null) { - if (rhs == null) { - return 0; - } - return -1; - } - if (rhs == null) { - return 1; - } - return lhs.compareTo(rhs); - } - } - - private TreeSet _ancestors; - - private TreeSet _successors; - - ModelObjectBase() { - _ancestors = new TreeSet(); - _successors = new TreeSet(new UuidComparator()); - } - - @Override - public void addSuccessor(ModelObject child) { - _successors.add(child); - ModelObjectBase base = (ModelObjectBase)child; - base._ancestors.add(new ModelReference(this)); - } - - @Override - public TreeSet ancestors() { - return _ancestors; - } - - private void clearAncestorReference(ModelObjectBase child) { - ModelReference ref = null; - for (ModelReference objref : child._ancestors) { - if (objref.get() == this) { - ref = objref; - break; - } - } - if (ref != null) { - child._ancestors.remove(ref); - } - } - - @Override - public void clearSuccessors() { - for (ModelObject successor : _successors) { - clearAncestorReference((ModelObjectBase)successor); - } - _successors.clear(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((_ancestors == null) ? 0 : _ancestors.hashCode()); - result = prime * result + ((_successors == null) ? 0 : _successors.hashCode()); - return result; - } - - @Override - public boolean equals(Object rhs) { - if (this == rhs) - return true; - if (rhs == null) - return false; - ModelObject other; - try { - other = (ModelObject)rhs; - } catch (ClassCastException ex) { - return false; - } - return compareTo(other) == 0; - } - - @Override - protected void finalize() { - clearSuccessors(); - } - - public boolean hasDescendents() { - return !successors().isEmpty(); - } - - @Override - public void removeSuccessor(ModelObject child) { - clearAncestorReference((ModelObjectBase)child); - _successors.remove(child); - } - - @Override - public TreeSet successors() { - return _successors; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java deleted file mode 100644 index d53d045ed5b1..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/NetworkPolicyModel.java +++ /dev/null @@ -1,303 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - -import com.cloud.network.Networks; - -import net.juniper.contrail.api.types.NetworkPolicy; -import net.juniper.contrail.api.types.PolicyEntriesType; -import net.juniper.contrail.api.types.PolicyEntriesType.PolicyRuleType; -import net.juniper.contrail.api.types.Project; -import net.juniper.contrail.api.ApiConnector; -import org.apache.cloudstack.network.contrail.management.ContrailManager; - -import com.cloud.exception.InternalErrorException; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.vpc.NetworkACLItem; -import com.cloud.network.vpc.NetworkACLItem.Action; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.exception.CloudRuntimeException; - -public class NetworkPolicyModel extends ModelObjectBase { - - private String _uuid; - private String _fqName; - private String _name; - private Project _project; - private NetworkPolicy _policy; - PolicyEntriesType _policyMap; - - public NetworkPolicyModel(String uuid, String name) { - _uuid = uuid; - _name = name; - } - - public String getQualifiedName() { - return _fqName; - } - - public String getName() { - return _name; - } - - public NetworkVO cidrToNetwork(ModelController controller, String cidr) { - SearchBuilder searchBuilder = controller.getNetworkDao().createSearchBuilder(); - searchBuilder.and("trafficType", searchBuilder.entity().getTrafficType(), Op.EQ); - searchBuilder.and("cidr", searchBuilder.entity().getCidr(), Op.EQ); - searchBuilder.and("networkOfferingId", searchBuilder.entity().getNetworkOfferingId(), Op.EQ); - - SearchCriteria sc = searchBuilder.create(); - - sc.setParameters("networkOfferingId", controller.getManager().getVpcRouterOffering().getId()); - sc.setParameters("cidr", cidr); - sc.setParameters("trafficType", Networks.TrafficType.Guest); - - List dbNets = controller.getNetworkDao().search(sc, null); - if (dbNets == null || dbNets.size() == 0) { - return null; - } - if (dbNets.size() > 1) { - logger.warn("more than one network found with cidr: " + cidr); - } - return dbNets.get(0); - } - - public void build(ModelController controller, List rules) throws Exception { - String projectName = null; - if (_project != null) { - _fqName = StringUtils.join(_project.getQualifiedName(), ':') + ":" + _name; - projectName = StringUtils.join(_project.getQualifiedName(), ':'); - } else { - _fqName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + _name; - projectName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT; - } - - PolicyEntriesType policyMap = new PolicyEntriesType(); - - for (NetworkACLItem rule:rules) { - if (rule.getState() != NetworkACLItem.State.Active && - rule.getState() != NetworkACLItem.State.Add) { - continue; - } - - String action = null; - if (rule.getAction() == Action.Allow) { - action = "pass"; - } else if (rule.getAction() == Action.Deny) { - action = "deny"; - } - List cidrList = rule.getSourceCidrList(); - String protocol = rule.getProtocol(); - if (protocol == null || protocol.equalsIgnoreCase("ALL") || protocol.isEmpty()) { - protocol = "any"; - } else { - protocol = protocol.toLowerCase(); - } - - Integer portStart = rule.getSourcePortStart(); - Integer portEnd = rule.getSourcePortEnd(); - if (portStart == null) { - portStart = 0; - } - if (portEnd == null) { - portEnd = 65535; - } - - List srcList = new ArrayList(); - List dstList = new ArrayList(); - - List srcPorts = new ArrayList(); - List dstPorts = new ArrayList(); - - if (rule.getTrafficType() == NetworkACLItem.TrafficType.Egress){ - for (String cidr: cidrList) { - NetworkVO net = cidrToNetwork(controller, cidr); - /*String[] maskInfo = StringUtils.splitByWholeSeparator(cidr, "/"); - SubnetType subnet = new SubnetType(); - subnet.setIpPrefix(maskInfo[0]); - subnet.setIpPrefixLen(Integer.parseInt(maskInfo[1])); - */ - String netName = projectName + ":" + controller.getManager().getCanonicalName(net); - dstList.add(new PolicyRuleType.AddressType(null, netName, null)); - } - dstPorts.add(new PolicyRuleType.PortType(portStart, portEnd)); - srcList.add(new PolicyRuleType.AddressType(null, "local", null)); - srcPorts.add(new PolicyRuleType.PortType(0, 65535)); - } else { - for (String cidr: cidrList) { - NetworkVO net = cidrToNetwork(controller, cidr); - String netName = projectName + ":" + controller.getManager().getCanonicalName(net); - srcList.add(new PolicyRuleType.AddressType(null, netName, null)); - } - dstPorts.add(new PolicyRuleType.PortType(portStart, portEnd)); - - dstList.add(new PolicyRuleType.AddressType(null, "local", null)); - srcPorts.add(new PolicyRuleType.PortType(0, 65535)); - } - - PolicyRuleType vnRule = new PolicyRuleType( - new PolicyRuleType.SequenceType(1, 0), rule.getUuid(), "<>", protocol, - srcList, srcPorts, null, dstList, dstPorts, - new PolicyRuleType.ActionListType(action, null, null, null)); - policyMap.addPolicyRule(vnRule); - } - _policyMap = policyMap; - } - - /* for service instance policy */ - public void build(ModelController modelController, String leftVn, String rightVn, String gatewayName, - List siList, String action) { - if (_project != null) { - _fqName = StringUtils.join(_project.getQualifiedName(), ':') + ":" + _name; - } else { - _fqName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + _name; - } - - PolicyEntriesType policyMap = new PolicyEntriesType(); - List srcList = new ArrayList(); - srcList.add(new PolicyRuleType.AddressType(null, leftVn, null)); - List dstList = new ArrayList(); - dstList.add(new PolicyRuleType.AddressType(null, rightVn, null)); - - List portAny = new ArrayList(); - portAny.add(new PolicyRuleType.PortType(0, 65535)); - - PolicyRuleType rule = new PolicyRuleType( - new PolicyRuleType.SequenceType(1, 0), null, "<>", "any", - srcList, portAny, null, dstList, portAny, - new PolicyRuleType.ActionListType(action, gatewayName, siList, null)); - policyMap.addPolicyRule(rule); - _policyMap = policyMap; - } - - public boolean hasPolicyRules() { - if (_policyMap != null && _policyMap.getPolicyRule() != null && _policyMap.getPolicyRule().size() > 0) { - return true; - } - return false; - } - - @Override - public int compareTo(ModelObject o) { - NetworkPolicyModel other; - try { - other = (NetworkPolicyModel) o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return NetworkPolicyModel.class.getName().compareTo(clsname); - } - return _uuid.compareTo(other._uuid); - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - if (_policy != null) { - api.delete(_policy); - _policy = null; - } - } - - @Override - public void destroy(ModelController controller) throws IOException { - } - - public String getUuid() { - return _uuid; - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - ApiConnector api = controller.getApiAccessor(); - if (_project == null) { - logger.debug("Project is null for the policy: " + _name); - throw new IOException("Project is null for the policy: " + _name); - } - - NetworkPolicy policy = _policy; - - if (policy == null) { - try { - String policyId = api.findByName(NetworkPolicy.class, _project, _name); - if (policyId != null) { - policy = _policy = (NetworkPolicy) api.findById(NetworkPolicy.class, policyId); - } - if (policy == null) { - policy = new NetworkPolicy(); - policy.setUuid(_uuid); - policy.setName(_name); - policy.setParent(_project); - } - } catch (IOException ex) { - logger.warn("network-policy read", ex); - return; - } - } - - policy.setEntries(_policyMap); - if (_policy == null) { - try { - api.create(policy); - } catch (Exception ex) { - logger.debug("network policy create", ex); - throw new CloudRuntimeException("Failed to create network policy", ex); - } - _policy = policy; - } else { - try { - api.update(policy); - } catch (IOException ex) { - logger.warn("network policy update", ex); - throw new CloudRuntimeException("Unable to update network policy", ex); - } - } - for (ModelObject successor: successors()) { - successor.update(controller); - } - } - - @Override - public boolean verify(ModelController controller) { - return false; - } - - @Override - public boolean compare(ModelController controller, ModelObject current) { - return true; - } - - public void setProperties(ModelController controller, List rules) { - - } - - public void setProject(Project project) { - _project = project; - } - - public NetworkPolicy getPolicy() { - return _policy; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java deleted file mode 100644 index 7f2bfe73e891..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/ServiceInstanceModel.java +++ /dev/null @@ -1,285 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.Project; -import net.juniper.contrail.api.types.ServiceInstance; -import net.juniper.contrail.api.types.ServiceInstanceType; -import net.juniper.contrail.api.types.ServiceTemplate; -import net.juniper.contrail.api.types.ServiceTemplateType; - -import org.apache.cloudstack.network.contrail.management.ContrailManager; -import org.apache.commons.lang3.StringUtils; - -import com.cloud.offering.ServiceOffering; -import com.cloud.template.VirtualMachineTemplate; -import com.cloud.utils.exception.CloudRuntimeException; - -public class ServiceInstanceModel extends ModelObjectBase { - - private String _uuid; - private String _fqName; - private String _projectId; - private String _mgmtName; - private String _leftName; - private String _rightName; - - private String _templateName; - private String _templateId; - private String _templateUrl; - private VirtualNetworkModel _left; - private VirtualNetworkModel _right; - private ServiceTemplate _tmpl; - private ServiceInstance _serviceInstance; - private NetworkPolicyModel _policy; - - /** - * Create a ServiceInstance as result of an API call. - * - * @param owner - * @param name - * @param template - * @param serviceOffering - * @param left - * @param right - */ - public ServiceInstanceModel(Project project, String name, VirtualMachineTemplate template, ServiceOffering serviceOffering, VirtualNetworkModel left, VirtualNetworkModel right) { - String parent_name; - if (project != null) { - parent_name = StringUtils.join(project.getQualifiedName(), ':'); - - _projectId = project.getUuid(); - } else { - parent_name = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT; - - //In the original code, if the projectId is null, it will simply throw NPE on the last line (nr. 90) of the method where the projectId.getUuid() is called. - //This was added as a way to avoid NPE. Should we perhaps throw a CloudRuntimeException if the project object is null? - _projectId = UUID.randomUUID().toString(); - } - _fqName = parent_name + ":" + name; - - _mgmtName = ContrailManager.VNC_ROOT_DOMAIN + ":" + ContrailManager.VNC_DEFAULT_PROJECT + ":" + ContrailManager.managementNetworkName; - _left = left; - _right = right; - _leftName = StringUtils.join(left.getVirtualNetwork().getQualifiedName(), ":"); - _rightName = StringUtils.join(right.getVirtualNetwork().getQualifiedName(), ":"); - - _templateName = template.getName(); - _templateId = template.getUuid(); - _templateUrl = template.getUrl(); - } - - /** - * Create an empty ServiceInstance. - * @param uuid - */ - public ServiceInstanceModel(String uuid) { - _uuid = uuid; - } - - public String getQualifiedName() { - return _fqName; - } - - public String getName() { - return _fqName.substring(_fqName.lastIndexOf(':') + 1); - } - - /** - * Recreate the model object from the Contrail API which is main for this type of object. - * @param siObj - */ - public void build(ModelController controller, ServiceInstance siObj) { - ApiConnector api = controller.getApiAccessor(); - _serviceInstance = siObj; - _fqName = StringUtils.join(siObj.getQualifiedName(), ':'); - ServiceInstanceType props = siObj.getProperties(); - // TODO: read management network names and cache network objects. - ObjectReference ref = siObj.getServiceTemplate().get(0); - if (ref != null) { - try { - ServiceTemplate tmpl = (ServiceTemplate)api.findById(ServiceTemplate.class, ref.getUuid()); - _templateId = tmpl.getUuid(); - } catch (IOException ex) { - logger.warn("service-template read", ex); - } - } - } - - @Override - public int compareTo(ModelObject o) { - ServiceInstanceModel other; - try { - other = (ServiceInstanceModel)o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return ServiceInstanceModel.class.getName().compareTo(clsname); - } - return _fqName.compareTo(other._fqName); - } - - private ServiceInstance createServiceInstance(ModelController controller) { - Project project = null; - if (_projectId != null) { - try { - ApiConnector api = controller.getApiAccessor(); - project = (Project)api.findById(Project.class, _projectId); - } catch (IOException ex) { - logger.warn("project read", ex); - throw new CloudRuntimeException("Unable to create service-instance object", ex); - } - } - - ServiceInstance si_obj = new ServiceInstance(); - if (project != null) { - si_obj.setParent(project); - } - si_obj.setName(getName()); - si_obj.setServiceTemplate(_tmpl); - si_obj.setProperties(new ServiceInstanceType(false, _mgmtName, _leftName, null, _rightName, null, new ServiceInstanceType.ServiceScaleOutType(1, false))); - try { - ApiConnector api = controller.getApiAccessor(); - api.create(si_obj); - } catch (IOException ex) { - logger.warn("service-instance create", ex); - throw new CloudRuntimeException("Unable to create service-instance object", ex); - } - - return si_obj; - } - - private void clearServicePolicy(ModelController controller) { - _left.addToNetworkPolicy(null); - _right.addToNetworkPolicy(null); - try { - controller.getManager().getDatabase().getNetworkPolicys().remove(_policy); - _policy.delete(controller.getManager().getModelController()); - _policy = null; - } catch (Exception e) { - logger.error(e); - } - try { - _left.update(controller.getManager().getModelController()); - _right.update(controller.getManager().getModelController()); - } catch (Exception ex) { - logger.error("virtual-network update for policy delete: ", ex); - } - } - - private NetworkPolicyModel setServicePolicy(ModelController controller) { - NetworkPolicyModel policyModel = new NetworkPolicyModel(UUID.randomUUID().toString(), _serviceInstance.getName()); - policyModel.setProject((Project)_serviceInstance.getParent()); - _left.addToNetworkPolicy(policyModel); - _right.addToNetworkPolicy(policyModel); - List siList = new ArrayList(); - siList.add(StringUtils.join(_serviceInstance.getQualifiedName(), ':')); - try { - policyModel.build(controller.getManager().getModelController(), _leftName, _rightName, "in-network", siList, "pass"); - } catch (Exception e) { - logger.error(e); - return null; - } - try { - if (!policyModel.verify(controller.getManager().getModelController())) { - policyModel.update(controller.getManager().getModelController()); - } - controller.getManager().getDatabase().getNetworkPolicys().add(policyModel); - } catch (Exception ex) { - logger.error("network-policy update: ", ex); - } - return policyModel; - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - clearServicePolicy(controller); - if (_serviceInstance != null) { - api.delete(_serviceInstance); - } - } - - @Override - public void destroy(ModelController controller) throws IOException { - } - - public ServiceInstance getServiceInstance() { - return _serviceInstance; - } - - public String getUuid() { - return _uuid; - } - - private ServiceTemplate locateServiceTemplate(ModelController controller) { - ServiceTemplate tmpl; - try { - ApiConnector api = controller.getApiAccessor(); - tmpl = (ServiceTemplate)api.findById(ServiceTemplate.class, _templateId); - } catch (IOException ex) { - logger.warn("service-template read", ex); - throw new CloudRuntimeException("Unable to create service-template object", ex); - } - if (tmpl == null) { - tmpl = new ServiceTemplate(); - tmpl.setName(_templateName); - tmpl.setUuid(_templateId); - ServiceTemplateType props = new ServiceTemplateType("in-network", null, _templateUrl, false, null); - tmpl.setProperties(props); - try { - ApiConnector api = controller.getApiAccessor(); - api.create(tmpl); - } catch (IOException ex) { - throw new CloudRuntimeException("Unable to create service-template object", ex); - } - } - return tmpl; - } - - @Override - public void update(ModelController controller) { - _tmpl = locateServiceTemplate(controller); - if (_serviceInstance == null) { - _serviceInstance = createServiceInstance(controller); - } - _uuid = _serviceInstance.getUuid(); - if (_policy == null) { - _policy = setServicePolicy(controller); - } - } - - @Override - public boolean verify(ModelController controller) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean compare(ModelController controller, ModelObject current) { - // TODO Auto-generated method stub - return true; - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java deleted file mode 100644 index 87d57b29afff..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModel.java +++ /dev/null @@ -1,263 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; - -import org.apache.cloudstack.network.contrail.management.ContrailManager; - -import com.cloud.exception.InternalErrorException; -import com.cloud.network.Network; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.types.MacAddressesType; -import net.juniper.contrail.api.types.VirtualMachineInterface; -import net.juniper.contrail.api.types.VirtualMachineInterfacePropertiesType; - -public class VMInterfaceModel extends ModelObjectBase { - - private String _uuid; - - /** - * properties - */ - private String _vmName; - private int _deviceId; - private boolean _netActive; - private boolean _nicActive; - private String _serviceTag; - private String _networkId; - private String _macAddress; - - /** - * cached objects - */ - private VirtualMachineModel _vmModel; - private VirtualNetworkModel _vnModel; - private VirtualMachineInterface _vmi; - - public VMInterfaceModel(String uuid) { - _uuid = uuid; - } - - public void addToVirtualMachine(VirtualMachineModel vmModel) { - _vmModel = vmModel; - if (vmModel != null) { - vmModel.addSuccessor(this); - } - } - - public void addToVirtualNetwork(VirtualNetworkModel vnModel) { - _vnModel = vnModel; - if (vnModel != null) { - vnModel.addSuccessor(this); - } - } - - public void build(ModelController controller, VMInstanceVO instance, NicVO nic) throws IOException { - setProperties(controller, instance, nic); - - InstanceIpModel ipModel = getInstanceIp(); - String ipAddress = nic.getIPv4Address(); - if (ipAddress != null) { - if (ipModel == null) { - ipModel = new InstanceIpModel(_vmName, _deviceId); - ipModel.addToVMInterface(this); - } - ipModel.setAddress(ipAddress); - } else if (ipModel != null) { - removeSuccessor(ipModel); - } - - _macAddress = nic.getMacAddress(); - } - - @Override - public int compareTo(ModelObject o) { - VMInterfaceModel other; - try { - other = (VMInterfaceModel)o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return VMInterfaceModel.class.getName().compareTo(clsname); - } - return _uuid.compareTo(other._uuid); - } - - @Override - public void delete(ModelController controller) throws IOException { - for (ModelObject successor : successors()) { - successor.delete(controller); - } - - ApiConnector api = controller.getApiAccessor(); - api.delete(VirtualMachineInterface.class, _uuid); - } - - @Override - public void destroy(ModelController controller) throws IOException { - delete(controller); - - for (ModelObject successor : successors()) { - successor.destroy(controller); - } - clearSuccessors(); - } - - public InstanceIpModel getInstanceIp() { - for (ModelObject successor : successors()) { - if (successor.getClass() == InstanceIpModel.class) { - return (InstanceIpModel)successor; - } - } - return null; - } - - public String getNetworkUuid() { - return _networkId; - } - - public VirtualNetworkModel getVirtualNetworkModel() { - return _vnModel; - } - - public String getUuid() { - return _uuid; - } - - public VirtualMachineInterface getVMInterface() { - return _vmi; - } - - public void setProperties(ModelController controller, VMInstanceVO instance, NicVO nic) throws IOException { - _vmName = instance.getInstanceName(); - _deviceId = nic.getDeviceId(); - Network network = controller.getNetworkDao().findById(nic.getNetworkId()); - - switch (nic.getState()) { - case Allocated: - case Reserved: - _nicActive = true; - break; - default: - _nicActive = false; - break; - } - - switch (network.getState()) { - case Implemented: - case Setup: - _netActive = true; - break; - default: - _netActive = false; - break; - } - assert _vnModel != null; - _networkId = _vnModel.getUuid(); - } - - public void setActive() { - _nicActive = true; - } - - void setServiceTag(String tag) { - _serviceTag = tag; - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - if (!_netActive || !_nicActive) { - logger.debug("vm interface update, _netActive: " + _netActive + ", _nicActive: " + _nicActive); - delete(controller); - return; - } - if (_vmModel == null) { - throw new InternalErrorException("virtual-machine not set on VMI: " + _uuid); - } - if (_vnModel == null) { - throw new InternalErrorException("virtual-network not set on VMI: " + _uuid); - } - ContrailManager manager = controller.getManager(); - ApiConnector api = controller.getApiAccessor(); - - VirtualMachineInterface vmi = (VirtualMachineInterface)api.findById(VirtualMachineInterface.class, _uuid); - boolean create = false; - if (vmi == null) { - create = true; - vmi = new VirtualMachineInterface(); - vmi.setParent(_vmModel.getVirtualMachine()); - vmi.setName(manager.getVifNameByVmName(_vmModel.getInstanceName(), _deviceId)); - vmi.setUuid(_uuid); - vmi.setVirtualNetwork(_vnModel.getVirtualNetwork()); - } else { - // Do not try to update VMI to routing-instance references. These are managed by schema-transformer. - vmi.clearRoutingInstance(); - } - _vmi = vmi; - if (_macAddress != null) { - MacAddressesType mac = new MacAddressesType(); - mac.addMacAddress(_macAddress); - vmi.setMacAddresses(mac); - } - - if (_serviceTag != null) { - vmi.setProperties(new VirtualMachineInterfacePropertiesType(_serviceTag, null)); - } - - if (create) { - if (!api.create(vmi)) { - throw new InternalErrorException("Unable to create virtual-machine-interface " + _uuid); - } - } else { - if (!api.update(vmi)) { - throw new InternalErrorException("Unable to update virtual-machine-interface " + _uuid); - } - } - - api.read(vmi); - - int ipCount = 0; - for (ModelObject successor : successors()) { - if (successor.getClass() == InstanceIpModel.class) { - ipCount++; - } - successor.update(controller); - } - // TODO: if there are no instance-ip successors present and we have an instance-ip object reference - // delete the object. - if (ipCount == 0) { - logger.warn("virtual-machine-interface " + _uuid + " has no instance-ip"); - } - } - - @Override - public boolean verify(ModelController controller) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean compare(ModelController controller, ModelObject current) { - // TODO Auto-generated method stub - return true; - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java deleted file mode 100644 index 7a1833302d69..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModel.java +++ /dev/null @@ -1,388 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.types.Project; -import net.juniper.contrail.api.types.ServiceInstance; -import net.juniper.contrail.api.types.VirtualMachine; - -import org.apache.cloudstack.network.contrail.management.ContrailManager; -import org.apache.commons.lang3.StringUtils; - -import com.cloud.exception.InternalErrorException; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.uservm.UserVm; -import com.cloud.utils.UuidUtils; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.dao.NicDao; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -public class VirtualMachineModel extends ModelObjectBase { - - private final String _uuid; - private long _instanceId; - - /* - * current state for object properties - */ - private boolean _initialized; - private boolean _active; - private String _serviceUuid; - private String _instanceName; - private String _projectId; - - /* - * cached API server objects - */ - private VirtualMachine _vm; - private ServiceInstanceModel _serviceModel; - - public VirtualMachineModel(VMInstanceVO vm, String uuid) { - _uuid = uuid; - if (vm != null) { - _instanceId = vm.getId(); - _instanceName = vm.getInstanceName(); - } - } - - /** - * Resynchronize internal state from the cloudstack DB object. - * @param instance - */ - public void build(ModelController controller, VMInstanceVO instance) { - setProperties(controller, instance); - UserVm userVm = controller.getVmDao().findById(instance.getId()); - if (userVm != null && userVm.getUserData() != null) { - logger.debug(String.format("vm %s user data: %s", instance, userVm.getUserData())); - final Gson json = new Gson(); - Map kvmap = json.fromJson(userVm.getUserData(), new TypeToken>() { - }.getType()); - //Renamed "data" to "serviceUuid" because it's clearer. - String serviceUuid = kvmap.get("service-instance"); - if (serviceUuid != null) { - /* - * UUID.fromString() does not validate an UUID properly. I tried, for example, informing less digits in the UUID, where 12 were expected, - * and the UUID.fromstring() did not thrown the exception as expected. However, if you try UUID.fromString("aaa") it breaks, but if you try - * UUID.fromString("3dd4fa6e-2899-4429-b818-d34fe8df5") it doesn't (the last portion should have 12, instead of 9 digits). - * - * In other fix I added the validate UUID method to the UuidUtil classes. - */ - if (UuidUtils.isUuid(serviceUuid)) { - /* link the object with the service instance */ - buildServiceInstance(controller, serviceUuid); - } else { - // Throw a CloudRuntimeException in case the UUID is not valid. - String message = "Invalid UUID ({0}) given for the service-instance for VM {1}."; - message = MessageFormat.format(message, serviceUuid, instance); - logger.warn(message); - throw new CloudRuntimeException(message); - } - } - } - } - - /** - * Link the virtual machine with the service instance when recovering state from database. - * - * @param controller - * @param serviceUuid - */ - private void buildServiceInstance(ModelController controller, String serviceUuid) { - ContrailManager manager = controller.getManager(); - ApiConnector api = controller.getApiAccessor(); - _serviceUuid = serviceUuid; - - ServiceInstance siObj; - try { - siObj = (ServiceInstance) api.findById(ServiceInstance.class, serviceUuid); - } catch (IOException ex) { - logger.warn("service-instance read", ex); - throw new CloudRuntimeException("Unable to read service-instance object", ex); - } - - ServiceInstanceModel siModel; - String fqn = StringUtils.join(siObj.getQualifiedName(), ':'); - siModel = manager.getDatabase().lookupServiceInstance(fqn); - if (siModel == null) { - siModel = new ServiceInstanceModel(serviceUuid); - siModel.build(controller, siObj); - manager.getDatabase().getServiceInstances().add(siModel); - } - /* - * The code that was under the ELSE was never executed and due to that has been removed. - * Also, in the case siObj was null, it was going pass it as parameter to the build() method in the - * siModel object. - */ - _serviceModel = siModel; - } - - @Override - public int compareTo(ModelObject o) { - VirtualMachineModel other; - try { - other = (VirtualMachineModel)o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return VirtualMachineModel.class.getName().compareTo(clsname); - } - return _uuid.compareTo(other._uuid); - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - for (ModelObject successor : successors()) { - successor.delete(controller); - } - - try { - api.delete(VirtualMachine.class, _uuid); - } catch (IOException ex) { - logger.warn("virtual-machine delete", ex); - } - - if (_serviceModel != null) { - _serviceModel.delete(controller); - } - } - - @Override - public void destroy(ModelController controller) throws IOException { - delete(controller); - - for (ModelObject successor : successors()) { - successor.destroy(controller); - } - - clearSuccessors(); - - if (_serviceModel != null) { - _serviceModel.removeSuccessor(this); - _serviceModel.destroy(controller); - ContrailManager manager = controller.getManager(); - manager.getDatabase().getServiceInstances().remove(_serviceModel); - _serviceModel = null; - } - } - - public String getInstanceName() { - return _instanceName; - } - - public String getUuid() { - return _uuid; - } - - public VirtualMachine getVirtualMachine() { - return _vm; - } - - public VMInterfaceModel getVMInterface(String uuid) { - TreeSet tree = successors(); - VMInterfaceModel vmiKey = new VMInterfaceModel(uuid); - VMInterfaceModel current = (VMInterfaceModel)tree.ceiling(vmiKey); - if (current != null && current.getUuid().equals(uuid)) { - return current; - } - return null; - } - - public boolean isActive() { - return _active; - } - - boolean isActiveInstance(VMInstanceVO instance) { - switch (instance.getState()) { - case Migrating: - case Starting: - case Running: - case Shutdown: - case Stopped: - case Stopping: - return true; - - case Destroyed: - case Error: - case Expunging: - return false; - - default: - logger.warn("Unknown VMInstance state " + instance.getState().getDescription()); - } - return true; - } - - /** - * Initialize the object properties based on the DB object. - * Common code between plugin calls and DBSync. - */ - public void setProperties(ModelController controller, VMInstanceVO instance) { - ContrailManager manager = controller.getManager(); - _instanceName = instance.getInstanceName(); - _active = isActiveInstance(instance); - - try { - _projectId = manager.getProjectId(instance.getDomainId(), instance.getAccountId()); - } catch (IOException ex) { - logger.warn("project read", ex); - throw new CloudRuntimeException(ex); - } - _initialized = true; - } - - /** - * Link the virtual machine with a service instance via programmatic API call. - * @throws IOException - */ - public void setServiceInstance(ModelController controller, VMInstanceVO instance, ServiceInstanceModel serviceModel) throws IOException { - _serviceUuid = serviceModel.getUuid(); - _serviceModel = serviceModel; - serviceModel.addSuccessor(this); - setServiceInstanceNics(controller, instance); - } - - private void setServiceInstanceNics(ModelController controller, VMInstanceVO instance) throws IOException { - NicDao nicDao = controller.getNicDao(); - ContrailManager manager = controller.getManager(); - NetworkDao networkDao = controller.getNetworkDao(); - - List nics = nicDao.listByVmId(_instanceId); - for (NicVO nic : nics) { - String tag; - - switch (nic.getDeviceId()) { - case 0: - tag = "management"; - break; - case 1: - tag = "left"; - break; - case 2: - tag = "right"; - break; - default: - tag = null; - } - - VMInterfaceModel vmiModel = getVMInterface(nic.getUuid()); - if (vmiModel == null) { - vmiModel = new VMInterfaceModel(nic.getUuid()); - vmiModel.addToVirtualMachine(this); - NetworkVO network = networkDao.findById(nic.getNetworkId()); - VirtualNetworkModel vnModel = manager.getDatabase().lookupVirtualNetwork(network.getUuid(), manager.getCanonicalName(network), network.getTrafficType()); - assert vnModel != null; - vmiModel.addToVirtualNetwork(vnModel); - } - vmiModel.setProperties(controller, instance, nic); - vmiModel.setServiceTag(tag); - } - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - assert _initialized; - ApiConnector api = controller.getApiAccessor(); - - VirtualMachine vm = _vm; - if (vm == null) { - _vm = vm = (VirtualMachine)api.findById(VirtualMachine.class, _uuid); - if (vm == null) { - vm = new VirtualMachine(); - if (_projectId != null) { - Project project; - try { - project = (Project)api.findById(Project.class, _projectId); - } catch (IOException ex) { - logger.debug("project read", ex); - throw new CloudRuntimeException("Failed to read project", ex); - } - vm.setParent(project); - } - vm.setName(_instanceName); - vm.setUuid(_uuid); - } - } - - if (_serviceModel != null) { - vm.setServiceInstance(_serviceModel.getServiceInstance()); - } - - if (_vm == null) { - try { - api.create(vm); - } catch (Exception ex) { - logger.debug("virtual-machine create", ex); - throw new CloudRuntimeException("Failed to create virtual-machine", ex); - } - _vm = vm; - } else { - try { - api.update(vm); - } catch (IOException ex) { - logger.warn("virtual-machine update", ex); - throw new CloudRuntimeException("Unable to update virtual-machine object", ex); - } - } - - for (ModelObject successor : successors()) { - successor.update(controller); - } - } - - @Override - public boolean verify(ModelController controller) { - assert _initialized : "initialized is false"; - assert _uuid != null : "uuid is not set"; - - ApiConnector api = controller.getApiAccessor(); - - try { - _vm = (VirtualMachine) api.findById(VirtualMachine.class, _uuid); - } catch (IOException e) { - logger.error("virtual-machine verify", e); - } - - if (_vm == null) { - return false; - } - - for (ModelObject successor: successors()) { - if (!successor.verify(controller)) { - return false; - } - } - return true; - } - - @Override - public boolean compare(ModelController controller, ModelObject current) { - // TODO Auto-generated method stub - return true; - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java b/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java deleted file mode 100644 index c27c57516e0c..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModel.java +++ /dev/null @@ -1,584 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.NetworkIpam; -import net.juniper.contrail.api.types.Project; -import net.juniper.contrail.api.types.SubnetType; -import net.juniper.contrail.api.types.VirtualNetwork; -import net.juniper.contrail.api.types.VirtualNetworkPolicyType; -import net.juniper.contrail.api.types.VnSubnetsType; - -import org.apache.cloudstack.network.contrail.management.ContrailManager; - -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.VlanDao; -import com.cloud.exception.InternalErrorException; -import com.cloud.network.Network; -import com.cloud.network.Networks.TrafficType; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; - -public class VirtualNetworkModel extends ModelObjectBase { - - private String _uuid; - private long _id; - private final TrafficType _trafficType; - - /* - * current state for object properties - */ - private boolean _initialized; - private String _name; - private String _prefix; - private String _gateway; - private String _projectId; - - /* - * cached API server objects - */ - private VirtualNetwork _vn; - private NetworkIpam _ipam; - - private FloatingIpPoolModel _fipPoolModel; - private NetworkPolicyModel _policyModel; - - public VirtualNetworkModel(Network network, String uuid, String name, TrafficType trafficType) { - _uuid = uuid; - _name = name; - _trafficType = trafficType; - if (network != null) { - _id = network.getId(); - } - - if (isDynamicNetwork()) { - assert _uuid != null : "uuid is must for dynamic networks"; - } else { - assert _name != null : "name is must for static networks"; - } - } - - /* - * Resynchronize internal state from the cloudstack DB object. - */ - public void build(ModelController controller, Network network) { - setProperties(controller, network); - } - - /** - * Determine whether this network is dynamically created by cloudstack or is created by default by the contrail - * API server. - * - * @return - */ - boolean isDynamicNetwork() { - return (_trafficType == TrafficType.Guest) || (_trafficType == TrafficType.Public); - } - - @Override - public int compareTo(ModelObject o) { - VirtualNetworkModel other; - try { - other = (VirtualNetworkModel)o; - } catch (ClassCastException ex) { - String clsname = o.getClass().getName(); - return VirtualNetworkModel.class.getName().compareTo(clsname); - } - - if (!isDynamicNetwork()) { - if (!other.isDynamicNetwork()) { - // name is not unique since both management and storage networks may map to ip-fabric - int cmp = _name.compareTo(other.getName()); - if (cmp != 0) { - return cmp; - } - return _trafficType.compareTo(other._trafficType); - } - return -1; - } else if (!other.isDynamicNetwork()) { - return 1; - } - - return _uuid.compareTo(other._uuid); - } - - @Override - public void delete(ModelController controller) throws IOException { - ApiConnector api = controller.getApiAccessor(); - for (ModelObject successor : successors()) { - successor.delete(controller); - } - - if (_policyModel != null) { - _policyModel.removeSuccessor(this); - } - - try { - api.delete(VirtualNetwork.class, _uuid); - } catch (IOException ex) { - logger.warn("virtual-network delete", ex); - } - } - - @Override - public void destroy(ModelController controller) throws IOException { - delete(controller); - - for (ModelObject successor : successors()) { - successor.destroy(controller); - } - clearSuccessors(); - } - - public String getName() { - return _name; - } - - public String getUuid() { - return _uuid; - } - - public VirtualNetwork getVirtualNetwork() { - return _vn; - } - - /** - * Initialize the object properties based on the DB object. - * Common code between plugin calls and DBSync. - */ - public void setProperties(ModelController controller, Network network) { - ContrailManager manager = controller.getManager(); - _name = manager.getCanonicalName(network); - _prefix = network.getCidr(); - _gateway = network.getGateway(); - - // For non-cloudstack managed network, find the uuid at this stage. - if (!isDynamicNetwork()) { - try { - _uuid = manager.findVirtualNetworkId(network); - } catch (IOException ex) { - logger.warn("Unable to read virtual-network", ex); - } - } - - _id = network.getId(); - - try { - _projectId = manager.getProjectId(network.getDomainId(), network.getAccountId()); - } catch (IOException ex) { - logger.warn("project read", ex); - throw new CloudRuntimeException(ex); - } - - _initialized = true; - } - - @Override - public void update(ModelController controller) throws InternalErrorException, IOException { - - assert _initialized; - - ApiConnector api = controller.getApiAccessor(); - VlanDao vlanDao = controller.getVlanDao(); - VirtualNetwork vn = _vn; - - if (!isDynamicNetwork()) { - _vn = (VirtualNetwork)controller.getApiAccessor().findById(VirtualNetwork.class, _uuid); - return; - } - - assert _uuid != null : "uuid is not set"; - - if (_vn == null) { - vn = _vn = (VirtualNetwork)controller.getApiAccessor().findById(VirtualNetwork.class, _uuid); - if (vn == null) { - vn = new VirtualNetwork(); - if (_projectId != null) { - Project project; - try { - project = (Project)api.findById(Project.class, _projectId); - } catch (IOException ex) { - logger.debug("project read", ex); - throw new CloudRuntimeException("Failed to read project", ex); - } - vn.setParent(project); - } - vn.setName(_name); - vn.setUuid(_uuid); - } - } - - if (_policyModel == null) { - vn.clearNetworkPolicy(); - } else if (!_policyModel.hasPolicyRules()) { - vn.clearNetworkPolicy(); - _policyModel.removeSuccessor(this); - } else { - vn.setNetworkPolicy(_policyModel.getPolicy(), new VirtualNetworkPolicyType( - new VirtualNetworkPolicyType.SequenceType(1, 0), null)); - } - - if (_ipam == null) { - NetworkIpam ipam = null; - try { - String ipam_id = api.findByName(NetworkIpam.class, null, "default-network-ipam"); - if (ipam_id == null) { - logger.debug("could not find default-network-ipam"); - return; - } - ipam = (NetworkIpam)api.findById(NetworkIpam.class, ipam_id); - if (ipam == null) { - logger.debug("could not find NetworkIpam with ipam_id: " + ipam_id); - return; - } - } catch (IOException ex) { - logger.error(ex); - return; - } - _ipam = ipam; - } - - if (_prefix != null) { - VnSubnetsType subnet = new VnSubnetsType(); - String[] addr_pair = _prefix.split("\\/"); - subnet.addIpamSubnets(new SubnetType(addr_pair[0], Integer.parseInt(addr_pair[1])), _gateway); - vn.setNetworkIpam(_ipam, subnet); - } else if (_trafficType == TrafficType.Public) { - vn.clearNetworkIpam(); - /* Subnet information for Public is stored in the vlan table */ - List vlan_list = vlanDao.listVlansByNetworkId(_id); - for (VlanVO vlan : vlan_list) { - String cidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); - int slash = cidr.indexOf('/'); - String ip_addr = cidr.substring(0, slash); - int plen = Integer.parseInt(cidr.substring(slash + 1)); - VnSubnetsType subnet = new VnSubnetsType(); - subnet.addIpamSubnets(new SubnetType(ip_addr, plen), vlan.getVlanGateway()); - vn.addNetworkIpam(_ipam, subnet); - } - } - - if (_vn == null) { - try { - api.create(vn); - } catch (Exception ex) { - logger.debug("virtual-network create", ex); - throw new CloudRuntimeException("Failed to create virtual-network", ex); - } - _vn = vn; - } else { - try { - api.update(vn); - } catch (IOException ex) { - logger.warn("virtual-network update", ex); - throw new CloudRuntimeException("Unable to update virtual-network object", ex); - } - } - - for (ModelObject successor : successors()) { - successor.update(controller); - } - } - - public void read(ModelController controller) { - ApiConnector api = controller.getApiAccessor(); - VlanDao vlanDao = controller.getVlanDao(); - try { - _vn = (VirtualNetwork)api.findById(VirtualNetwork.class, _uuid); - } catch (IOException e) { - e.printStackTrace(); - } - if (_vn == null) { - return; - } - if (_ipam == null) { - NetworkIpam ipam = null; - try { - String ipam_id = api.findByName(NetworkIpam.class, null, "default-network-ipam"); - if (ipam_id == null) { - logger.debug("could not find default-network-ipam"); - return; - } - ipam = (NetworkIpam)api.findById(NetworkIpam.class, ipam_id); - if (ipam == null) { - logger.debug("could not find NetworkIpam with ipam_id: " + ipam_id); - return; - } - } catch (IOException ex) { - logger.error(ex); - return; - } - _ipam = ipam; - } - - if (_prefix != null) { - VnSubnetsType subnet = new VnSubnetsType(); - String[] addr_pair = _prefix.split("\\/"); - subnet.addIpamSubnets(new SubnetType(addr_pair[0], Integer.parseInt(addr_pair[1])), _gateway); - _vn.setNetworkIpam(_ipam, subnet); - } else if (_trafficType == TrafficType.Public) { - _vn.clearNetworkIpam(); - /* Subnet information for Public is stored in the vlan table */ - List vlan_list = vlanDao.listVlansByNetworkId(_id); - for (VlanVO vlan : vlan_list) { - String cidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); - int slash = cidr.indexOf('/'); - String ip_addr = cidr.substring(0, slash); - int plen = Integer.parseInt(cidr.substring(slash + 1)); - VnSubnetsType subnet = new VnSubnetsType(); - subnet.addIpamSubnets(new SubnetType(ip_addr, plen), vlan.getVlanGateway()); - _vn.addNetworkIpam(_ipam, subnet); - } - } - return; - } - - @Override - public boolean verify(ModelController controller) { - assert _initialized : "initialized is false"; - assert _uuid != null : "uuid is not set"; - - ApiConnector api = controller.getApiAccessor(); - VlanDao vlanDao = controller.getVlanDao(); - - try { - _vn = (VirtualNetwork)api.findById(VirtualNetwork.class, _uuid); - } catch (IOException e) { - e.printStackTrace(); - } - - if (_vn == null) { - return false; - } - - if (!isDynamicNetwork()) { - return true; - } - - List dbSubnets = new ArrayList(); - if (_trafficType == TrafficType.Public) { - List vlan_list = vlanDao.listVlansByNetworkId(_id); - for (VlanVO vlan : vlan_list) { - String cidr = NetUtils.ipAndNetMaskToCidr(vlan.getVlanGateway(), vlan.getVlanNetmask()); - dbSubnets.add(vlan.getVlanGateway() + cidr); - } - } else { - dbSubnets.add(_gateway + _prefix); - } - - List> ipamRefs = _vn.getNetworkIpam(); - List vncSubnets = new ArrayList(); - - if (ipamRefs == null && !dbSubnets.isEmpty()) { - return false; - } - - if (ipamRefs != null) { - for (ObjectReference ref : ipamRefs) { - VnSubnetsType vnSubnetType = ref.getAttr(); - if (vnSubnetType != null) { - List subnets = vnSubnetType.getIpamSubnets(); - if (subnets != null && !subnets.isEmpty()) { - VnSubnetsType.IpamSubnetType ipamSubnet = subnets.get(0); - vncSubnets.add(ipamSubnet.getDefaultGateway() + ipamSubnet.getSubnet().getIpPrefix() + "/" + ipamSubnet.getSubnet().getIpPrefixLen()); - } - } - } - } - // unordered, no duplicates hence perform negation operation as set - Set diff = new HashSet(dbSubnets); - diff.removeAll(vncSubnets); - - if (!diff.isEmpty()) { - logger.debug(String.format("Subnets changed, network: [id: %d, uuid: %s, name: %s]; " + - "db: %s, vnc: %s, diff: %s", _id, _uuid, _name, dbSubnets, vncSubnets, diff)); - return false; - } - - List> policyRefs = _vn.getNetworkPolicy(); - if ((policyRefs == null || policyRefs.isEmpty()) && _policyModel != null) { - return false; - } - - if ((policyRefs != null && !policyRefs.isEmpty()) && _policyModel == null) { - return false; - } - - if (policyRefs != null && !policyRefs.isEmpty() && _policyModel != null) { - ObjectReference ref = policyRefs.get(0); - if (!ref.getUuid().equals(_policyModel.getUuid())) { - return false; - } - } - - for (ModelObject successor : successors()) { - if (!successor.verify(controller)) { - return false; - } - } - return true; - } - - @Override - public boolean compare(ModelController controller, ModelObject o) { - VirtualNetworkModel latest; - assert _vn != null : "vnc virtual network current is not initialized"; - - try { - latest = (VirtualNetworkModel)o; - } catch (ClassCastException ex) { - logger.warn("Invalid model object is passed to cast to VirtualNetworkModel"); - return false; - } - - try { - latest.read(controller); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - assert latest._vn != null : "vnc virtual network new is not initialized"; - - List> currentIpamRefs = _vn.getNetworkIpam(); - List> newIpamRefs = latest._vn.getNetworkIpam(); - List currentSubnets = new ArrayList(); - List newSubnets = new ArrayList(); - - if ((currentIpamRefs == null && newIpamRefs != null) || (currentIpamRefs != null && newIpamRefs == null)) { //Check for existence only - logger.debug("ipams differ: current=" + currentIpamRefs + ", new=" + newIpamRefs); - return false; - } - if (currentIpamRefs == null) { - return true; - } - - for (ObjectReference ref : currentIpamRefs) { - VnSubnetsType vnSubnetType = ref.getAttr(); - if (vnSubnetType != null) { - List subnets = vnSubnetType.getIpamSubnets(); - if (subnets != null && !subnets.isEmpty()) { - VnSubnetsType.IpamSubnetType ipamSubnet = subnets.get(0); - currentSubnets.add(ipamSubnet.getDefaultGateway() + ipamSubnet.getSubnet().getIpPrefix() + "/" + ipamSubnet.getSubnet().getIpPrefixLen()); - } - } - } - - for (ObjectReference ref : newIpamRefs) { - VnSubnetsType vnSubnetType = ref.getAttr(); - if (vnSubnetType != null) { - List subnets = vnSubnetType.getIpamSubnets(); - if (subnets != null && !subnets.isEmpty()) { - VnSubnetsType.IpamSubnetType ipamSubnet = subnets.get(0); - newSubnets.add(ipamSubnet.getDefaultGateway() + ipamSubnet.getSubnet().getIpPrefix() + "/" + ipamSubnet.getSubnet().getIpPrefixLen()); - } - } - } - - Set diff = new HashSet(currentSubnets); - diff.removeAll(newSubnets); - - if (!diff.isEmpty()) { - logger.debug(String.format("Subnets differ, network: [id: %d, uuid: %s, name: %s]; db: %s, vnc: %s, diff: %s", _id, _uuid, _name, currentSubnets, newSubnets, diff)); - return false; - } - - List> currentPolicyRefs = _vn.getNetworkPolicy(); - List> latestPolicyRefs = latest._vn.getNetworkPolicy(); - - if (currentPolicyRefs == null && latestPolicyRefs == null) { - return true; - } - - if ((currentPolicyRefs == null && latestPolicyRefs != null) || (currentPolicyRefs != null - && latestPolicyRefs == null)) { - return false; - } - - if ((currentPolicyRefs != null && latestPolicyRefs != null) && (currentPolicyRefs.size() != latestPolicyRefs.size())) { - return false; - } - - if ((currentPolicyRefs != null && latestPolicyRefs != null) && currentPolicyRefs.isEmpty() - && latestPolicyRefs.isEmpty()) { - return true; - } - - //both must be non empty lists - ObjectReference ref1 = null; - - if (currentPolicyRefs != null) { - ref1 = currentPolicyRefs.get(0); - } - - ObjectReference ref2 = null; - - if (latestPolicyRefs != null) { - ref2 = latestPolicyRefs.get(0); - } - - if (ref1 == null && ref2 == null) { - return true; - } - - if ((ref1 != null && ref2 == null) || (ref1 == null && ref2 != null)) { - return false; - } - - if ((ref1 != null && ref2 != null) && ((ref1.getUuid() != null && ref2.getUuid() == null) - || (ref1.getUuid() == null && ref2.getUuid() != null))) { - return false; - } - if ((ref1 != null && ref2 != null) && (ref1.getUuid() == null && ref2.getUuid() == null)) { - return true; - } - if ((ref1 != null && ref2 != null) && !ref1.getUuid().equals(ref2.getUuid())) { - return false; - } - return true; - } - - public FloatingIpPoolModel getFipPoolModel() { - return _fipPoolModel; - } - - public void setFipPoolModel(FloatingIpPoolModel fipPoolModel) { - _fipPoolModel = fipPoolModel; - } - - public NetworkPolicyModel getNetworkPolicyModel() { - return _policyModel; - } - - public void addToNetworkPolicy(NetworkPolicyModel policyModel) { - if (_policyModel != null) { - _policyModel.removeSuccessor(this); - } - _policyModel = policyModel; - if (_policyModel != null) { - _policyModel.addSuccessor(this); - } - } -} diff --git a/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/module.properties b/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/module.properties deleted file mode 100644 index 0c3091dc9309..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=contrail -parent=network diff --git a/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml b/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml deleted file mode 100644 index b95ec82658a3..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/contrail/spring-contrail-context.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/system/spring-contrail-system-context-inheritable.xml b/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/system/spring-contrail-system-context-inheritable.xml deleted file mode 100644 index 6db4ab4072cf..000000000000 --- a/plugins/network-elements/juniper-contrail/src/main/resources/META-INF/cloudstack/system/spring-contrail-system-context-inheritable.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java deleted file mode 100644 index 2cd929479995..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ApiConnectorMockito.java +++ /dev/null @@ -1,125 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import static org.mockito.Mockito.spy; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorMock; -import net.juniper.contrail.api.ApiObjectBase; -import net.juniper.contrail.api.ApiPropertyBase; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.NetworkIpam; - - -import com.google.common.collect.ImmutableMap; - -public class ApiConnectorMockito implements ApiConnector { - - static final Map object_map = new ImmutableMap.Builder().put("network-ipam:default-network-ipam", new NetworkIpam()) - .build(); - private ApiConnectorMock _mock; - private ApiConnector _spy; - - public ApiConnectorMockito(String hostname, int port) { - _mock = new ApiConnectorMock(hostname, port); - _spy = spy(_mock); - } - - public ApiConnector getSpy() { - return _spy; - } - - @Override - public boolean create(ApiObjectBase arg0) throws IOException { - return _spy.create(arg0); - } - - @Override - public void delete(ApiObjectBase arg0) throws IOException { - _spy.delete(arg0); - } - - @Override - public void delete(Class arg0, String arg1) throws IOException { - _spy.delete(arg0, arg1); - } - - @Override - public ApiObjectBase find(Class arg0, ApiObjectBase arg1, String arg2) throws IOException { - StringBuilder msg = new StringBuilder(); - msg.append("find " + arg0.getName()); - if (arg1 != null) { - msg.append(" parent: " + arg1.getName()); - } - msg.append(" name: " + arg2); - - return _mock.find(arg0, arg1, arg2); - } - - @Override - public ApiObjectBase findByFQN(Class arg0, String arg1) throws IOException { - return _mock.findByFQN(arg0, arg1); - } - - @Override - public ApiObjectBase findById(Class arg0, String arg1) throws IOException { - return _mock.findById(arg0, arg1); - } - - @Override - public String findByName(Class arg0, List arg1) throws IOException { - return _mock.findByName(arg0, arg1); - } - - @Override - public String findByName(Class arg0, ApiObjectBase arg1, String arg2) throws IOException { - StringBuilder msg = new StringBuilder(); - msg.append("findByName " + arg0.getName()); - if (arg1 != null) { - msg.append(" parent: " + arg1.getName()); - } - msg.append(" name: " + arg2); - return _mock.findByName(arg0, arg1, arg2); - } - - @Override - public List getObjects(Class arg0, List> arg1) throws IOException { - return _mock.getObjects(arg0, arg1); - } - - @Override - public List list(Class arg0, List arg1) throws IOException { - return _mock.list(arg0, arg1); - } - - @Override - public boolean read(ApiObjectBase arg0) throws IOException { - return _mock.read(arg0); - } - - @Override - public boolean update(ApiObjectBase arg0) throws IOException { - return _spy.update(arg0); - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java deleted file mode 100644 index 9903f0e74901..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/IntegrationTestConfiguration.java +++ /dev/null @@ -1,757 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; - -import javax.inject.Inject; - -import org.apache.cloudstack.framework.config.dao.ConfigurationGroupDaoImpl; -import org.apache.cloudstack.framework.config.dao.ConfigurationSubGroupDaoImpl; -import org.eclipse.jetty.security.IdentityService; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ComponentScan.Filter; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.core.type.filter.TypeFilter; - -import org.apache.cloudstack.acl.APIChecker; -import org.apache.cloudstack.acl.ControlledEntity; -import org.apache.cloudstack.affinity.AffinityGroupService; -import org.apache.cloudstack.affinity.AffinityGroupVO; -import org.apache.cloudstack.affinity.dao.AffinityGroupDao; -import org.apache.cloudstack.affinity.dao.AffinityGroupDaoImpl; -import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDaoImpl; -import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDaoImpl; -import org.apache.cloudstack.auth.UserAuthenticator; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.engine.datacenter.entity.api.db.dao.DcDetailsDaoImpl; -import org.apache.cloudstack.engine.orchestration.NetworkOrchestrator; -import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; -import org.apache.cloudstack.engine.service.api.OrchestrationService; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; -import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; -import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; -import org.apache.cloudstack.framework.config.ConfigDepot; -import org.apache.cloudstack.framework.config.ConfigDepotAdmin; -import org.apache.cloudstack.framework.config.dao.ConfigurationDaoImpl; -import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher; -import org.apache.cloudstack.framework.jobs.dao.AsyncJobDaoImpl; -import org.apache.cloudstack.framework.jobs.dao.AsyncJobJoinMapDaoImpl; -import org.apache.cloudstack.framework.jobs.dao.AsyncJobJournalDaoImpl; -import org.apache.cloudstack.framework.jobs.dao.SyncQueueItemDaoImpl; -import org.apache.cloudstack.framework.jobs.impl.AsyncJobManagerImpl; -import org.apache.cloudstack.framework.jobs.impl.AsyncJobMonitor; -import org.apache.cloudstack.framework.jobs.impl.SyncQueueManager; -import org.apache.cloudstack.lb.dao.ApplicationLoadBalancerRuleDaoImpl; -import org.apache.cloudstack.network.element.InternalLoadBalancerElement; -import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService; -import org.apache.cloudstack.network.lb.InternalLoadBalancerVMManager; -import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; -import org.apache.cloudstack.query.QueryService; -import org.apache.cloudstack.region.PortableIpDaoImpl; -import org.apache.cloudstack.region.PortableIpRangeDaoImpl; -import org.apache.cloudstack.region.RegionManager; -import org.apache.cloudstack.region.dao.RegionDaoImpl; -import org.apache.cloudstack.spring.lifecycle.registry.ExtensionRegistry; -import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager; -import org.apache.cloudstack.storage.image.datastore.ImageStoreProviderManager; -import org.apache.cloudstack.storage.datastore.db.ImageStoreDaoImpl; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl; -import org.apache.cloudstack.storage.image.db.TemplateDataStoreDaoImpl; -import org.apache.cloudstack.usage.UsageService; - -import com.cloud.acl.DomainChecker; -import com.cloud.agent.AgentManager; -import com.cloud.agent.manager.allocator.HostAllocator; -import com.cloud.agent.manager.allocator.PodAllocator; -import com.cloud.alert.AlertManager; -import com.cloud.api.ApiDBUtils; -import com.cloud.api.query.dao.AccountJoinDaoImpl; -import com.cloud.api.query.dao.AffinityGroupJoinDaoImpl; -import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; -import com.cloud.api.query.dao.DataCenterJoinDaoImpl; -import com.cloud.api.query.dao.DiskOfferingJoinDaoImpl; -import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; -import com.cloud.api.query.dao.HostJoinDaoImpl; -import com.cloud.api.query.dao.ImageStoreJoinDaoImpl; -import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl; -import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl; -import com.cloud.api.query.dao.ProjectInvitationJoinDaoImpl; -import com.cloud.api.query.dao.ProjectJoinDaoImpl; -import com.cloud.api.query.dao.ResourceTagJoinDaoImpl; -import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl; -import com.cloud.api.query.dao.ServiceOfferingJoinDaoImpl; -import com.cloud.api.query.dao.StoragePoolJoinDaoImpl; -import com.cloud.api.query.dao.TemplateJoinDaoImpl; -import com.cloud.api.query.dao.UserAccountJoinDaoImpl; -import com.cloud.api.query.dao.UserVmJoinDaoImpl; -import com.cloud.api.query.dao.VolumeJoinDaoImpl; -import com.cloud.capacity.CapacityManager; -import com.cloud.capacity.dao.CapacityDaoImpl; -import com.cloud.cluster.ClusterManager; -import com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl; -import com.cloud.cluster.dao.ManagementServerHostDaoImpl; -import com.cloud.configuration.ConfigurationManagerImpl; -import com.cloud.configuration.dao.ResourceCountDaoImpl; -import com.cloud.configuration.dao.ResourceLimitDaoImpl; -import com.cloud.consoleproxy.ConsoleProxyManager; -import com.cloud.consoleproxy.ConsoleProxyService; -import com.cloud.dc.ClusterDetailsDaoImpl; -import com.cloud.dc.DataCenter; -import com.cloud.dc.dao.AccountVlanMapDaoImpl; -import com.cloud.dc.dao.ClusterDaoImpl; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.DataCenterDaoImpl; -import com.cloud.dc.dao.DataCenterDetailsDaoImpl; -import com.cloud.dc.dao.DataCenterIpAddressDaoImpl; -import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl; -import com.cloud.dc.dao.DataCenterVnetDaoImpl; -import com.cloud.dc.dao.DedicatedResourceDaoImpl; -import com.cloud.dc.dao.HostPodDaoImpl; -import com.cloud.dc.dao.PodVlanDaoImpl; -import com.cloud.dc.dao.PodVlanMapDaoImpl; -import com.cloud.dc.dao.VlanDaoImpl; -import com.cloud.deploy.DeploymentPlanner; -import com.cloud.deploy.DeploymentPlanningManager; -import com.cloud.deploy.dao.PlannerHostReservationDaoImpl; -import com.cloud.domain.dao.DomainDaoImpl; -import com.cloud.domain.dao.DomainDetailsDaoImpl; -import com.cloud.event.dao.EventDaoImpl; -import com.cloud.event.dao.EventJoinDaoImpl; -import com.cloud.event.dao.UsageEventDaoImpl; -import com.cloud.ha.HighAvailabilityManager; -import com.cloud.host.dao.HostDaoImpl; -import com.cloud.host.dao.HostDetailsDaoImpl; -import com.cloud.host.dao.HostTagsDaoImpl; -import com.cloud.hypervisor.HypervisorGuruManagerImpl; -import com.cloud.hypervisor.XenServerGuru; -import com.cloud.hypervisor.dao.HypervisorCapabilitiesDaoImpl; -import com.cloud.network.ExternalDeviceUsageManager; -import com.cloud.network.IpAddress; -import com.cloud.network.IpAddressManagerImpl; -import com.cloud.network.Ipv6AddressManagerImpl; -import com.cloud.network.NetworkServiceImpl; -import com.cloud.network.NetworkUsageService; -import com.cloud.network.StorageNetworkManager; -import com.cloud.network.StorageNetworkService; -import com.cloud.network.as.AutoScaleService; -import com.cloud.network.as.dao.AutoScalePolicyConditionMapDaoImpl; -import com.cloud.network.as.dao.AutoScalePolicyDaoImpl; -import com.cloud.network.as.dao.AutoScaleVmGroupDaoImpl; -import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDaoImpl; -import com.cloud.network.as.dao.AutoScaleVmProfileDaoImpl; -import com.cloud.network.as.dao.ConditionDaoImpl; -import com.cloud.network.as.dao.CounterDaoImpl; -import com.cloud.network.dao.AccountGuestVlanMapDaoImpl; -import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; -import com.cloud.network.dao.FirewallRulesDaoImpl; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressDaoImpl; -import com.cloud.network.dao.LBHealthCheckPolicyDaoImpl; -import com.cloud.network.dao.LBStickinessPolicyDaoImpl; -import com.cloud.network.dao.LoadBalancerDaoImpl; -import com.cloud.network.dao.LoadBalancerVMMapDaoImpl; -import com.cloud.network.dao.NetworkAccountDaoImpl; -import com.cloud.network.dao.NetworkDaoImpl; -import com.cloud.network.dao.NetworkDomainDaoImpl; -import com.cloud.network.dao.NetworkOpDaoImpl; -import com.cloud.network.dao.NetworkRuleConfigDaoImpl; -import com.cloud.network.dao.NetworkServiceMapDaoImpl; -import com.cloud.network.dao.PhysicalNetworkDaoImpl; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDaoImpl; -import com.cloud.network.dao.PhysicalNetworkTrafficTypeDaoImpl; -import com.cloud.network.dao.RemoteAccessVpnDaoImpl; -import com.cloud.network.dao.RouterNetworkDaoImpl; -import com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl; -import com.cloud.network.dao.Site2SiteVpnConnectionDaoImpl; -import com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl; -import com.cloud.network.dao.UserIpv6AddressDaoImpl; -import com.cloud.network.dao.VirtualRouterProviderDaoImpl; -import com.cloud.network.dao.VpnUserDaoImpl; -import com.cloud.network.element.FirewallServiceProvider; -import com.cloud.network.element.NetworkACLServiceProvider; -import com.cloud.network.element.PortForwardingServiceProvider; -import com.cloud.network.element.Site2SiteVpnServiceProvider; -import com.cloud.network.element.VpcProvider; -import com.cloud.network.firewall.FirewallManagerImpl; -import com.cloud.network.lb.LoadBalancingRulesManagerImpl; -import com.cloud.network.router.VpcVirtualNetworkApplianceManagerImpl; -import com.cloud.network.rules.RulesManagerImpl; -import com.cloud.network.rules.dao.PortForwardingRulesDaoImpl; -import com.cloud.network.security.dao.SecurityGroupDaoImpl; -import com.cloud.network.security.dao.SecurityGroupRuleDaoImpl; -import com.cloud.network.security.dao.SecurityGroupRulesDaoImpl; -import com.cloud.network.security.dao.SecurityGroupVMMapDaoImpl; -import com.cloud.network.security.dao.SecurityGroupWorkDaoImpl; -import com.cloud.network.security.dao.VmRulesetLogDaoImpl; -import com.cloud.network.vpc.NetworkACLManagerImpl; -import com.cloud.network.vpc.NetworkACLService; -import com.cloud.network.vpc.VpcManagerImpl; -import com.cloud.network.vpc.dao.NetworkACLDaoImpl; -import com.cloud.network.vpc.dao.NetworkACLItemDaoImpl; -import com.cloud.network.vpc.dao.PrivateIpDaoImpl; -import com.cloud.network.vpc.dao.StaticRouteDaoImpl; -import com.cloud.network.vpc.dao.VpcDaoImpl; -import com.cloud.network.vpc.dao.VpcGatewayDaoImpl; -import com.cloud.network.vpc.dao.VpcOfferingDaoImpl; -import com.cloud.network.vpc.dao.VpcOfferingServiceMapDaoImpl; -import com.cloud.network.vpc.dao.VpcServiceMapDaoImpl; -import com.cloud.network.vpn.RemoteAccessVpnService; -import com.cloud.network.vpn.Site2SiteVpnManager; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.offerings.dao.NetworkOfferingDaoImpl; -import com.cloud.offerings.dao.NetworkOfferingDetailsDaoImpl; -import com.cloud.offerings.dao.NetworkOfferingServiceMapDaoImpl; -import com.cloud.projects.ProjectManagerImpl; -import com.cloud.projects.dao.ProjectAccountDaoImpl; -import com.cloud.projects.dao.ProjectDaoImpl; -import com.cloud.projects.dao.ProjectInvitationDaoImpl; -import com.cloud.region.ha.GlobalLoadBalancingRulesService; -import com.cloud.resource.ResourceManager; -import com.cloud.server.ConfigurationServerImpl; -import com.cloud.server.ManagementServer; -import com.cloud.server.ResourceMetaDataService; -import com.cloud.server.StatsCollector; -import com.cloud.server.TaggedResourceService; -import com.cloud.service.dao.ServiceOfferingDaoImpl; -import com.cloud.service.dao.ServiceOfferingDetailsDaoImpl; -import com.cloud.storage.DataStoreProviderApiService; -import com.cloud.storage.StorageManager; -import com.cloud.storage.VolumeApiService; -import com.cloud.storage.dao.DiskOfferingDaoImpl; -import com.cloud.storage.dao.GuestOSCategoryDaoImpl; -import com.cloud.storage.dao.GuestOSDaoImpl; -import com.cloud.storage.dao.LaunchPermissionDaoImpl; -import com.cloud.storage.dao.SnapshotDaoImpl; -import com.cloud.storage.dao.SnapshotPolicyDaoImpl; -import com.cloud.storage.dao.StoragePoolDetailsDaoImpl; -import com.cloud.storage.dao.StoragePoolHostDaoImpl; -import com.cloud.storage.dao.UploadDaoImpl; -import com.cloud.storage.dao.VMTemplateDaoImpl; -import com.cloud.storage.dao.VMTemplateDetailsDaoImpl; -import com.cloud.storage.dao.VMTemplateZoneDaoImpl; -import com.cloud.storage.dao.VolumeDaoImpl; -import com.cloud.storage.snapshot.SnapshotApiService; -import com.cloud.storage.snapshot.SnapshotManager; -import com.cloud.tags.dao.ResourceTagDao; -import com.cloud.tags.dao.ResourceTagsDaoImpl; -import com.cloud.template.TemplateApiService; -import com.cloud.template.TemplateManager; -import com.cloud.user.Account; -import com.cloud.user.AccountDetailsDaoImpl; -import com.cloud.user.DomainManagerImpl; -import com.cloud.user.ResourceLimitService; -import com.cloud.user.User; -import com.cloud.user.dao.AccountDao; -import com.cloud.user.dao.AccountDaoImpl; -import com.cloud.user.dao.SSHKeyPairDaoImpl; -import com.cloud.user.dao.UserDao; -import com.cloud.user.dao.UserDaoImpl; -import com.cloud.user.dao.UserStatisticsDaoImpl; -import com.cloud.user.dao.UserStatsLogDaoImpl; -import com.cloud.user.dao.VmDiskStatisticsDaoImpl; -import com.cloud.utils.db.EntityManager; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackNoReturn; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.vm.ItWorkDaoImpl; -import com.cloud.vm.UserVmManagerImpl; -import com.cloud.vm.VirtualMachineManagerImpl; -import com.cloud.vm.dao.ConsoleProxyDaoImpl; -import com.cloud.vm.dao.DomainRouterDaoImpl; -import com.cloud.vm.dao.InstanceGroupDaoImpl; -import com.cloud.vm.dao.InstanceGroupVMMapDaoImpl; -import com.cloud.vm.dao.NicDaoImpl; -import com.cloud.vm.dao.NicIpAliasDaoImpl; -import com.cloud.vm.dao.NicSecondaryIpDaoImpl; -import com.cloud.vm.dao.SecondaryStorageVmDaoImpl; -import com.cloud.vm.dao.UserVmCloneSettingDaoImpl; -import com.cloud.vm.dao.UserVmDaoImpl; -import com.cloud.vm.dao.VMInstanceDetailsDaoImpl; -import com.cloud.vm.dao.VMInstanceDaoImpl; -import com.cloud.vm.snapshot.VMSnapshotManager; -import com.cloud.vm.snapshot.dao.VMSnapshotDaoImpl; - -@ComponentScan(basePackageClasses = {AccountDaoImpl.class, AccountDetailsDaoImpl.class, AccountGuestVlanMapDaoImpl.class, AccountJoinDaoImpl.class, - AccountVlanMapDaoImpl.class, AffinityGroupDaoImpl.class, AffinityGroupDomainMapDaoImpl.class, AffinityGroupJoinDaoImpl.class, AffinityGroupVMMapDaoImpl.class, - ApiDBUtils.class, ApplicationLoadBalancerRuleDaoImpl.class, AsyncJobDaoImpl.class, AsyncJobJoinDaoImpl.class, AsyncJobJoinMapDaoImpl.class, - AsyncJobJournalDaoImpl.class, AsyncJobManagerImpl.class, AutoScalePolicyConditionMapDaoImpl.class, AutoScalePolicyDaoImpl.class, AutoScaleVmGroupDaoImpl.class, - AutoScaleVmGroupPolicyMapDaoImpl.class, AutoScaleVmProfileDaoImpl.class, CapacityDaoImpl.class, ClusterDaoImpl.class, ClusterDetailsDaoImpl.class, - ConditionDaoImpl.class, ConfigurationDaoImpl.class, ConfigurationGroupDaoImpl.class, ConfigurationSubGroupDaoImpl.class, ConfigurationManagerImpl.class, ConfigurationServerImpl.class, - ConsoleProxyDaoImpl.class, ContrailElementImpl.class, ContrailGuru.class, ContrailManagerImpl.class, CounterDaoImpl.class, DataCenterDaoImpl.class, DataCenterDetailsDaoImpl.class, - DataCenterIpAddressDaoImpl.class, DataCenterJoinDaoImpl.class, DataCenterLinkLocalIpAddressDaoImpl.class, DataCenterVnetDaoImpl.class, DcDetailsDaoImpl.class, DedicatedResourceDaoImpl.class, - DiskOfferingDaoImpl.class, DiskOfferingJoinDaoImpl.class, DomainDaoImpl.class, DomainDetailsDaoImpl.class, DomainManagerImpl.class, DomainRouterDaoImpl.class, DomainRouterJoinDaoImpl.class, - EventDaoImpl.class, EventJoinDaoImpl.class, EventUtils.class, ExtensionRegistry.class, FirewallManagerImpl.class, FirewallRulesCidrsDaoImpl.class, - FirewallRulesDaoImpl.class, GuestOSCategoryDaoImpl.class, GuestOSDaoImpl.class, HostDaoImpl.class, HostDetailsDaoImpl.class, HostJoinDaoImpl.class, - HostPodDaoImpl.class, HostTagsDaoImpl.class, HostTransferMapDaoImpl.class, HypervisorCapabilitiesDaoImpl.class, HypervisorGuruManagerImpl.class, - ImageStoreDaoImpl.class, ImageStoreJoinDaoImpl.class, InstanceGroupDaoImpl.class, InstanceGroupJoinDaoImpl.class, - InstanceGroupVMMapDaoImpl.class, InternalLoadBalancerElement.class, IPAddressDaoImpl.class, IpAddressManagerImpl.class, Ipv6AddressManagerImpl.class, ItWorkDaoImpl.class, LBHealthCheckPolicyDaoImpl.class, - LBStickinessPolicyDaoImpl.class, LaunchPermissionDaoImpl.class, LoadBalancerDaoImpl.class, LoadBalancerVMMapDaoImpl.class, LoadBalancingRulesManagerImpl.class, - ManagementServerHostDaoImpl.class, MockAccountManager.class, NetworkACLDaoImpl.class, NetworkACLItemDaoImpl.class, NetworkACLManagerImpl.class, - NetworkAccountDaoImpl.class, NetworkDaoImpl.class, NetworkDomainDaoImpl.class, NetworkOfferingDaoImpl.class, - NetworkOfferingDetailsDaoImpl.class, NetworkOfferingServiceMapDaoImpl.class, NetworkOpDaoImpl.class, NetworkOrchestrator.class, NetworkRuleConfigDaoImpl.class, NetworkServiceImpl.class, - NetworkServiceMapDaoImpl.class, NicDaoImpl.class, NicIpAliasDaoImpl.class, NicSecondaryIpDaoImpl.class, PhysicalNetworkDaoImpl.class, PhysicalNetworkServiceProviderDaoImpl.class, - PhysicalNetworkTrafficTypeDaoImpl.class, PlannerHostReservationDaoImpl.class, PodVlanDaoImpl.class, PodVlanMapDaoImpl.class, PortForwardingRulesDaoImpl.class, - PortableIpDaoImpl.class, PortableIpRangeDaoImpl.class, PrimaryDataStoreDaoImpl.class, PrivateIpDaoImpl.class, ProjectAccountDaoImpl.class, - ProjectAccountJoinDaoImpl.class, ProjectInvitationDaoImpl.class, ProjectDaoImpl.class, ProjectInvitationJoinDaoImpl.class, ProjectJoinDaoImpl.class, - ProjectManagerImpl.class, RegionDaoImpl.class, RemoteAccessVpnDaoImpl.class, ResourceCountDaoImpl.class, ResourceLimitDaoImpl.class, ResourceTagDao.class, - ResourceTagJoinDaoImpl.class, ResourceTagsDaoImpl.class, RouterNetworkDaoImpl.class, RulesManagerImpl.class, SSHKeyPairDaoImpl.class, - SecondaryStorageVmDaoImpl.class, SecurityGroupDaoImpl.class, SecurityGroupJoinDaoImpl.class, SecurityGroupRuleDaoImpl.class, SecurityGroupRulesDaoImpl.class, - SecurityGroupVMMapDaoImpl.class, SecurityGroupWorkDaoImpl.class, ServerEventHandlerImpl.class, ServiceOfferingDaoImpl.class, ServiceOfferingDetailsDaoImpl.class, - ServiceOfferingJoinDaoImpl.class, Site2SiteCustomerGatewayDaoImpl.class, Site2SiteVpnConnectionDaoImpl.class, Site2SiteVpnGatewayDaoImpl.class, - SnapshotDaoImpl.class, SnapshotPolicyDaoImpl.class, StaticRouteDaoImpl.class, StatsCollector.class, StoragePoolDetailsDaoImpl.class, StoragePoolHostDaoImpl.class, - StoragePoolJoinDaoImpl.class, SyncQueueItemDaoImpl.class, TemplateDataStoreDaoImpl.class, TemplateJoinDaoImpl.class, UploadDaoImpl.class, UsageEventDaoImpl.class, - UserAccountJoinDaoImpl.class, UserDaoImpl.class, UserIpv6AddressDaoImpl.class, UserStatisticsDaoImpl.class, UserStatsLogDaoImpl.class, - UserVmCloneSettingDaoImpl.class, UserVmDaoImpl.class, VMInstanceDetailsDaoImpl.class, UserVmJoinDaoImpl.class, UserVmManagerImpl.class, VMInstanceDaoImpl.class, VMSnapshotDaoImpl.class, - VMTemplateDaoImpl.class, VMTemplateDetailsDaoImpl.class, VMTemplateZoneDaoImpl.class, VirtualMachineManagerImpl.class, VirtualRouterProviderDaoImpl.class, - VlanDaoImpl.class, VmDiskStatisticsDaoImpl.class, VmRulesetLogDaoImpl.class, VolumeDaoImpl.class, VolumeJoinDaoImpl.class, VpcDaoImpl.class, - VpcGatewayDaoImpl.class, VpcManagerImpl.class, VpcOfferingDaoImpl.class, VpcOfferingServiceMapDaoImpl.class, VpcServiceMapDaoImpl.class, - VpcVirtualNetworkApplianceManagerImpl.class, VpnUserDaoImpl.class, XenServerGuru.class}, includeFilters = {@Filter(value = IntegrationTestConfiguration.ComponentFilter.class, - type = FilterType.CUSTOM)}, useDefaultFilters = false) -@Configuration -public class IntegrationTestConfiguration { - public static class ComponentFilter implements TypeFilter { - @Override - public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException { - String clsname = mdr.getClassMetadata().getClassName(); - ComponentScan cs = IntegrationTestConfiguration.class.getAnnotation(ComponentScan.class); - return includedInBasePackageClasses(clsname, cs); - } - } - - public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs) { - Class clazzToCheck; - try { - clazzToCheck = Class.forName(clazzName); - } catch (ClassNotFoundException e) { - System.out.println("Unable to find " + clazzName); - return false; - } - Class[] clazzes = cs.basePackageClasses(); - for (Class clazz : clazzes) { - if (clazzToCheck.isAssignableFrom(clazz)) { - return true; - } - } - return false; - } - - @Inject - AffinityGroupDao _affinityGroupDao; - @Inject - AccountDao _accountDao; - @Inject - UserDao _userDao; - @Inject - NetworkOfferingDao _networkOfferingDao; - @Inject - DataCenterDao _zoneDao; - @Inject - IPAddressDao _ipAddressDao; - - @Bean - public AffinityGroupService affinityGroupService() { - AffinityGroupService mock = Mockito.mock(AffinityGroupService.class); - try { - final AffinityGroupVO gmock = new AffinityGroupVO("grp1", "grp-type", "affinity group", 1, Account.ACCOUNT_ID_SYSTEM, ControlledEntity.ACLType.Account); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - _affinityGroupDao.persist(gmock); - } - }); - Mockito.when( - mock.createAffinityGroup(ArgumentMatchers.any(String.class), ArgumentMatchers.any(Long.class), ArgumentMatchers.any(Long.class), ArgumentMatchers.any(String.class), ArgumentMatchers.any(String.class), - ArgumentMatchers.any(String.class))).thenReturn(gmock); - } catch (Exception e) { - e.printStackTrace(); - } - return mock; - } - - @Bean - public AgentManager agentManager() { - return Mockito.mock(AgentManager.class); - } - - @Bean - public AlertManager alertManager() { - return Mockito.mock(AlertManager.class); - } - - @Bean - public APIChecker apiChecker() { - return Mockito.mock(APIChecker.class); - } - - @Bean - public AsyncJobDispatcher asyncJobDispatcher() { - return Mockito.mock(AsyncJobDispatcher.class); - } - - @Bean - public AsyncJobMonitor asyncJobMonitor() { - return Mockito.mock(AsyncJobMonitor.class); - } - - @Bean - public AutoScaleService autoScaleService() { - return Mockito.mock(AutoScaleService.class); - } - - @Bean - public CapacityManager capacityManager() { - return Mockito.mock(CapacityManager.class); - } - - @Bean - public ClusterManager clusterManager() { - return Mockito.mock(ClusterManager.class); - } - - @Bean - public ConfigDepot configDepot() { - return Mockito.mock(ConfigDepot.class); - } - - @Bean - public ConfigDepotAdmin configDepotAdmin() { - return Mockito.mock(ConfigDepotAdmin.class); - } - - @Bean - public ConsoleProxyManager consoleProxyManager() { - return Mockito.mock(ConsoleProxyManager.class); - } - - @Bean - public ConsoleProxyService consoleProxyService() { - return Mockito.mock(ConsoleProxyService.class); - } - - @Bean - public DataStoreManager dataStoreManager() { - return Mockito.mock(DataStoreManager.class); - } - - @Bean - public DataStoreProviderApiService dataStoreProviderApiService() { - return Mockito.mock(DataStoreProviderApiService.class); - } - - @Bean - public DeploymentPlanner deploymentPlanner() { - return Mockito.mock(DeploymentPlanner.class); - } - - @Bean - public DeploymentPlanningManager deploymentPlanningManager() { - return Mockito.mock(DeploymentPlanningManager.class); - } - - @Bean - public DomainChecker domainChecker() { - DomainChecker mock = Mockito.mock(DomainChecker.class); - try { - Mockito.when(mock.checkAccess(ArgumentMatchers.any(Account.class), ArgumentMatchers.any(DataCenter.class))).thenReturn(true); - } catch (Exception e) { - e.printStackTrace(); - } - return mock; - } - - @Bean - public EndPointSelector endPointSelector() { - return Mockito.mock(EndPointSelector.class); - } - - @Bean - public EntityManager entityManager() { - EntityManager mock = Mockito.mock(EntityManager.class); - try { - Mockito.when(mock.findById(ArgumentMatchers.same(Account.class), ArgumentMatchers.anyLong())).thenReturn(_accountDao.findById(Account.ACCOUNT_ID_SYSTEM)); - Mockito.when(mock.findById(ArgumentMatchers.same(User.class), ArgumentMatchers.anyLong())).thenReturn(_userDao.findById(User.UID_SYSTEM)); - Mockito.when(mock.findById(ArgumentMatchers.same(NetworkOffering.class), ArgumentMatchers.any(Long.class))).thenAnswer(new Answer() { - @Override - public NetworkOffering answer(final InvocationOnMock invocation) throws Throwable { - Long id = (Long)invocation.getArguments()[1]; - return _networkOfferingDao.findById(id); - } - }); - Mockito.when(mock.findById(ArgumentMatchers.same(IpAddress.class), ArgumentMatchers.any(Long.class))).thenAnswer(new Answer() { - @Override - public IpAddress answer(final InvocationOnMock invocation) throws Throwable { - Long id = (Long)invocation.getArguments()[1]; - return _ipAddressDao.findById(id); - } - }); - Mockito.when(mock.findById(ArgumentMatchers.same(DataCenter.class), ArgumentMatchers.any(Long.class))).thenAnswer(new Answer() { - @Override - public DataCenter answer(final InvocationOnMock invocation) throws Throwable { - Long id = (Long)invocation.getArguments()[1]; - return _zoneDao.findById(id); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - CallContext.init(mock); - return mock; - } - - @Bean - public ExternalDeviceUsageManager externalDeviceUsageManager() { - return Mockito.mock(ExternalDeviceUsageManager.class); - } - - @Bean - public GlobalLoadBalancingRulesService globalLoadBalancingRulesService() { - return Mockito.mock(GlobalLoadBalancingRulesService.class); - } - - @Bean - public HighAvailabilityManager highAvailabilityManager() { - return Mockito.mock(HighAvailabilityManager.class); - } - - @Bean - public HostAllocator hostAllocator() { - return Mockito.mock(HostAllocator.class); - } - - @Bean - public IdentityService identityService() { - return Mockito.mock(IdentityService.class); - } - - @Bean - public InternalLoadBalancerVMManager internalLoadBalancerVMManager() { - return Mockito.mock(InternalLoadBalancerVMManager.class); - } - - @Bean - public InternalLoadBalancerVMService internalLoadBalancerVMService() { - return Mockito.mock(InternalLoadBalancerVMService.class); - } - - @Bean - public ApplicationLoadBalancerService applicationLoadBalancerService() { - return Mockito.mock(ApplicationLoadBalancerService.class); - } - - @Bean - public ManagementServer managementServer() { - return Mockito.mock(ManagementServer.class); - } - - @Bean - public NetworkACLService networkACLService() { - return Mockito.mock(NetworkACLService.class); - } - - @Bean - public NetworkUsageService networkUsageService() { - return Mockito.mock(NetworkUsageService.class); - } - - @Bean - public OrchestrationService orchSrvc() { - return Mockito.mock(OrchestrationService.class); - } - - @Bean - public PodAllocator podAllocator() { - return Mockito.mock(PodAllocator.class); - } - - @Bean - public QueryService queryService() { - return Mockito.mock(QueryService.class); - } - - @Bean - public RegionManager regionManager() { - return Mockito.mock(RegionManager.class); - } - - @Bean - public RemoteAccessVpnService remoteAccessVpnService() { - return Mockito.mock(RemoteAccessVpnService.class); - } - - @Bean - public ResourceLimitService resourceLimitService() { - return Mockito.mock(ResourceLimitService.class); - } - - @Bean - public ResourceManager resourceManager() { - return Mockito.mock(ResourceManager.class); - } - - @Bean - public ResourceMetaDataService resourceMetaDataService() { - return Mockito.mock(ResourceMetaDataService.class); - } - - @Bean - public Site2SiteVpnManager site2SiteVpnManager() { - return Mockito.mock(Site2SiteVpnManager.class); - } - - @Bean - public Site2SiteVpnServiceProvider site2SiteVpnServiceProvider() { - return Mockito.mock(Site2SiteVpnServiceProvider.class); - } - - @Bean - public SnapshotApiService snapshotApiService() { - return Mockito.mock(SnapshotApiService.class); - } - - @Bean - public SnapshotManager snapshotManager() { - return Mockito.mock(SnapshotManager.class); - } - - @Bean - public StorageManager storageManager() { - return Mockito.mock(StorageManager.class); - } - - @Bean - public StorageNetworkManager storageNetworkManager() { - return Mockito.mock(StorageNetworkManager.class); - } - - @Bean - public StorageNetworkService storageNetworkService() { - return Mockito.mock(StorageNetworkService.class); - } - - @Bean - public StoragePoolAllocator storagePoolAllocator() { - return Mockito.mock(StoragePoolAllocator.class); - } - - @Bean - public SyncQueueManager syncQueueManager() { - return Mockito.mock(SyncQueueManager.class); - } - - @Bean - public TaggedResourceService taggedResourceService() { - return Mockito.mock(TaggedResourceService.class); - } - - @Bean - public TemplateDataFactory templateDataFactory() { - return Mockito.mock(TemplateDataFactory.class); - } - - @Bean - public TemplateApiService templateApiService() { - return Mockito.mock(TemplateApiService.class); - } - - @Bean - public TemplateManager templateManager() { - return Mockito.mock(TemplateManager.class); - } - - @Bean - public TemplateService templateService() { - return Mockito.mock(TemplateService.class); - } - - @Bean - public UsageService usageService() { - return Mockito.mock(UsageService.class); - } - - @Bean - public UserAuthenticator userAuthenticator() { - return Mockito.mock(UserAuthenticator.class); - } - - @Bean - public VMSnapshotManager vMSnapshotManager() { - return Mockito.mock(VMSnapshotManager.class); - } - - @Bean - public VolumeApiService volumeApiService() { - return Mockito.mock(VolumeApiService.class); - } - - @Bean - public VolumeDataFactory volumeDataFactory() { - return Mockito.mock(VolumeDataFactory.class); - } - - @Bean - public VolumeOrchestrationService volumeOrchestrationService() { - return Mockito.mock(VolumeOrchestrationService.class); - } - @Bean - public FirewallServiceProvider firewallServiceProvider() { - return Mockito.mock(FirewallServiceProvider.class); - } - @Bean - public PortForwardingServiceProvider portForwardingServiceProvider() { - return Mockito.mock(PortForwardingServiceProvider.class); - } - @Bean - public NetworkACLServiceProvider networkACLServiceProvider() { - return Mockito.mock(NetworkACLServiceProvider.class); - } - @Bean - public VpcProvider vpcProvier() { - return Mockito.mock(VpcProvider.class); - } - @Bean - public VolumeService volumeService() { - return Mockito.mock(VolumeService.class); - } - @Bean - public PrimaryDataStoreProviderManager privateDataStoreProviderManager() { - return Mockito.mock(PrimaryDataStoreProviderManager.class); - } - @Bean - public ImageStoreProviderManager imageStoreProviderManager() { - return Mockito.mock(ImageStoreProviderManager.class); - } - @Bean - public DataStoreProvider dataStoreProvider() { - return Mockito.mock(DataStoreProvider.class); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java deleted file mode 100644 index 2107850c36be..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ManagementServerMock.java +++ /dev/null @@ -1,380 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import static org.junit.Assert.assertNotNull; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - -import javax.inject.Inject; - -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.PlugNicAnswer; -import com.cloud.agent.api.UnPlugNicAnswer; -import com.cloud.agent.manager.Commands; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.configuration.ConfigurationService; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.domain.Domain; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.host.Host.Type; -import com.cloud.host.HostVO; -import com.cloud.host.Status; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.network.Network; -import com.cloud.network.Network.Provider; -import com.cloud.network.NetworkService; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetwork.BroadcastDomainRange; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PhysicalNetworkTrafficType; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.offering.ServiceOffering; -import com.cloud.resource.ResourceState; -import com.cloud.service.ServiceOfferingVO; -import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.User; -import com.cloud.uservm.UserVm; -import com.cloud.utils.Pair; -import com.cloud.utils.component.ComponentContext; -import com.cloud.vm.NicProfile; -import com.cloud.vm.UserVmVO; -import com.cloud.vm.VirtualMachineManager; -import com.cloud.vm.dao.UserVmDao; - -public class ManagementServerMock { - protected Logger logger = LogManager.getLogger(getClass()); - - @Inject - private AccountManager _accountMgr; - @Inject - private ConfigurationService _configService; - @Inject - private DataCenterDao _zoneDao; - @Inject - private NetworkService _networkService; - @Inject - private NetworkDao _networksDao; - @Inject - private PhysicalNetworkDao _physicalNetworkDao; - @Inject - private UserVmDao _userVmDao; - @Inject - private ServiceOfferingDao _serviceOfferingDao; - @Inject - private VMTemplateDao _vmTemplateDao; - @Inject - private HostDao _hostDao; - @Inject - public AgentManager _agentMgr; - @Inject - public VirtualMachineManager _vmMgr; - - private DataCenterVO _zone; - private PhysicalNetwork _znet; - - private long _hostId = -1L; - - // TODO: Use the name parameter to retrieve the @Parameter annotation. - static void setParameter(BaseCmd cmd, String name, BaseCmd.CommandType fieldType, Object value) { - Class cls = cmd.getClass(); - Field field; - try { - field = cls.getDeclaredField(name); - } catch (Exception ex) { - return; - } - field.setAccessible(true); - switch (fieldType) { - case STRING: - try { - field.set(cmd, value); - } catch (Exception ex) { - return; - } - break; - case UUID: - if (value.equals("-1")) { - try { - field.setLong(cmd, -1L); - } catch (Exception ex) { - return; - } - } - break; - case LONG: - try { - field.set(cmd, value); - } catch (Exception ex) { - return; - } - break; - default: - try { - field.set(cmd, value); - } catch (Exception ex) { - return; - } - break; - } - } - - private void createHost() { - HostVO host = - new HostVO(_hostId, "aa01", Type.BaremetalDhcp, "192.168.1.1", "255.255.255.0", null, null, null, null, null, null, null, null, null, null, - UUID.randomUUID().toString(), Status.Up, "1.0", null, null, _zone.getId(), null, 0, 0, "aa", 0, StoragePoolType.NetworkFilesystem); - host.setResourceState(ResourceState.Enabled); - _hostDao.persist(host); - _hostId = host.getId(); - } - - private void createPublicVlanIpRange() { - CreateVlanIpRangeCmd cmd = new CreateVlanIpRangeCmd(); - BaseCmd proxy = ComponentContext.inject(cmd); - Long public_net_id = null; - - List nets = _networksDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); - if (nets != null && !nets.isEmpty()) { - NetworkVO public_net = nets.get(0); - public_net_id = public_net.getId(); - } - Account system = _accountMgr.getSystemAccount(); - - setParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); - setParameter(cmd, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN); - setParameter(cmd, "startIp", BaseCmd.CommandType.STRING, "10.84.60.200"); - setParameter(cmd, "endIp", BaseCmd.CommandType.STRING, "10.84.60.250"); - setParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.84.60.254"); - setParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0"); - setParameter(cmd, "networkID", BaseCmd.CommandType.LONG, public_net_id); - setParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, _zone.getId()); - setParameter(cmd, "vlan", BaseCmd.CommandType.STRING, "untagged"); - try { - _configService.createVlanAndPublicIpRange(cmd); - } catch (Exception e) { - } - } - - public UserVm createVM(String name, Network network) { - VMTemplateVO tmpl = getVMTemplate(); - assertNotNull(tmpl); - ServiceOffering small = getServiceByName("Small Instance"); - assertNotNull(small); - - Answer callback = new Answer() { - @Override - public Object answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Commands cmds = (Commands)args[1]; - if (cmds == null) { - return null; - } - PlugNicAnswer reply = new PlugNicAnswer(null, true, "PlugNic"); - com.cloud.agent.api.Answer[] answers = {reply}; - cmds.setAnswers(answers); - return null; - } - }; - sendCommands(callback); - long id = _userVmDao.getNextInSequence(Long.class, "id"); - UserVmVO vm = - new UserVmVO(id, name, name, tmpl.getId(), HypervisorType.XenServer, tmpl.getGuestOSId(), false, false, _zone.getDomainId(), Account.ACCOUNT_ID_SYSTEM, - 1, small.getId(), null, null, null, name); - vm.setState(com.cloud.vm.VirtualMachine.State.Running); - vm.setHostId(_hostId); - vm.setDataCenterId(network.getDataCenterId()); - _userVmDao.persist(vm); - - NicProfile profile = new NicProfile(); - try { - _vmMgr.addVmToNetwork(vm, network, profile); - } catch (Exception ex) { - // ignored - } - return vm; - } - - private void sendCommands(Answer callback) { - try { - Mockito.when(_agentMgr.send(ArgumentMatchers.anyLong(), ArgumentMatchers.any(Commands.class))).thenAnswer(callback); - } catch (AgentUnavailableException e) { - logger.warn("no agent running", e); - } catch (OperationTimedoutException e) { - logger.warn("agent not responding (in time)", e); - } - } - - private void deleteHost() { - _hostDao.remove(_hostId); - - } - - public void deleteVM(UserVm vm, Network network) { - Answer callback = new Answer() { - @Override - public Object answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - Commands cmds = (Commands)args[1]; - if (cmds == null) { - return null; - } - UnPlugNicAnswer reply = new UnPlugNicAnswer(null, true, "PlugNic"); - com.cloud.agent.api.Answer[] answers = {reply}; - cmds.setAnswers(answers); - return null; - } - }; - sendCommands(callback); - _userVmDao.remove(vm.getId()); - } - - public void initialize(boolean oneShot) { - locateZone(); - locatePhysicalNetwork(); - createHost(); - if (oneShot) { - createPublicVlanIpRange(); - } - } - - private VMTemplateVO getVMTemplate() { - List tmpl_list = _vmTemplateDao.listDefaultBuiltinTemplates(); - for (VMTemplateVO tmpl : tmpl_list) { - if (tmpl.getHypervisorType() == HypervisorType.XenServer) { - return tmpl; - } - } - return null; - } - - private ServiceOffering getServiceByName(String name) { - List service_list = Collections.emptyList(); - for (ServiceOfferingVO service : service_list) { - if (service.getName().equals(name)) { - return service; - } - } - return null; - } - - public DataCenter getZone() { - return _zone; - } - - private void locatePhysicalNetwork() { - // mandatory: name, zone-id - try { - long id = _networkService.findPhysicalNetworkId(_zone.getId(), "znet", TrafficType.Guest); - _znet = _networkService.getPhysicalNetwork(id); - List nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); - if (nets == null || nets.isEmpty()) { - _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), "vlan", null, null, null, null, null, null, null); - } - } catch (InvalidParameterValueException e) { - List isolationMethods = new ArrayList(); - isolationMethods.add("L3VPN"); - _znet = - _networkService.createPhysicalNetwork(_zone.getId(), null, null, isolationMethods, BroadcastDomainRange.ZONE.toString(), _zone.getDomainId(), null, - "znet"); - List nets = _physicalNetworkDao.listByZoneAndTrafficType(_zone.getId(), TrafficType.Public); - if (nets == null || nets.isEmpty()) { - _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Public.toString(), "vlan", null, null, null, null, null, null, null); - } - } - if (_znet.getState() != PhysicalNetwork.State.Enabled) { - _znet = _networkService.updatePhysicalNetwork(_znet.getId(), null, null, null, PhysicalNetwork.State.Enabled.toString()); - } - - // Ensure that the physical network supports Guest traffic. - Pair, Integer> trafficTypes = _networkService.listTrafficTypes(_znet.getId()); - boolean found = false; - for (PhysicalNetworkTrafficType ttype : trafficTypes.first()) { - if (ttype.getTrafficType() == TrafficType.Guest) { - found = true; - } - } - if (!found) { - _networkService.addTrafficTypeToPhysicalNetwork(_znet.getId(), TrafficType.Guest.toString(), "vlan", null, null, null, null, null, null, null); - } - - Pair, Integer> providers = - _networkService.listNetworkServiceProviders(_znet.getId(), Provider.JuniperContrailRouter.getName(), null, null, null); - if (providers.second() == 0) { - PhysicalNetworkServiceProvider provider = _networkService.addProviderToPhysicalNetwork(_znet.getId(), Provider.JuniperContrailRouter.getName(), null, null); - _networkService.updateNetworkServiceProvider(provider.getId(), PhysicalNetworkServiceProvider.State.Enabled.toString(), null); - } else { - PhysicalNetworkServiceProvider provider = providers.first().get(0); - if (provider.getState() != PhysicalNetworkServiceProvider.State.Enabled) { - _networkService.updateNetworkServiceProvider(provider.getId(), PhysicalNetworkServiceProvider.State.Enabled.toString(), null); - } - } - - providers = _networkService.listNetworkServiceProviders(_znet.getId(), null, PhysicalNetworkServiceProvider.State.Enabled.toString(), null, null); - for (PhysicalNetworkServiceProvider provider : providers.first()) { - if (provider.getProviderName().equals(Provider.JuniperContrailRouter.getName())) { - continue; - } - _networkService.updateNetworkServiceProvider(provider.getId(), PhysicalNetworkServiceProvider.State.Disabled.toString(), null); - } - } - - private void locateZone() { - _zone = _zoneDao.findByName("default"); - if (_zone == null) { - ConfigurationManager mgr = (ConfigurationManager)_configService; - _zone = - mgr.createZone(User.UID_SYSTEM, "default", "8.8.8.8", null, "8.8.4.4", null, null /* cidr */, "ROOT", Domain.ROOT_DOMAIN, NetworkType.Advanced, null, - null /* networkDomain */, false, false, null, null, false, null); - } - } - - public void shutdown() { - deleteHost(); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/MockAccountManager.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/MockAccountManager.java deleted file mode 100644 index d9f4963165ec..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/MockAccountManager.java +++ /dev/null @@ -1,617 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.util.List; -import java.util.Map; -import java.net.InetAddress; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import com.cloud.api.auth.SetupUserTwoFactorAuthenticationCmd; -import org.apache.cloudstack.acl.RolePermissionEntity; -import org.apache.cloudstack.acl.apikeypair.ApiKeyPairPermission; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.command.admin.account.CreateAccountCmd; -import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; -import org.apache.cloudstack.api.command.admin.user.DeleteUserKeysCmd; -import org.apache.cloudstack.api.command.admin.user.GetUserKeysCmd; -import org.apache.cloudstack.api.command.admin.user.ListUserKeyRulesCmd; -import org.apache.cloudstack.api.command.admin.user.ListUserKeysCmd; -import org.apache.cloudstack.api.command.admin.user.MoveUserCmd; -import org.apache.cloudstack.api.command.admin.user.RegisterUserKeysCmd; -import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; -import org.apache.cloudstack.api.response.UserTwoFactorAuthenticationSetupResponse; -import org.apache.cloudstack.auth.UserTwoFactorAuthenticator; -import org.apache.cloudstack.backup.BackupOffering; -import org.apache.cloudstack.framework.config.ConfigKey; - -import org.apache.cloudstack.acl.apikeypair.ApiKeyPair; -import org.apache.cloudstack.acl.ControlledEntity; -import org.apache.cloudstack.acl.RoleType; -import org.apache.cloudstack.api.response.ApiKeyPairResponse; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.acl.SecurityChecker.AccessType; -import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.query.vo.ControlledViewEntity; -import com.cloud.configuration.ResourceLimit; -import com.cloud.configuration.dao.ResourceCountDao; -import com.cloud.dc.DataCenter; -import com.cloud.domain.Domain; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.PermissionDeniedException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.vpc.VpcOffering; -import com.cloud.offering.DiskOffering; -import com.cloud.offering.NetworkOffering; -import com.cloud.offering.ServiceOffering; -import com.cloud.projects.Project.ListProjectResourcesCriteria; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; -import com.cloud.user.User; -import com.cloud.user.UserAccount; -import com.cloud.user.UserVO; -import com.cloud.user.dao.AccountDao; -import com.cloud.user.dao.UserDao; -import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; -import com.cloud.utils.component.ManagerBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackNoReturn; -import com.cloud.utils.db.TransactionStatus; - -public class MockAccountManager extends ManagerBase implements AccountManager { - - @Inject - AccountDao _accountDao; - @Inject - ResourceCountDao _resourceCountDao; - - @Inject - UserDao _userDao; - - UserVO _systemUser; - AccountVO _systemAccount; - - @Override - public boolean configure(final String name, final Map params) throws ConfigurationException { - _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM); - if (_systemAccount == null) { - throw new ConfigurationException("Unable to find the system account using " + Account.ACCOUNT_ID_SYSTEM); - } - - _systemUser = _userDao.findById(User.UID_SYSTEM); - if (_systemUser == null) { - throw new ConfigurationException("Unable to find the system user using " + User.UID_SYSTEM); - } - CallContext.register(_systemUser, _systemAccount); - logger.info("MockAccountManager initialization successful"); - return true; - } - - @Override - public void checkAccess(Account arg0, Domain arg1) throws PermissionDeniedException { - // TODO Auto-generated method stub - - } - - @Override - public UserAccount getUserAccountById(Long userId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void checkAccess(Account arg0, AccessType arg1, boolean arg2, ControlledEntity... arg3) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public ApiKeyPair createApiKeyAndSecretKey(RegisterUserKeysCmd arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String[] createApiKeyAndSecretKey(final long userId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public User createUser(String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6, Long arg7, String arg8, boolean arg9) { - // TODO Auto-generated method stub - return null; - } - - @Override public User createUser(String userName, String password, String firstName, String lastName, String email, String timeZone, String accountName, Long domainId, - String userUUID, User.Source source) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserAccount createUserAccount(CreateAccountCmd cmd) { - return createUserAccount(cmd.getUsername(), cmd.getPassword(), cmd.getFirstName(), - cmd.getLastName(), cmd.getEmail(), cmd.getTimeZone(), cmd.getAccountName(), - cmd.getAccountType(), cmd.getRoleId(), cmd.getDomainId(), - cmd.getNetworkDomain(), cmd.getDetails(), cmd.getAccountUUID(), - cmd.getUserUUID(), User.Source.UNKNOWN); - } - - @Override - public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, Account.Type accountType, Long roleId, - Long domainId, String networkDomain, Map details, String accountUUID, String userUUID, User.Source source) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Account finalizeOwner(Account arg0, String arg1, Long arg2, Long arg3) { - return _systemAccount; - } - - @Override - public Account getActiveAccountByName(String arg0, Long arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserAccount getActiveUserAccount(String username, Long domainId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getActiveUserAccountByEmail(String email, Long domainId) { - return null; - } - - @Override - public User getActiveUser(long arg0) { - return _systemUser; - } - - @Override - public User getActiveUserByRegistrationToken(String arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public RoleType getRoleType(Account arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Account getSystemAccount() { - return _systemAccount; - } - - @Override - public User getSystemUser() { - return _systemUser; - } - - @Override - public UserAccount getUserByApiKey(String arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public User getUserIncludingRemoved(long arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isAdmin(Long accountId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isRootAdmin(Long accountId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isDomainAdmin(Long accountId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isResourceDomainAdmin(Long accountId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isNormalUser(long accountId) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List listAclGroupsByAccount(Long accountId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserAccount lockUser(long arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void markUserRegistered(long arg0) { - // TODO Auto-generated method stub - - } - - @Override - public UserAccount authenticateUser(String arg0, String arg1, Long arg2, InetAddress arg3, Map arg4) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void buildACLSearchBuilder( - SearchBuilder arg0, Long arg1, - boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { - // TODO Auto-generated method stub - - } - - @Override - public void buildACLSearchCriteria( - SearchCriteria arg0, Long arg1, - boolean arg2, List arg3, ListProjectResourcesCriteria arg4) { - // TODO Auto-generated method stub - - } - - @Override - public void buildACLSearchParameters(Account arg0, Long arg1, String arg2, - Long arg3, List arg4, - Ternary arg5, - boolean arg6, boolean arg7) { - // TODO Auto-generated method stub - - } - - @Override - public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria) { - // TODO Auto-generated method stub - - } - - @Override - public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, - ListProjectResourcesCriteria listProjectResourcesCriteria) { - // TODO Auto-generated method stub - - } - - @Override - public Long checkAccessAndSpecifyAuthority(Account arg0, Long arg1) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean deleteAccount(AccountVO arg0, long arg1, Account arg2) { - return true; - } - - @Override - public boolean deleteUser(DeleteUserCmd arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean moveUser(MoveUserCmd moveUserCmd) { - return false; - } - - @Override - public boolean moveUser(long id, Long domainId, Account account) { - return false; - } - - @Override - public UserTwoFactorAuthenticator getUserTwoFactorAuthenticator(Long domainId, Long userAccountId) { - return null; - } - - @Override - public void verifyUsingTwoFactorAuthenticationCode(String code, Long domainId, Long userAccountId) { - } - - @Override - public UserTwoFactorAuthenticationSetupResponse setupUserTwoFactorAuthentication(SetupUserTwoFactorAuthenticationCmd cmd) { - return null; - } - - @Override - public List getApiNameList() { - return null; - } - - @Override - public boolean deleteUserAccount(long arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean disableAccount(long arg0) throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public Account disableAccount(String arg0, Long arg1, Long arg2) throws ConcurrentOperationException, ResourceUnavailableException { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserAccount disableUser(long arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean enableAccount(long arg0) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Account enableAccount(String arg0, Long arg1, Long arg2) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserAccount enableUser(long arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Ternary findUserByApiKey(String arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Account lockAccount(String arg0, Long arg1, Long arg2) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Account updateAccount(UpdateAccountCmd arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserAccount updateUser(UpdateUserCmd arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Account getActiveAccountById(long accountId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Account getAccount(long accountId) { - return _systemAccount; - } - - @Override - public Account createAccount(String accountName, Account.Type accountType, Long roleId, Long domainId, String networkDomain, Map details, String uuid) { - final AccountVO account = new AccountVO(accountName, domainId, networkDomain, accountType, roleId, uuid); - Transaction.execute(new TransactionCallbackNoReturn() { - @Override - public void doInTransactionWithoutResult(TransactionStatus status) { - - _accountDao.persist(account); - _resourceCountDao.createResourceCounts(account.getId(), ResourceLimit.ResourceOwnerType.Account); - } - }); - return account; - } - - @Override - public void logoutUser(long userId) { - // TODO Auto-generated method stub - - } - - @Override - public void checkAccess(Account account, AccessType accessType, boolean sameOwner, String apiName, - ControlledEntity... entities) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public void validateAccountHasAccessToResource(Account account, AccessType accessType, Object resource) { - // TODO Auto-generated method stub - } - - @Override - public void validateCallingUserHasAccessToDesiredUser(Long userId) { - } - - @Override - public Long finalizeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Long finalizeAccountId(Long accountId, String accountName, Long domainId, Long projectId) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void checkAccess(Account account, ServiceOffering so, DataCenter zone) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public void checkAccess(Account account, DiskOffering dof, DataCenter zone) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public void checkAccess(Account account, NetworkOffering nof, DataCenter zone) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public void checkAccess(Account account, VpcOffering vof, DataCenter zone) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public void checkAccess(Account account, BackupOffering bof) throws PermissionDeniedException { - // TODO Auto-generated method stub - } - - @Override - public Pair> getKeys(GetUserKeysCmd cmd){ - return null; - } - - @Override - public ListResponse listKeys(ListUserKeysCmd cmd) { - return null; - } - - @Override - public List listKeyRules(ListUserKeyRulesCmd cmd) { - return null; - } - - @Override - public void deleteApiKey(DeleteUserKeysCmd cmd) { - } - - @Override - public void deleteApiKey(ApiKeyPair id) { - } - - @Override - public List listUserTwoFactorAuthenticationProviders() { - return null; - } - - @Override - public UserTwoFactorAuthenticator getUserTwoFactorAuthenticationProvider(Long domainId) { - return null; - } - - @Override - public ApiKeyPair getLatestUserKeyPair(Long userId) { - return null; - } - - @Override - public ApiKeyPair getKeyPairById(Long id) { - return null; - } - - @Override - public ApiKeyPair getKeyPairByApiKey(String apiKey) { - return null; - } - - @Override - public String getAccessingApiKey(BaseCmd cmd) { - return null; - } - - @Override - public List getAllKeypairPermissions(String apiKey) { - return List.of(); - } - - @Override - public void checkAccess(User user, ControlledEntity entity) - throws PermissionDeniedException { - - } - @Override - public String getConfigComponentName() { - return null; - } - - @Override - public ConfigKey[] getConfigKeys() { - return null; - } - - public void validateUserPasswordAndUpdateIfNeeded(String newPassword, UserVO user, - String currentPassword, - boolean skipCurrentPassValidation) { - } - - @Override - public void checkApiAccess(Account account, String command, String apiKey) throws PermissionDeniedException { - } - - @Override - public UserAccount clearUserTwoFactorAuthenticationInSetupStateOnLogin(UserAccount user) { - return null; - } - - @Override - public void verifyCallerPrivilegeForUserOrAccountOperations(Account userAccount) { - } - - @Override - public void verifyCallerPrivilegeForUserOrAccountOperations(User user) { - } - - @Override - public void checkCallerRoleTypeAllowedForUserOrAccountOperations(Account userAccount, User user) { - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java deleted file mode 100644 index cbd93669c689..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/NetworkProviderTest.java +++ /dev/null @@ -1,466 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.command.user.address.AssociateIPAddrCmd; -import org.apache.cloudstack.api.command.user.nat.DisableStaticNatCmd; -import org.apache.cloudstack.api.command.user.nat.EnableStaticNatCmd; -import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; -import org.apache.cloudstack.api.command.user.project.CreateProjectCmd; -import org.apache.cloudstack.api.command.user.project.DeleteProjectCmd; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.utils.identity.ManagementServerNode; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.cloud.agent.AgentManager; -import com.cloud.dc.DataCenter; -import com.cloud.domain.Domain; -import com.cloud.domain.DomainVO; -import com.cloud.domain.dao.DomainDao; -import com.cloud.exception.CloudException; -import com.cloud.network.Network; -import com.cloud.network.NetworkService; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.projects.ProjectVO; -import com.cloud.projects.dao.ProjectDao; -import com.cloud.user.Account; -import com.cloud.user.AccountManager; -import com.cloud.user.User; -import com.cloud.uservm.UserVm; -import com.cloud.utils.component.ComponentContext; -import com.cloud.utils.component.ComponentLifecycle; -import com.cloud.utils.db.Merovingian2; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.mgmt.JmxUtil; -import com.cloud.vm.VirtualMachineManager; - -import junit.framework.TestCase; -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorFactory; -import net.juniper.contrail.api.ApiConnectorMock; -import net.juniper.contrail.api.types.InstanceIp; -import net.juniper.contrail.api.types.NetworkIpam; -import net.juniper.contrail.api.types.Project; -import net.juniper.contrail.api.types.SubnetType; -import net.juniper.contrail.api.types.VirtualMachine; -import net.juniper.contrail.api.types.VirtualMachineInterface; -import net.juniper.contrail.api.types.VirtualNetwork; -import net.juniper.contrail.api.types.VnSubnetsType; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "classpath:/providerContext.xml") -/** - * Exercise the public API. - */ -public class NetworkProviderTest extends TestCase { - - @Inject - public ContrailManager _contrailMgr; - @Inject - public ServerDBSync _dbSync; - @Inject - public AccountManager _accountMgr; - @Inject - IPAddressDao _ipAddressDao; - @Inject - private NetworkService _networkService; - - @Inject - public VirtualMachineManager _vmMgr; - - @Inject - public DomainDao _domainDao; - @Inject - public ProjectDao _projectDao; - @Inject - public AgentManager _agentMgr; - - private ManagementServerMock _server; - private ApiConnector _api; - private static int s_mysqlSrverPort; - private static long s_msId; - private static Merovingian2 s_lockController; - public static boolean s_initDone = false; - - @BeforeClass - public static void globalSetUp() throws Exception { - ApiConnectorFactory.setImplementation(ApiConnectorMock.class); - s_mysqlSrverPort = TestDbSetup.init(null); - - s_msId = ManagementServerNode.getManagementServerId(); - s_lockController = Merovingian2.createLockController(s_msId); - } - - @AfterClass - public static void globalTearDown() throws Exception { - s_lockController.cleanupForServer(s_msId); - JmxUtil.unregisterMBean("Locks", "Locks"); - s_lockController = null; - - AbstractApplicationContext ctx = (AbstractApplicationContext)ComponentContext.getApplicationContext(); - Map lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class); - for (ComponentLifecycle bean : lifecycleComponents.values()) { - bean.stop(); - } - ctx.close(); - - TestDbSetup.destroy(s_mysqlSrverPort, null); - } - - @Override - @Before - public void setUp() throws Exception { - try { - ComponentContext.initComponentsLifeCycle(); - } catch (Exception ex) { - ex.printStackTrace(); - } - Account system = _accountMgr.getSystemAccount(); - User user = _accountMgr.getSystemUser(); - CallContext.register(user, system); - _server = ComponentContext.inject(new ManagementServerMock()); - - _server.initialize(!s_initDone); - s_initDone = false; - _api = _contrailMgr.getApiConnector(); - } - - @Override - @After - public void tearDown() throws Exception { - _server.shutdown(); - } - - private void purgeTestNetwork() { - Account system = _accountMgr.getSystemAccount(); - DataCenter zone = _server.getZone(); - List list = _networkService.getIsolatedNetworksOwnedByAccountInZone(zone.getId(), system); - for (Network net : list) { - _networkService.deleteNetwork(net.getId(), false); - } - } - - private Network lookupTestNetwork(String name) { - Account system = _accountMgr.getSystemAccount(); - DataCenter zone = _server.getZone(); - List list = _networkService.getIsolatedNetworksOwnedByAccountInZone(zone.getId(), system); - for (Network net : list) { - if (net.getName().equals(name)) { - return net; - } - } - return null; - } - - private Network createTestNetwork(String name) { - CreateNetworkCmd cmd = new CreateNetworkCmd(); - ComponentContext.inject(cmd); - Account system = _accountMgr.getSystemAccount(); - DataCenter zone = _server.getZone(); - - ManagementServerMock.setParameter(cmd, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); - ManagementServerMock.setParameter(cmd, ApiConstants.NAME, BaseCmd.CommandType.STRING, name); - ManagementServerMock.setParameter(cmd, "displayText", BaseCmd.CommandType.STRING, "test network"); - ManagementServerMock.setParameter(cmd, "networkOfferingId", BaseCmd.CommandType.LONG, _contrailMgr.getRouterOffering().getId()); - ManagementServerMock.setParameter(cmd, "zoneId", BaseCmd.CommandType.LONG, zone.getId()); - ManagementServerMock.setParameter(cmd, ApiConstants.GATEWAY, BaseCmd.CommandType.STRING, "10.0.1.254"); - ManagementServerMock.setParameter(cmd, ApiConstants.NETMASK, BaseCmd.CommandType.STRING, "255.255.255.0"); - // Physical network id can't be specified for Guest traffic type. - // SetParameter(cmd, "physicalNetworkId", BaseCmd.CommandType.LONG, _znet.getId()); - - Network result = null; - try { - result = _networkService.createGuestNetwork(cmd); - } catch (CloudException e) { - e.printStackTrace(); - return null; - } - return result; - } - - @Test - //@Ignore - public - void testCreateNetwork() { - purgeTestNetwork(); - createTestNetwork("test"); - } - - @Test - public void testConnectivity() { - Network network = lookupTestNetwork("test"); - if (network == null) { - network = createTestNetwork("test"); - } - UserVm vm1 = _server.createVM("x01", network); - UserVm vm2 = _server.createVM("x02", network); - - _server.deleteVM(vm1, network); - _server.deleteVM(vm2, network); - } - - @Test - public void floatingIpTest() { - Network network = lookupTestNetwork("test-fip-net"); - if (network == null) { - network = createTestNetwork("test-fip-net"); - } - UserVm vm = _server.createVM("test-fip-vm", network); - try { - IPAddressVO ip = createFloatingIp(network, vm); - deleteFloatingIp(ip); - } catch (Exception e) { - fail("unable to create/delete floating ip"); - } - _server.deleteVM(vm, network); - } - - public void deleteFloatingIp(IPAddressVO ip) throws Exception { - BaseCmd cmd = new DisableStaticNatCmd(); - BaseCmd proxy = ComponentContext.inject(cmd); - ManagementServerMock.setParameter(proxy, "ipAddressId", BaseCmd.CommandType.LONG, ip.getId()); - try { - proxy.execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - public IPAddressVO createFloatingIp(Network network, UserVm vm) throws Exception { - BaseCmd cmd = new AssociateIPAddrCmd(); - BaseCmd proxy = ComponentContext.inject(cmd); - Account system = _accountMgr.getSystemAccount(); - DataCenter zone = _server.getZone(); - - ManagementServerMock.setParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); - ManagementServerMock.setParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN); - ManagementServerMock.setParameter(proxy, "zoneId", BaseCmd.CommandType.LONG, zone.getId()); - ManagementServerMock.setParameter(proxy, "networkId", BaseCmd.CommandType.LONG, network.getId()); - try { - ((AssociateIPAddrCmd)cmd).create(); - ((AssociateIPAddrCmd)cmd).execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - SearchBuilder searchBuilder = _ipAddressDao.createSearchBuilder(); - searchBuilder.and("sourceNat", searchBuilder.entity().isSourceNat(), Op.EQ); - searchBuilder.and("network", searchBuilder.entity().getAssociatedWithNetworkId(), Op.EQ); - searchBuilder.and("dataCenterId", searchBuilder.entity().getDataCenterId(), Op.EQ); - searchBuilder.and("associatedWithVmId", searchBuilder.entity().getAssociatedWithVmId(), Op.NULL); - SearchCriteria sc = searchBuilder.create(); - sc.setParameters("sourceNat", false); - sc.setParameters("network", network.getId()); - - List publicIps = _ipAddressDao.search(sc, null); - assertNotNull(publicIps); - - cmd = new EnableStaticNatCmd(); - proxy = ComponentContext.inject(cmd); - ManagementServerMock.setParameter(proxy, "ipAddressId", BaseCmd.CommandType.LONG, publicIps.get(0).getId()); - ManagementServerMock.setParameter(proxy, "networkId", BaseCmd.CommandType.LONG, network.getId()); - ManagementServerMock.setParameter(proxy, "virtualMachineId", BaseCmd.CommandType.LONG, vm.getId()); - - try { - proxy.execute(); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - return publicIps.get(0); - } - - public void createProject(String name) { - BaseCmd cmd = new CreateProjectCmd(); - BaseCmd proxy = ComponentContext.inject(cmd); - Account system = _accountMgr.getSystemAccount(); - - ManagementServerMock.setParameter(proxy, "accountName", BaseCmd.CommandType.STRING, system.getAccountName()); - ManagementServerMock.setParameter(proxy, "domainId", BaseCmd.CommandType.LONG, Domain.ROOT_DOMAIN); - ManagementServerMock.setParameter(proxy, "name", BaseCmd.CommandType.STRING, name); - ManagementServerMock.setParameter(proxy, "displayText", BaseCmd.CommandType.STRING, name); - try { - ((CreateProjectCmd)proxy).create(); - ((CreateProjectCmd)proxy).execute(); - } catch (Exception e) { - e.printStackTrace(); - fail("create project cmd failed"); - } - DomainVO domain = _domainDao.findById(Domain.ROOT_DOMAIN); - try { - net.juniper.contrail.api.types.Domain vncDomain = - (net.juniper.contrail.api.types.Domain)_api.findById(net.juniper.contrail.api.types.Domain.class, domain.getUuid()); - if (_api.findByName(net.juniper.contrail.api.types.Project.class, vncDomain, name) == null) { - fail("create project failed in vnc"); - } - } catch (Exception e) { - e.printStackTrace(); - fail("Exception while creating a project in vnc"); - } - } - - public void deleteProject(String name) { - BaseCmd cmd = new DeleteProjectCmd(); - BaseCmd proxy = ComponentContext.inject(cmd); - - ProjectVO project = _projectDao.findByNameAndDomain(name, Domain.ROOT_DOMAIN); - try { - ManagementServerMock.setParameter(proxy, "id", BaseCmd.CommandType.LONG, project.getId()); - ((DeleteProjectCmd)proxy).execute(); - if (_api.findById(net.juniper.contrail.api.types.Project.class, project.getUuid()) != null) { - fail("unable to delete project in vnc"); - } - } catch (Exception e) { - e.printStackTrace(); - fail("Exception while deleting project"); - } - } - - @Test - public void testProject() { - createProject("test-project"); - deleteProject("test-project"); - } - - @Test - public void dbSyncTest() { - Network network = lookupTestNetwork("test-db-only-net"); - if (network == null) { - network = createTestNetwork("test-db-only-net"); - } - UserVm vm = _server.createVM("test-db-only-vm", network); - try { - createFloatingIp(network, vm); - } catch (Exception e) { - fail("unable to create floating ip"); - } - - /* reset ApiServer objects to default config only, so above created objects - * exists only in cludstack db but not in api server - */ - ((ApiConnectorMock)_api).initConfig(); - /* reset model cached objects */ - _contrailMgr.getDatabase().initDb(); - - /* Create one object of each type directly in api-server - these objects does not exist in cloudstack */ - net.juniper.contrail.api.types.Domain domain = new net.juniper.contrail.api.types.Domain(); - domain.setName("test-vnc-only-domain--1"); - domain.setUuid(UUID.randomUUID().toString()); - try { - assertTrue(_api.create(domain)); - } catch (IOException ex) { - fail(ex.getMessage()); - } - - Project project = new Project(); - project.setName("test-vnc-only-project-1"); - project.setUuid(UUID.randomUUID().toString()); - project.setParent(domain); - try { - assertTrue(_api.create(project)); - } catch (IOException ex) { - fail(ex.getMessage()); - } - - VirtualNetwork net = new VirtualNetwork(); - net.setName("test-vnc-only-net-1"); - net.setUuid(UUID.randomUUID().toString()); - net.setParent(project); - - NetworkIpam ipam = null; - try { - // Find default-network-ipam - String ipam_id = _api.findByName(NetworkIpam.class, null, "default-network-ipam"); - assertNotNull(ipam_id); - ipam = (NetworkIpam)_api.findById(NetworkIpam.class, ipam_id); - assertNotNull(ipam); - } catch (IOException ex) { - fail(ex.getMessage()); - } - - VnSubnetsType subnet = new VnSubnetsType(); - subnet.addIpamSubnets(new SubnetType("10.0.2.0", 24), "10.0.2.254"); - - net.addNetworkIpam(ipam, subnet); - - VirtualMachine vncVm = new VirtualMachine(); - vncVm.setName("test-vnc-only-vm-1"); - try { - assertTrue(_api.create(vncVm)); - } catch (IOException ex) { - fail(ex.getMessage()); - } - - VirtualMachineInterface vmi = new VirtualMachineInterface(); - vmi.setParent(vncVm); - vmi.setName("test-vnc-only-vmi-1"); - - try { - assertTrue(_api.create(vmi)); - assertTrue(_api.create(net)); - } catch (IOException ex) { - fail(ex.getMessage()); - } - InstanceIp ip_obj = new InstanceIp(); - ip_obj.setName(net.getName() + ":0"); - ip_obj.setVirtualNetwork(net); - ip_obj.setVirtualMachineInterface(vmi); - try { - assertTrue(_api.create(ip_obj)); - // Must perform a GET in order to update the object contents. - assertTrue(_api.read(ip_obj)); - assertNotNull(ip_obj.getAddress()); - - } catch (IOException ex) { - fail(ex.getMessage()); - } - - //now db sync - if (_dbSync.syncAll(DBSyncGeneric.SYNC_MODE_UPDATE) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) { - //# Cloudstack DB & VNC are out of sync - resync done - } - - if (_dbSync.syncAll(DBSyncGeneric.SYNC_MODE_CHECK) == ServerDBSync.SYNC_STATE_OUT_OF_SYNC) { - //# Cloudstack DB & VNC are still out of sync - fail("DB Sync failed"); - } - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java deleted file mode 100644 index 3c2159015333..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/ProviderTestConfiguration.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 org.apache.cloudstack.network.contrail.management; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ProviderTestConfiguration { - @Bean - ServerDBSync getServerDBSync() { - return new ServerDBSyncImpl(); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java deleted file mode 100644 index 914545e26830..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTest.java +++ /dev/null @@ -1,144 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import junit.framework.TestCase; -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorFactory; -import net.juniper.contrail.api.ApiObjectBase; -import net.juniper.contrail.api.types.VirtualMachineInterface; -import net.juniper.contrail.api.types.VirtualNetwork; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import org.apache.cloudstack.utils.identity.ManagementServerNode; - -import com.cloud.dc.DataCenter; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.uservm.UserVm; -import com.cloud.utils.component.ComponentContext; -import com.cloud.utils.component.ComponentLifecycle; -import com.cloud.utils.db.Merovingian2; -import com.cloud.utils.mgmt.JmxUtil; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "classpath:/publicNetworkContext.xml") -public class PublicNetworkTest extends TestCase { - - @Inject - public ContrailManager _contrailMgr; - @Inject - public NetworkDao _networksDao; - - private static boolean s_initDone = false; - private static int s_mysqlServerPort; - private static long s_msId; - private static Merovingian2 s_lockController; - private ManagementServerMock _server; - private ApiConnector _spy; - - @BeforeClass - public static void globalSetUp() throws Exception { - ApiConnectorFactory.setImplementation(ApiConnectorMockito.class); - s_mysqlServerPort = TestDbSetup.init(null); - s_msId = ManagementServerNode.getManagementServerId(); - s_lockController = Merovingian2.createLockController(s_msId); - } - - @AfterClass - public static void globalTearDown() throws Exception { - s_lockController.cleanupForServer(s_msId); - JmxUtil.unregisterMBean("Locks", "Locks"); - s_lockController = null; - - AbstractApplicationContext ctx = (AbstractApplicationContext)ComponentContext.getApplicationContext(); - Map lifecycleComponents = ctx.getBeansOfType(ComponentLifecycle.class); - for (ComponentLifecycle bean : lifecycleComponents.values()) { - bean.stop(); - } - ctx.close(); - - TestDbSetup.destroy(s_mysqlServerPort, null); - } - - @Override - @Before - public void setUp() throws Exception { - try { - ComponentContext.initComponentsLifeCycle(); - } catch (Exception ex) { - ex.printStackTrace(); - } - _server = ComponentContext.inject(new ManagementServerMock()); - - _server.initialize(!s_initDone); - s_initDone = false; - _spy = ((ApiConnectorMockito)_contrailMgr.getApiConnector()).getSpy(); - } - - @Override - @After - public void tearDown() throws Exception { - _server.shutdown(); - } - - @Test - public void testPublicNetwork() throws IOException { - DataCenter zone = _server.getZone(); - List networks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Public); - assertNotNull(networks); - assertFalse(networks.isEmpty()); - UserVm vm1 = _server.createVM("test", networks.get(0)); - - ArgumentCaptor createArg = ArgumentCaptor.forClass(ApiObjectBase.class); - verify(_spy, times(4)).create(createArg.capture()); - - List argumentList = createArg.getAllValues(); - ApiObjectBase vmObj = argumentList.get(0); - assertEquals(VirtualNetwork.class, vmObj.getClass()); - assertEquals("__default_Public__", vmObj.getName()); - - String vmiName = null; - for (ApiObjectBase obj : argumentList) { - if (obj.getClass() == VirtualMachineInterface.class) { - vmiName = obj.getName(); - } - } - assertEquals("test-0", vmiName); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java deleted file mode 100644 index b41e282d9343..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/PublicNetworkTestConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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 org.apache.cloudstack.network.contrail.management; - -import org.mockito.Mockito; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class PublicNetworkTestConfiguration { - @Bean - ServerDBSync getServerDBSync() { - return Mockito.mock(ServerDBSync.class); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/TestDbSetup.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/TestDbSetup.java deleted file mode 100644 index 4dfc207897dd..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/management/TestDbSetup.java +++ /dev/null @@ -1,142 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.management; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStreamReader; -import java.net.ServerSocket; - -import org.apache.commons.configuration.PropertiesConfiguration; - -public class TestDbSetup { - - public static int findFreePort() throws Exception { - - int port; - ServerSocket socket = new ServerSocket(0); - port = socket.getLocalPort(); - socket.close(); - - return port; - } - - public static void startMysqlServer(int port, String startMysqlScript) throws Exception { - - try { - String cwd = new java.io.File(".").getCanonicalPath(); - Runtime r = Runtime.getRuntime(); - String script = startMysqlScript; - if (script == null) { - script = "test/resources/mysql_db_start.sh " + port; - } - Process process = r.exec("sh " + cwd + "/" + script); - process.waitFor(); - System.out.println("new sql server instance launched on port: " + port); - } catch (Exception e) { - - String cause = e.getMessage(); - if (cause.equals("sh: not found")) - System.out.println("No sh interpreter found."); - throw e; - } - } - - public static void stopMysqlServer(int port, String stopMysqlScript) throws Exception { - - try { - Runtime r = Runtime.getRuntime(); - String script = stopMysqlScript; - if (script == null) { - script = "test/resources/mysql_db_stop.sh " + port; - } - Process process = r.exec("sh " + script); - process.waitFor(); - System.out.println("sql server instance running at port " + port + " stopped"); - } catch (Exception e) { - - String cause = e.getMessage(); - if (cause.equals("sh: not found")) - System.out.println("No sh interpreter found."); - throw e; - } - } - - /* this is required for deploying db with new set of sql server parameters */ - public static void copyDbPropertiesFile() throws Exception { - Runtime.getRuntime().exec("cp ../../../utils/conf/db.properties ../../../utils/conf/db.properties.override"); - } - - public static void updateSqlPort(int port, String propertyFileOverride) throws Exception { - - PropertiesConfiguration config = new PropertiesConfiguration(propertyFileOverride); - System.out.println("File: " + propertyFileOverride + "; old: db.properties port: " + config.getProperty("db.cloud.port") + ", new port: " + port); - config.setProperty("db.cloud.port", "" + port); - config.setProperty("db.cloud.username", System.getProperty("user.name")); - config.setProperty("db.cloud.password", ""); - - config.setProperty("db.usage.port", "" + port); - config.setProperty("db.usage.username", System.getProperty("user.name")); - config.setProperty("db.usage.password", ""); - - config.setProperty("db.simulator.port", "" + port); - config.setProperty("db.simulator.username", System.getProperty("user.name")); - config.setProperty("db.simulator.password", ""); - - config.save(); - } - - public static void initCloudstackDb() throws Exception { - try { - File dir = new File("../../../"); - Runtime r = Runtime.getRuntime(); - Process process = r.exec("mvn -P developer -pl developer -Ddeploydb ", null, dir); - dumpProcessOutput(process); - process.waitFor(); - } catch (Exception e) { - String cause = e.getMessage(); - System.out.println("e: " + cause); - throw e; - } - } - - public static void dumpProcessOutput(Process p) throws Exception { - - BufferedReader istream = null; - istream = new BufferedReader(new InputStreamReader(p.getInputStream())); - String line = null; - while ((line = istream.readLine()) != null) { - System.out.println(line); - } - } - - public static int init(String startScript) throws Exception { - int port = TestDbSetup.findFreePort(); - TestDbSetup.startMysqlServer(port, startScript); - copyDbPropertiesFile(); - /* both of these files needs to have mysql port, username password details */ - TestDbSetup.updateSqlPort(port, "db.properties"); /* for cloudstack runtime */ - TestDbSetup.updateSqlPort(port, "../../../utils/conf/db.properties.override"); /* for deploying db */ - TestDbSetup.initCloudstackDb(); - return port; - } - - public static void destroy(int port, String stopScript) throws Exception { - TestDbSetup.stopMysqlServer(port, stopScript); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/InstanceIpModelTest.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/InstanceIpModelTest.java deleted file mode 100644 index fa0f2afcc6d5..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/InstanceIpModelTest.java +++ /dev/null @@ -1,128 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.UUID; - -import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; -import org.junit.Test; - -import com.cloud.network.Network; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.dao.UserVmDao; - -import junit.framework.TestCase; -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorMock; - -public class InstanceIpModelTest extends TestCase { - - @Test - public void testCreateInstanceIp() throws IOException { - - ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); - ModelController controller = mock(ModelController.class); - ApiConnector api = new ApiConnectorMock(null, 0); - when(controller.getApiAccessor()).thenReturn(api); - when(controller.getManager()).thenReturn(contrailMgr); - - // Create Virtual-Network (VN) - NetworkVO network = MockNetworkVO.getNetwork(Network.State.Implemented); - NetworkDao networkDao = mock(NetworkDao.class); - when(networkDao.findById(anyLong())).thenReturn(network); - when(controller.getNetworkDao()).thenReturn(networkDao); - - when(contrailMgr.getCanonicalName(network)).thenReturn("testnetwork"); - when(contrailMgr.getProjectId(network.getDomainId(), network.getAccountId())).thenReturn("testProjectId"); - - VirtualNetworkModel vnModel = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test", - TrafficType.Guest); - vnModel.build(controller, network); - try { - vnModel.update(controller); - } catch (Exception ex) { - fail("virtual-network update failed "); - } - - // Create Virtual-Machine (VM) - VMInstanceVO vm = mock(VMInstanceVO.class); - when(vm.getInstanceName()).thenReturn("testVM1"); - when(vm.getState()).thenReturn(VirtualMachine.State.Running); - when(vm.getDomainId()).thenReturn(10L); - when(vm.getAccountId()).thenReturn(42L); - UserVmDao VmDao = mock(UserVmDao.class); - when(VmDao.findById(anyLong())).thenReturn(null); - when(controller.getVmDao()).thenReturn(VmDao); - - VirtualMachineModel vmModel = new VirtualMachineModel(vm, UUID.randomUUID().toString()); - vmModel.build(controller, vm); - try { - vmModel.update(controller); - } catch (Exception ex) { - fail("virtual-machine update failed "); - } - - // Create Virtual=Machine-Interface (VMInterface) - NicVO nic = mock(NicVO.class); - when(nic.getIPv4Address()).thenReturn("10.1.1.2"); - when(nic.getMacAddress()).thenReturn("00:01:02:03:04:05"); - when(nic.getDeviceId()).thenReturn(100); - when(nic.getState()).thenReturn(NicVO.State.Allocated); - when(nic.getNetworkId()).thenReturn(10L); - - when(contrailMgr.getVifNameByVmName(anyString(), anyInt())).thenReturn("testVM1-100"); - - VMInterfaceModel vmiModel = new VMInterfaceModel(UUID.randomUUID().toString()); - vmiModel.addToVirtualMachine(vmModel); - vmiModel.addToVirtualNetwork(vnModel); - - try { - vmiModel.build(controller, vm, nic); - vmiModel.setActive(); - } catch (Exception ex) { - fail("vm-interface build failed "); - } - - try { - vmiModel.update(controller); - } catch (Exception ex) { - fail("vm-interface update failed "); - } - InstanceIpModel ipModel = new InstanceIpModel(vm.getInstanceName(), nic.getDeviceId()); - ipModel.addToVMInterface(vmiModel); - ipModel.setAddress(nic.getIPv4Address()); - - try { - ipModel.update(controller); - } catch (Exception ex) { - fail("ipInstance update failed "); - } - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/MockNetworkVO.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/MockNetworkVO.java deleted file mode 100644 index d7d774a947b0..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/MockNetworkVO.java +++ /dev/null @@ -1,50 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import com.cloud.network.Network; -import com.cloud.network.dao.NetworkVO; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MockNetworkVO { - - private NetworkVO network; - - MockNetworkVO(Network.State state) { - network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(state); - when(network.getGateway()).thenReturn("10.1.1.1"); - when(network.getCidr()).thenReturn("10.1.1.0/24"); - when(network.getPhysicalNetworkId()).thenReturn(42L); - when(network.getDomainId()).thenReturn(10L); - when(network.getAccountId()).thenReturn(42L); - } - - public NetworkVO getNetwork() { - return network; - } - - public static NetworkVO getNetwork(Network.State state) { - MockNetworkVO mockNetwork = new MockNetworkVO(state); - return mockNetwork.getNetwork(); - } - -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModelTest.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModelTest.java deleted file mode 100644 index 5339066dd007..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VMInterfaceModelTest.java +++ /dev/null @@ -1,133 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.UUID; - -import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; -import org.junit.Test; - -import com.cloud.network.Network; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.vm.NicVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.dao.UserVmDao; - -import junit.framework.TestCase; -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorMock; -import net.juniper.contrail.api.types.VirtualMachineInterface; - -public class VMInterfaceModelTest extends TestCase { - - @Test - public void testCreateVMInterface() throws IOException { - - String uuid; - ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); - ModelController controller = mock(ModelController.class); - ApiConnector api = new ApiConnectorMock(null, 0); - when(controller.getManager()).thenReturn(contrailMgr); - when(controller.getApiAccessor()).thenReturn(api); - - // Create Virtual-Network (VN) - NetworkVO network = MockNetworkVO.getNetwork(Network.State.Implemented); - NetworkDao networkDao = mock(NetworkDao.class); - when(networkDao.findById(anyLong())).thenReturn(network); - when(controller.getNetworkDao()).thenReturn(networkDao); - - when(contrailMgr.getCanonicalName(network)).thenReturn("testnetwork"); - when(contrailMgr.getProjectId(network.getDomainId(), network.getAccountId())).thenReturn("testProjectId"); - - VirtualNetworkModel vnModel = new VirtualNetworkModel(network, UUID.randomUUID().toString(), - "test", TrafficType.Guest); - vnModel.build(controller, network); - try { - vnModel.update(controller); - } catch (Exception ex) { - fail("virtual-network update failed "); - } - - // Create Virtual-Machine (VM) - VMInstanceVO vm = mock(VMInstanceVO.class); - when(vm.getInstanceName()).thenReturn("testVM1"); - when(vm.getState()).thenReturn(VirtualMachine.State.Running); - when(vm.getDomainId()).thenReturn(10L); - when(vm.getAccountId()).thenReturn(42L); - UserVmDao VmDao = mock(UserVmDao.class); - when(VmDao.findById(anyLong())).thenReturn(null); - when(controller.getVmDao()).thenReturn(VmDao); - - VirtualMachineModel vmModel = new VirtualMachineModel(vm, UUID.randomUUID().toString()); - vmModel.build(controller, vm); - try { - vmModel.update(controller); - } catch (Exception ex) { - fail("virtual-machine update failed "); - } - - // Create Virtual=Machine-Interface (VMInterface) - NicVO nic = mock(NicVO.class); - when(nic.getIPv4Address()).thenReturn("10.1.1.2"); - when(nic.getMacAddress()).thenReturn("00:01:02:03:04:05"); - when(nic.getDeviceId()).thenReturn(100); - when(nic.getState()).thenReturn(NicVO.State.Allocated); - when(nic.getNetworkId()).thenReturn(10L); - - when(contrailMgr.getVifNameByVmName(anyString(), anyInt())).thenReturn("testVM1-100"); - - uuid = UUID.randomUUID().toString(); - VMInterfaceModel vmiModel = new VMInterfaceModel(uuid); - - assertEquals(uuid, vmiModel.getUuid()); - - vmiModel.addToVirtualMachine(vmModel); - vmiModel.addToVirtualNetwork(vnModel); - - try { - vmiModel.build(controller, vm, nic); - vmiModel.setActive(); - } catch (Exception ex) { - fail("vm-interface build failed "); - } - - try { - vmiModel.update(controller); - } catch (Exception ex) { - fail("vm-interface update failed "); - } - - // Verify virtual-machine-interface creation. - try { - VirtualMachineInterface vmi = (VirtualMachineInterface) api.findById(VirtualMachineInterface.class, vmiModel.getUuid()); - assertNotNull(vmi); - } catch (Exception ex) { - fail("vm-interface verify failed "); - } - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java deleted file mode 100644 index 0219c3200deb..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualMachineModelTest.java +++ /dev/null @@ -1,110 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.UUID; - -import junit.framework.TestCase; -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorMock; - -import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; -import org.apache.cloudstack.network.contrail.management.ModelDatabase; -import org.junit.Test; - -import com.cloud.network.Network; -import com.cloud.network.dao.NetworkVO; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.dao.UserVmDao; - -public class VirtualMachineModelTest extends TestCase { - - @Test - public void testVirtualMachineDBLookup() { - ModelDatabase db = new ModelDatabase(); - VMInstanceVO vm = mock(VMInstanceVO.class); - - // Create 3 dummy Virtual Machine model objects - // Add these models to database. - // Each VM is identified by unique UUId. - VirtualMachineModel vm0 = new VirtualMachineModel(vm, "fbc1f8fa-4b78-45ee-bba0-b551dbf72353"); - db.getVirtualMachines().add(vm0); - - VirtualMachineModel vm1 = new VirtualMachineModel(vm, "fbc1f8fa-4b78-45ee-bba0-b551dbf83464"); - db.getVirtualMachines().add(vm1); - - VirtualMachineModel vm2 = new VirtualMachineModel(vm, "fbc1f8fa-4b78-45ee-bba0-b551dbf94575"); - db.getVirtualMachines().add(vm2); - - - assertEquals(3, db.getVirtualMachines().size()); - - assertSame(vm0, db.lookupVirtualMachine("fbc1f8fa-4b78-45ee-bba0-b551dbf72353")); - assertSame(vm1, db.lookupVirtualMachine("fbc1f8fa-4b78-45ee-bba0-b551dbf83464")); - assertSame(vm2, db.lookupVirtualMachine("fbc1f8fa-4b78-45ee-bba0-b551dbf94575")); - } - - @Test - public void testCreateVirtualMachine() throws IOException { - - String uuid = UUID.randomUUID().toString(); - ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); - ModelController controller = mock(ModelController.class); - ApiConnector api = new ApiConnectorMock(null, 0); - when(controller.getManager()).thenReturn(contrailMgr); - when(controller.getApiAccessor()).thenReturn(api); - - // Create Virtual-Network (VN) - NetworkVO network = MockNetworkVO.getNetwork(Network.State.Allocated); - - when(contrailMgr.getCanonicalName(network)).thenReturn("testnetwork"); - when(contrailMgr.getProjectId(network.getDomainId(), network.getAccountId())).thenReturn("testProjectId"); - - // Create Virtual-Machine (VM) - VMInstanceVO vm = mock(VMInstanceVO.class); - when(vm.getInstanceName()).thenReturn("testVM1"); - when(vm.getState()).thenReturn(VirtualMachine.State.Starting); - when(vm.getDomainId()).thenReturn(10L); - when(vm.getAccountId()).thenReturn(42L); - - UserVmDao VmDao = mock(UserVmDao.class); - when(VmDao.findById(anyLong())).thenReturn(null); - when(controller.getVmDao()).thenReturn(VmDao); - - VirtualMachineModel vmModel = new VirtualMachineModel(vm, uuid); - - assertEquals(vmModel.getInstanceName(), "testVM1"); - assertEquals(vmModel.getUuid(), uuid); - - vmModel.build(controller, vm); - try { - vmModel.update(controller); - } catch (Exception ex) { - fail("virtual-network update failed "); - } - - //verify - assertTrue(vmModel.verify(controller)); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java b/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java deleted file mode 100644 index 2b2cd9af9f06..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/java/org/apache/cloudstack/network/contrail/model/VirtualNetworkModelTest.java +++ /dev/null @@ -1,205 +0,0 @@ -// 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 org.apache.cloudstack.network.contrail.model; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -import junit.framework.TestCase; -import net.juniper.contrail.api.ApiConnector; -import net.juniper.contrail.api.ApiConnectorMock; -import net.juniper.contrail.api.ObjectReference; -import net.juniper.contrail.api.types.VirtualNetwork; -import net.juniper.contrail.api.types.VirtualNetworkPolicyType; - -import org.apache.cloudstack.network.contrail.management.ContrailManager; -import org.apache.cloudstack.network.contrail.management.ContrailManagerImpl; -import org.apache.cloudstack.network.contrail.management.ModelDatabase; -import org.junit.Before; -import org.junit.Test; - -import com.cloud.dc.dao.VlanDao; -import com.cloud.network.Network.State; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.NetworkVO; - -public class VirtualNetworkModelTest extends TestCase { - - - private ModelController controller; - - private VirtualNetworkModel vnModel; - private VirtualNetworkModel vnModel1; - private VirtualNetworkModel vnModel2; - private VirtualNetworkModel vnModel3; - - @Override - @Before - public void setUp() throws IOException { - //Network UUIDs - String uuid = UUID.randomUUID().toString(); - String uuid1 = UUID.randomUUID().toString(); - String uuid2 = UUID.randomUUID().toString(); - String uuid3 = UUID.randomUUID().toString(); - - //ContrailManager - ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); - - controller = mock(ModelController.class); - VlanDao vlanDao = mock(VlanDao.class); - - ApiConnector api = mock(ApiConnectorMock.class); - - //Mock classes/methods - when(controller.getManager()).thenReturn(contrailMgr); - when(controller.getApiAccessor()).thenReturn(api); - when(controller.getVlanDao()).thenReturn(vlanDao); - - //Policy References used by vnModel1 - List> policyRefs1 = new ArrayList>(); - ObjectReference objectReference1 = new ObjectReference(); - policyRefs1.add(objectReference1); - - //Policy References used by vnModel2 - List> policyRefs2 = new ArrayList>(); - ObjectReference objectReference2 = new ObjectReference(); - policyRefs2.add(objectReference2); - - //Policy References used by vnModel3 - List> policyRefs3 = new ArrayList>(); - ObjectReference objectReference3 = new ObjectReference(); - objectReference3.setReference(Arrays.asList(""), null, null, UUID.randomUUID().toString()); - - policyRefs3.add(objectReference3); - - //Network to be compared with - VirtualNetwork vn = mock(VirtualNetwork.class); - when(api.findById(VirtualNetwork.class, uuid)).thenReturn(vn); - - //Network to be compared with - VirtualNetwork vn1 = mock(VirtualNetwork.class); - when(api.findById(VirtualNetwork.class, uuid1)).thenReturn(vn1); - when(vn1.getNetworkPolicy()).thenReturn(policyRefs1); - - //Network to be compared to - VirtualNetwork vn2 = mock(VirtualNetwork.class); - when(api.findById(VirtualNetwork.class, uuid2)).thenReturn(vn2); - when(vn2.getNetworkPolicy()).thenReturn(policyRefs2); - - //Network to be compared to - VirtualNetwork vn3 = mock(VirtualNetwork.class); - when(api.findById(VirtualNetwork.class, uuid3)).thenReturn(vn3); - when(vn3.getNetworkPolicy()).thenReturn(policyRefs3); - - //Virtual-Network 1 - NetworkVO network1 = MockNetworkVO.getNetwork(State.Allocated); - - //Virtual-Network 2 - NetworkVO network2 = MockNetworkVO.getNetwork(State.Allocated); - - //Virtual-Network 3 - NetworkVO network3 = MockNetworkVO.getNetwork(State.Allocated); - - when(contrailMgr.getCanonicalName(network1)).thenReturn("testnetwork"); - when(contrailMgr.getProjectId(network1.getDomainId(), network1.getAccountId())).thenReturn("testProjectId"); - - vnModel = new VirtualNetworkModel(network1, uuid, "testnetwork", TrafficType.Guest); - vnModel1 = new VirtualNetworkModel(network1, uuid1, "testnetwork", TrafficType.Guest); - vnModel2 = new VirtualNetworkModel(network2, uuid2, "testnetwork", TrafficType.Guest); - vnModel3 = new VirtualNetworkModel(network3, uuid3, "testnetwork", TrafficType.Guest); - } - - @Test - public void testDBLookup() { - ModelDatabase db = new ModelDatabase(); - NetworkVO network = mock(NetworkVO.class); - VirtualNetworkModel storageModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName, TrafficType.Storage); - db.getVirtualNetworks().add(storageModel); - VirtualNetworkModel mgmtModel = new VirtualNetworkModel(network, null, ContrailManager.managementNetworkName, TrafficType.Management); - db.getVirtualNetworks().add(mgmtModel); - VirtualNetworkModel guestModel1 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test", TrafficType.Guest); - db.getVirtualNetworks().add(guestModel1); - VirtualNetworkModel guestModel2 = new VirtualNetworkModel(network, UUID.randomUUID().toString(), "test", TrafficType.Guest); - db.getVirtualNetworks().add(guestModel2); - assertEquals(4, db.getVirtualNetworks().size()); - assertSame(storageModel, db.lookupVirtualNetwork(null, storageModel.getName(), TrafficType.Storage)); - assertSame(mgmtModel, db.lookupVirtualNetwork(null, mgmtModel.getName(), TrafficType.Management)); - assertSame(guestModel1, db.lookupVirtualNetwork(guestModel1.getUuid(), null, TrafficType.Guest)); - assertSame(guestModel2, db.lookupVirtualNetwork(guestModel2.getUuid(), null, TrafficType.Guest)); - } - - @Test - public void testCreateVirtualNetwork() throws IOException { - - String uuid = UUID.randomUUID().toString(); - ContrailManagerImpl contrailMgr = mock(ContrailManagerImpl.class); - ModelController controller = mock(ModelController.class); - ApiConnector api = new ApiConnectorMock(null, 0); - when(controller.getManager()).thenReturn(contrailMgr); - when(controller.getApiAccessor()).thenReturn(api); - - // Create Virtual-Network (VN) - NetworkVO network = MockNetworkVO.getNetwork(State.Allocated); - - when(contrailMgr.getCanonicalName(network)).thenReturn("testnetwork"); - when(contrailMgr.getProjectId(network.getDomainId(), network.getAccountId())).thenReturn("testProjectId"); - - VirtualNetworkModel vnModel = new VirtualNetworkModel(network, uuid, "testnetwork", TrafficType.Guest); - - assertEquals(vnModel.getName(), "testnetwork"); - assertEquals(vnModel.getUuid(), uuid); - - vnModel.build(controller, network); - try { - vnModel.update(controller); - } catch (Exception ex) { - fail("virtual-network update failed "); - } - assertTrue(vnModel.verify(controller)); - } - - @Test - public void testCompareDifferentVirtualNetwork() throws IOException { - //This one returns false because one network has Policy References - vnModel.read(controller); - - assertFalse(vnModel.compare(controller, vnModel1)); - } - - @Test - public void testCompareSameVirtualNetwork() throws IOException { - //This one returns true because both networks have the same Policy References - vnModel1.read(controller); - - assertTrue(vnModel1.compare(controller, vnModel2)); - } - - @Test - public void testCompareDifferentDeeperVirtualNetwork() throws IOException { - //This one returns false because one network has Policy References - vnModel2.read(controller); - - assertFalse(vnModel2.compare(controller, vnModel3)); - } -} diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/commonContext.xml b/plugins/network-elements/juniper-contrail/src/test/resources/commonContext.xml deleted file mode 100644 index 708b8dbb6c52..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/commonContext.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/contrail.properties b/plugins/network-elements/juniper-contrail/src/test/resources/contrail.properties deleted file mode 100644 index b38adb161e8e..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/contrail.properties +++ /dev/null @@ -1,19 +0,0 @@ -# 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. - -api.hostname= -api.port= diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/db.properties b/plugins/network-elements/juniper-contrail/src/test/resources/db.properties deleted file mode 100644 index 235de858697d..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/db.properties +++ /dev/null @@ -1,68 +0,0 @@ -# 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. - -cluster.servlet.port=9090 - -# CloudStack database settings -db.cloud.username=cloud -db.cloud.password=cloud -db.root.password= -db.cloud.host=localhost -db.cloud.driver=jdbc:mysql -db.cloud.port=3306 -db.cloud.name=cloud - -# CloudStack database tuning parameters -db.cloud.maxActive=250 -db.cloud.maxIdle=30 -db.cloud.maxWait=10000 -db.cloud.autoReconnect=true -db.cloud.validationQuery=SELECT 1 -db.cloud.testOnBorrow=true -db.cloud.testWhileIdle=true -db.cloud.timeBetweenEvictionRunsMillis=40000 -db.cloud.minEvictableIdleTimeMillis=240000 -db.cloud.poolPreparedStatements=false -db.cloud.url.params=prepStmtCacheSize=517&cachePrepStmts=true&prepStmtCacheSqlLimit=4096 - -# usage database settings -db.usage.username=cloud -db.usage.password=cloud -db.usage.host=localhost -# It's not guaranteed that using a different DB provider than the one from the regular cloud DB will work -db.usage.driver=jdbc:mysql -db.usage.port=3306 -db.usage.name=cloud_usage - -# usage database tuning parameters -db.usage.maxActive=100 -db.usage.maxIdle=30 -db.usage.maxWait=10000 -db.usage.autoReconnect=true - -# Simulator database settings -db.simulator.username=cloud -db.simulator.password=cloud -db.simulator.host=localhost -# It's not guaranteed that using a different DB provider than the one from the regular cloud DB will work -db.simulator.driver=jdbc:mysql -db.simulator.port=3306 -db.simulator.name=simulator -db.simulator.maxActive=250 -db.simulator.maxIdle=30 -db.simulator.maxWait=10000 -db.simulator.autoReconnect=true diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/log4j.properties b/plugins/network-elements/juniper-contrail/src/test/resources/log4j.properties deleted file mode 100644 index 27276fc5012b..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/log4j.properties +++ /dev/null @@ -1,34 +0,0 @@ -# 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. - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n -log4j.appender.stdout.threshold=INFO -log4j.rootLogger=INFO, stdout, rolling -log4j.appender.rolling=org.apache.log4j.DailyRollingFileAppender -log4j.appender.rolling.layout=org.apache.log4j.PatternLayout -log4j.appender.rolling.layout.ConversionPattern=%d %-5p [%c{3}] (%t:%x) %m%n -log4j.appender.rolling.file.threshold=DEBUG -log4j.appender.rolling.File=./target/logs/testclient.log -log4j.appender.rolling.DatePattern='.'yyy-MM-dd -log4j.appender.rolling.file.append=false -log4j.category.org.apache=INFO, rolling, stdout -#log4j.category.com.cloud.utils.db.Transaction=ALL -log4j.category.org.apache.cloudstack.network.contrail=ALL -log4j.category.com.cloud.network=ALL diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_start.sh b/plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_start.sh deleted file mode 100644 index 86c8bdaaa9ca..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_start.sh +++ /dev/null @@ -1,51 +0,0 @@ -# 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. - -if [ "$#" -ne 1 ] ; then - echo "Usage: $0 " >&2 - exit 1 -fi - -PORT=$1 -echo "starting mysql on port: "$PORT - -echo "creating temporary mysql db directories /tmp/mysql"$PORT -mkdir /tmp/mysql$PORT -mkdir /tmp/mysql$PORT/data - -echo "install db"; - -mysql_install_db --user=$USER --datadir=/tmp/mysql$PORT/data -mysqld_safe --datadir=/tmp/mysql$PORT/data --socket=/tmp/mysql$PORT/mysqld.sock --port=$PORT --log-error=/tmp/mysql$PORT/mysql.log --pid-file=/tmp/mysql$PORT/mysql.pid --user=$USER & - -attempts=0 -while [ $attempts -lt 30 ]; do - db=$(mysql -h 127.0.0.1 -P $PORT --user=$USER -e "show databases;") - status=$? - if [ $status == 0 ]; then - break - fi - attempts=`expr $attempts + 1` - sleep 1 -done - -echo "new mysql server is started on port "$PORT -echo $db - -echo "commands ...." -echo "to connect(from local host): mysql -h 127.0.0.1 -P "$PORT -echo "to stop: mysqladmin -S /tmp/mysql"$PORT"/mysqld.sock shutdown -u root" diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_stop.sh b/plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_stop.sh deleted file mode 100644 index 7ac304fe6e56..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/mysql_db_stop.sh +++ /dev/null @@ -1,29 +0,0 @@ -# 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. - -if [ "$#" -ne 1 ] ; then - echo "Usage: $0 " >&2 - exit 1 -fi - -echo "Stopping mysql server on port "$1 - -mysqladmin -S /tmp/mysql$1/mysqld.sock shutdown -u root - -rm -rf /tmp/mysql$1 - -echo "Deleting db directories" diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/providerContext.xml b/plugins/network-elements/juniper-contrail/src/test/resources/providerContext.xml deleted file mode 100644 index adf0e1994809..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/providerContext.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/juniper-contrail/src/test/resources/publicNetworkContext.xml b/plugins/network-elements/juniper-contrail/src/test/resources/publicNetworkContext.xml deleted file mode 100644 index a8edec62d1f3..000000000000 --- a/plugins/network-elements/juniper-contrail/src/test/resources/publicNetworkContext.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - diff --git a/plugins/network-elements/nicira-nvp/pom.xml b/plugins/network-elements/nicira-nvp/pom.xml deleted file mode 100644 index 10a584312071..000000000000 --- a/plugins/network-elements/nicira-nvp/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-nvp - Apache CloudStack Plugin - Network Nicira NVP - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - - - org.apache.cloudstack - cloud-utils - ${project.version} - test-jar - test - - - - - integration - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - integration-test - verify - - - - - - - - - diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java deleted file mode 100644 index 1765a8148124..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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.api; - -/** - * - */ -public class ConfigurePortForwardingRulesOnLogicalRouterAnswer extends Answer { - - public ConfigurePortForwardingRulesOnLogicalRouterAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public ConfigurePortForwardingRulesOnLogicalRouterAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java deleted file mode 100644 index 133714e35f7c..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java +++ /dev/null @@ -1,63 +0,0 @@ -// -// 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.api; - -import java.util.List; - -import com.cloud.agent.api.to.PortForwardingRuleTO; - -/** - * - */ -public class ConfigurePortForwardingRulesOnLogicalRouterCommand extends Command { - - private String logicalRouterUuid; - private List rules; - - public ConfigurePortForwardingRulesOnLogicalRouterCommand(final String logicalRouterUuid, final List rules) { - this.logicalRouterUuid = logicalRouterUuid; - this.rules = rules; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(final String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public List getRules() { - return rules; - } - - public void setRules(final List rules) { - this.rules = rules; - } - - /* (non-Javadoc) - * @see com.cloud.agent.api.Command#executeInSequence() - */ - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java deleted file mode 100644 index 9da6caf8b6bd..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.api; - -public class ConfigurePublicIpsOnLogicalRouterAnswer extends Answer { - - public ConfigurePublicIpsOnLogicalRouterAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public ConfigurePublicIpsOnLogicalRouterAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java deleted file mode 100644 index ff81ae465766..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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.api; - -import java.util.List; - -public class ConfigurePublicIpsOnLogicalRouterCommand extends Command { - - private String logicalRouterUuid; - private String l3GatewayServiceUuid; - private List publicCidrs; - - public ConfigurePublicIpsOnLogicalRouterCommand(final String logicalRouterUuid, final String l3GatewayServiceUuid, final List publicCidrs) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - this.publicCidrs = publicCidrs; - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(final String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public String getL3GatewayServiceUuid() { - return l3GatewayServiceUuid; - } - - public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - - public List getPublicCidrs() { - return publicCidrs; - } - - public void setPublicCidrs(final List publicCidrs) { - this.publicCidrs = publicCidrs; - } - - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidAnswer.java deleted file mode 100644 index 46fc8f5476db..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidAnswer.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.api; - -public class ConfigureSharedNetworkUuidAnswer extends Answer { - - public ConfigureSharedNetworkUuidAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public ConfigureSharedNetworkUuidAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidCommand.java deleted file mode 100644 index 4dd361b6b0d2..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkUuidCommand.java +++ /dev/null @@ -1,85 +0,0 @@ -// -// 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.api; - -public class ConfigureSharedNetworkUuidCommand extends Command { - - private String logicalRouterUuid; - private String logicalSwitchUuid; - private String portIpAddress; - private String ownerName; - private long networkId; - - public ConfigureSharedNetworkUuidCommand(final String logicalRouterUuid, final String logicalSwitchUuid, - final String portIpAddress, final String ownerName, final long networkId) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - this.logicalSwitchUuid = logicalSwitchUuid; - this.portIpAddress = portIpAddress; - this.ownerName = ownerName; - this.networkId = networkId; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public void setLogicalSwitchUuid(String logicalSwitchUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - } - - public String getPortIpAddress() { - return portIpAddress; - } - - public void setPortIpAddress(String portIpAddress) { - this.portIpAddress = portIpAddress; - } - - public String getOwnerName() { - return ownerName; - } - - public void setOwnerName(String ownerName) { - this.ownerName = ownerName; - } - - public long getNetworkId() { - return networkId; - } - - public void setNetworkId(long networkId) { - this.networkId = networkId; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdAnswer.java deleted file mode 100644 index 12955693b454..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdAnswer.java +++ /dev/null @@ -1,31 +0,0 @@ -// -// 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.api; - -public class ConfigureSharedNetworkVlanIdAnswer extends Answer { - - public ConfigureSharedNetworkVlanIdAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public ConfigureSharedNetworkVlanIdAnswer(final Command command, final Exception e) { - super(command, e); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdCommand.java deleted file mode 100644 index c6837dd1b09b..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureSharedNetworkVlanIdCommand.java +++ /dev/null @@ -1,84 +0,0 @@ -// -// 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.api; - -public class ConfigureSharedNetworkVlanIdCommand extends Command { - - private String logicalSwitchUuid; - private String l2GatewayServiceUuid; - private long vlanId; - private String ownerName; - private long networkId; - - public ConfigureSharedNetworkVlanIdCommand(final String logicalSwitchUuid, final String l2GatewayServiceUuid, - final long vlanId, final String ownerName, final long networkId) { - this.logicalSwitchUuid = logicalSwitchUuid; - this.l2GatewayServiceUuid = l2GatewayServiceUuid; - this.vlanId = vlanId; - this.ownerName = ownerName; - this.networkId = networkId; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public void setLogicalSwitchUuid(String logicalSwitchUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - } - - public String getL2GatewayServiceUuid() { - return l2GatewayServiceUuid; - } - - public void setL2GatewayServiceUuid(String l2GatewayServiceUuid) { - this.l2GatewayServiceUuid = l2GatewayServiceUuid; - } - - public long getVlanId() { - return vlanId; - } - - public void setVlanId(long vlanId) { - this.vlanId = vlanId; - } - - public String getOwnerName() { - return ownerName; - } - - public void setOwnerName(String ownerName) { - this.ownerName = ownerName; - } - - public long getNetworkId() { - return networkId; - } - - public void setNetworkId(long networkId) { - this.networkId = networkId; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java deleted file mode 100644 index 907449170fc9..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.api; - -/** - * - */ -public class ConfigureStaticNatRulesOnLogicalRouterAnswer extends Answer { - - /** - * @param command - * @param success - * @param details - */ - public ConfigureStaticNatRulesOnLogicalRouterAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - /** - * @param command - * @param e - */ - public ConfigureStaticNatRulesOnLogicalRouterAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java deleted file mode 100644 index b5434b34e158..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java +++ /dev/null @@ -1,65 +0,0 @@ -// -// 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.api; - -import java.util.List; - -import com.cloud.agent.api.to.StaticNatRuleTO; - -/** - * - */ -public class ConfigureStaticNatRulesOnLogicalRouterCommand extends Command { - - private String logicalRouterUuid; - private List rules; - - public ConfigureStaticNatRulesOnLogicalRouterCommand(final String logicalRouterUuid, final List rules) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - this.rules = rules; - - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(final String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public List getRules() { - return rules; - } - - public void setRules(final List rules) { - this.rules = rules; - } - - /* (non-Javadoc) - * @see com.cloud.agent.api.Command#executeInSequence() - */ - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java deleted file mode 100644 index 0172891d4df7..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterAnswer.java +++ /dev/null @@ -1,42 +0,0 @@ -// -// 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.api; - -/** - * - */ -public class CreateLogicalRouterAnswer extends Answer { - - private String logicalRouterUuid; - - public CreateLogicalRouterAnswer(final Command command, final boolean success, final String details, final String logicalRouterUuid) { - super(command, success, details); - this.logicalRouterUuid = logicalRouterUuid; - } - - public CreateLogicalRouterAnswer(final Command command, final Exception e) { - super(command, e); - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java deleted file mode 100644 index ff12b8d58645..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalRouterCommand.java +++ /dev/null @@ -1,116 +0,0 @@ -// -// 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.api; - -/** - * - */ -public class CreateLogicalRouterCommand extends Command { - private String gatewayServiceUuid; - private String logicalSwitchUuid; - private long vlanId; - private String name; - private String ownerName; - private String publicIpCidr; - private String publicNextHop; - private String internalIpCidr; - - public CreateLogicalRouterCommand(final String gatewayServiceUuid, final long vlanId, final String logicalSwitchUuid, final String name, final String publicIpCidr, - final String publicNextHop, final String internalIpCidr, final String ownerName) { - super(); - this.gatewayServiceUuid = gatewayServiceUuid; - this.logicalSwitchUuid = logicalSwitchUuid; - this.vlanId = vlanId; - this.name = name; - this.ownerName = ownerName; - this.publicIpCidr = publicIpCidr; - this.publicNextHop = publicNextHop; - this.internalIpCidr = internalIpCidr; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getGatewayServiceUuid() { - return gatewayServiceUuid; - } - - public void setGatewayServiceUuid(final String gatewayServiceUuid) { - this.gatewayServiceUuid = gatewayServiceUuid; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public void setLogicalSwitchUuid(final String logicalSwitchUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - } - - public long getVlanId() { - return vlanId; - } - - public void setVlanId(final long vlanId) { - this.vlanId = vlanId; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getOwnerName() { - return ownerName; - } - - public void setOwnerName(final String ownerName) { - this.ownerName = ownerName; - } - - public String getPublicIpCidr() { - return publicIpCidr; - } - - public void setPublicIpCidr(final String publicIpCidr) { - this.publicIpCidr = publicIpCidr; - } - - public String getInternalIpCidr() { - return internalIpCidr; - } - - public void setInternalIpCidr(final String internalIpCidr) { - this.internalIpCidr = internalIpCidr; - } - - public String getPublicNextHop() { - return publicNextHop; - } - - public void setPublicNextHop(final String publicNextHop) { - this.publicNextHop = publicNextHop; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java deleted file mode 100644 index ee9924e79a07..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchAnswer.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class CreateLogicalSwitchAnswer extends Answer { - private String logicalSwitchUuid; - - public CreateLogicalSwitchAnswer(final Command command, final boolean success, final String details, final String logicalSwitchUuid) { - super(command, success, details); - this.logicalSwitchUuid = logicalSwitchUuid; - } - - public CreateLogicalSwitchAnswer(final Command command, final Exception e) { - super(command, e); - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java deleted file mode 100644 index 5dc8616034ab..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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.api; - -public class CreateLogicalSwitchCommand extends Command { - - private final String transportUuid; - private final String transportType; - private final String name; - private final String ownerName; - - public CreateLogicalSwitchCommand(final String transportUuid, final String transportType, final String name, final String ownerName) { - this.transportUuid = transportUuid; - this.transportType = transportType; - this.name = name; - this.ownerName = ownerName; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getTransportUuid() { - return transportUuid; - } - - public String getTransportType() { - return transportType; - } - - public String getName() { - return name; - } - - public String getOwnerName() { - return ownerName; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java deleted file mode 100644 index 8b093897e454..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortAnswer.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class CreateLogicalSwitchPortAnswer extends Answer { - private String logicalSwitchPortUuid; - - public CreateLogicalSwitchPortAnswer(final Command command, final boolean success, final String details, final String localSwitchPortUuid) { - super(command, success, details); - logicalSwitchPortUuid = localSwitchPortUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwitchPortUuid; - } - - public CreateLogicalSwitchPortAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java deleted file mode 100644 index 6bc578fae6fd..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/CreateLogicalSwitchPortCommand.java +++ /dev/null @@ -1,56 +0,0 @@ -// -// 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.api; - -public class CreateLogicalSwitchPortCommand extends Command { - private final String logicalSwitchUuid; - private final String attachmentUuid; - private final String ownerName; - private final String nicName; - - public CreateLogicalSwitchPortCommand(final String logicalSwitchUuid, final String attachmentUuid, final String ownerName, final String nicName) { - this.logicalSwitchUuid = logicalSwitchUuid; - this.attachmentUuid = attachmentUuid; - this.ownerName = ownerName; - this.nicName = nicName; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public String getAttachmentUuid() { - return attachmentUuid; - } - - public String getOwnerName() { - return ownerName; - } - - public String getNicName() { - return nicName; - } - - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java deleted file mode 100644 index f7f101d029fc..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterAnswer.java +++ /dev/null @@ -1,34 +0,0 @@ -// -// 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.api; - -/** - * - */ -public class DeleteLogicalRouterAnswer extends Answer { - - public DeleteLogicalRouterAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public DeleteLogicalRouterAnswer(final Command command, final Exception e) { - super(command, e); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java deleted file mode 100644 index 8fd14e95ef41..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.api; - -/** - * - */ -public class DeleteLogicalRouterCommand extends Command { - - private final String logicalRouterUuid; - - public DeleteLogicalRouterCommand(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - /* (non-Javadoc) - * @see com.cloud.agent.api.Command#executeInSequence() - */ - @Override - public boolean executeInSequence() { - return false; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortAnswer.java deleted file mode 100644 index 2850047aedad..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortAnswer.java +++ /dev/null @@ -1,31 +0,0 @@ -// -// 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.api; - -public class DeleteLogicalRouterPortAnswer extends Answer { - - public DeleteLogicalRouterPortAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public DeleteLogicalRouterPortAnswer(final Command command, final Exception e) { - super(command, e); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortCommand.java deleted file mode 100644 index 729535831f31..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalRouterPortCommand.java +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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.api; - -public class DeleteLogicalRouterPortCommand extends Command { - - private String logicalRouterUuid; - private String logicalRouterPortUuid; - - public DeleteLogicalRouterPortCommand(String logicalRouterUuid, String logicalRouterPortUuid) { - this.logicalRouterUuid = logicalRouterUuid; - this.logicalRouterPortUuid = logicalRouterPortUuid; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public String getLogicalRouterPortUuid() { - return logicalRouterPortUuid; - } - - public void setLogicalRouterPortUuid(String logicalRouterPortUuid) { - this.logicalRouterPortUuid = logicalRouterPortUuid; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java deleted file mode 100644 index e2c483f8e543..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchAnswer.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.api; - -public class DeleteLogicalSwitchAnswer extends Answer { - - public DeleteLogicalSwitchAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public DeleteLogicalSwitchAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java deleted file mode 100644 index dbfefe2e7a55..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchCommand.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class DeleteLogicalSwitchCommand extends Command { - - private final String logicalSwitchUuid; - - public DeleteLogicalSwitchCommand(final String logicalSwitchUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java deleted file mode 100644 index 1cd87ea90d96..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortAnswer.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.api; - -public class DeleteLogicalSwitchPortAnswer extends Answer { - - public DeleteLogicalSwitchPortAnswer(final Command command, final boolean success, final String details) { - super(command, success, details); - } - - public DeleteLogicalSwitchPortAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java deleted file mode 100644 index 4a5e6076d581..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/DeleteLogicalSwitchPortCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.api; - -public class DeleteLogicalSwitchPortCommand extends Command { - private final String logicalSwitchUuid; - private final String logicalSwithPortUuid; - - public DeleteLogicalSwitchPortCommand(final String logicalSwitchUuid, final String logicalSwitchPortUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - logicalSwithPortUuid = logicalSwitchPortUuid; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwithPortUuid; - } - - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceAnswer.java deleted file mode 100644 index 16f24eb7e198..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceAnswer.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class FindL2GatewayServiceAnswer extends Answer { - - private String gatewayServiceUuid; - - public FindL2GatewayServiceAnswer(final Command command, final boolean success, final String details, final String gatewayServiceUuid) { - super(command, success, details); - this.gatewayServiceUuid = gatewayServiceUuid; - } - - public FindL2GatewayServiceAnswer(final Command command, final Exception e) { - super(command, e); - } - - public String getGatewayServiceUuid() { - return gatewayServiceUuid; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceCommand.java deleted file mode 100644 index a3ec1dcc18f4..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindL2GatewayServiceCommand.java +++ /dev/null @@ -1,46 +0,0 @@ -// -// 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.api; - -import com.cloud.network.nicira.GatewayServiceConfig; -import com.cloud.network.nicira.L2GatewayServiceConfig; - -public class FindL2GatewayServiceCommand extends Command { - - private L2GatewayServiceConfig gatewayServiceConfig; - - public FindL2GatewayServiceCommand(L2GatewayServiceConfig config) { - this.gatewayServiceConfig = config; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public GatewayServiceConfig getGatewayServiceConfig() { - return gatewayServiceConfig; - } - - public void setGatewayServiceConfig(L2GatewayServiceConfig gatewayServiceConfig) { - this.gatewayServiceConfig = gatewayServiceConfig; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortAnswer.java deleted file mode 100644 index 2ec211b41324..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortAnswer.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class FindLogicalRouterPortAnswer extends Answer { - - private String logicalRouterPortUuid; - - public FindLogicalRouterPortAnswer(final Command command, final boolean success, final String details, final String lRouterPortUuid) { - super(command, success, details); - this.logicalRouterPortUuid = lRouterPortUuid; - } - - public FindLogicalRouterPortAnswer(final Command command, final Exception e) { - super(command, e); - } - - public String getLogicalRouterPortUuid() { - return logicalRouterPortUuid; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortCommand.java deleted file mode 100644 index 965f65b8c137..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalRouterPortCommand.java +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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.api; - -public class FindLogicalRouterPortCommand extends Command { - - private String logicalRouterUuid; - private String attachmentLswitchUuid; - - public FindLogicalRouterPortCommand(String logicalRouterUuid) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - } - - public FindLogicalRouterPortCommand(String logicalRouterUuid, String attachmentLswitchUuid) { - super(); - this.logicalRouterUuid = logicalRouterUuid; - this.attachmentLswitchUuid = attachmentLswitchUuid; - } - - @Override - public boolean executeInSequence() { - return false; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public String getAttachmentLswitchUuid() { - return attachmentLswitchUuid; - } - - public void setAttachmentLswitchUuid(String attachmentLswitchUuid) { - this.attachmentLswitchUuid = attachmentLswitchUuid; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java deleted file mode 100644 index 0524531abe81..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortAnswer.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class FindLogicalSwitchPortAnswer extends Answer { - private String logicalSwitchPortUuid; - - public FindLogicalSwitchPortAnswer(final Command command, final boolean success, final String details, final String localSwitchPortUuid) { - super(command, success, details); - logicalSwitchPortUuid = localSwitchPortUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwitchPortUuid; - } - - public FindLogicalSwitchPortAnswer(final Command command, final Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java deleted file mode 100644 index ee00bd24a3c4..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/FindLogicalSwitchPortCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.api; - -public class FindLogicalSwitchPortCommand extends Command { - private final String logicalSwitchUuid; - private final String logicalSwitchPortUuid; - - public FindLogicalSwitchPortCommand(String logicalSwitchUuid, String logicalSwitchPortUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - this.logicalSwitchPortUuid = logicalSwitchPortUuid; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwitchPortUuid; - } - - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java deleted file mode 100644 index 9597d2f668f7..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/StartupNiciraNvpCommand.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// 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.api; - -import com.cloud.host.Host; - -public class StartupNiciraNvpCommand extends StartupCommand { - - public StartupNiciraNvpCommand() { - super(Host.Type.L2Networking); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java deleted file mode 100644 index 14717232d762..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortAnswer.java +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.api; - -public class UpdateLogicalSwitchPortAnswer extends Answer { - private String logicalSwitchPortUuid; - - public UpdateLogicalSwitchPortAnswer(Command command, boolean success, String details, String localSwitchPortUuid) { - super(command, success, details); - logicalSwitchPortUuid = localSwitchPortUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwitchPortUuid; - } - - public UpdateLogicalSwitchPortAnswer(Command command, Exception e) { - super(command, e); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java deleted file mode 100644 index 91682a1acad2..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/agent/api/UpdateLogicalSwitchPortCommand.java +++ /dev/null @@ -1,63 +0,0 @@ -// -// 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.api; - -public class UpdateLogicalSwitchPortCommand extends Command { - private final String logicalSwitchUuid; - private final String logicalSwitchPortUuid; - private final String attachmentUuid; - private final String ownerName; - private final String nicName; - - public UpdateLogicalSwitchPortCommand(final String logicalSwitchPortUuid, final String logicalSwitchUuid, final String attachmentUuid, final String ownerName, - final String nicName) { - this.logicalSwitchUuid = logicalSwitchUuid; - this.logicalSwitchPortUuid = logicalSwitchPortUuid; - this.attachmentUuid = attachmentUuid; - this.ownerName = ownerName; - this.nicName = nicName; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwitchPortUuid; - } - - public String getAttachmentUuid() { - return attachmentUuid; - } - - public String getOwnerName() { - return ownerName; - } - - public String getNicName() { - return nicName; - } - - @Override - public boolean executeInSequence() { - return false; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java deleted file mode 100644 index 3aeba5127d03..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java +++ /dev/null @@ -1,158 +0,0 @@ -// -// 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.api.commands; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.NiciraNvpDeviceResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.network.element.NiciraNvpElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "addNiciraNvpDevice", responseObject = NiciraNvpDeviceResponse.class, description = "Adds a Nicira NVP device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { - @Inject - protected NiciraNvpElementService niciraNvpElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, - type = CommandType.UUID, - entityType = PhysicalNetworkResponse.class, - required = true, - description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname of ip address of the Nicira NVP Controller.") - private String host; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to access the Nicira Controller API") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to access the Nicira Controller API") - private String password; - - @Parameter(name = ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID, - type = CommandType.STRING, - required = true, - description = "The Transportzone UUID configured on the Nicira Controller") - private String transportzoneuuid; - - @Parameter(name = ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID, - type = CommandType.STRING, - required = false, - description = "The L3 Gateway Service UUID configured on the Nicira Controller") - private String l3gatewayserviceuuid; - - @Parameter(name = ApiConstants.NICIRA_NVP_L2_GATEWAYSERVICE_UUID, - type = CommandType.STRING, - required = false, - description = "The L2 Gateway Service UUID configured on the Nicira Controller") - private String l2gatewayserviceuuid; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public String getHost() { - return host; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getTransportzoneUuid() { - return transportzoneuuid; - } - - public String getL3GatewayServiceUuid() { - return l3gatewayserviceuuid; - } - - public String getL2GatewayServiceUuid() { - return l2gatewayserviceuuid; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - NiciraNvpDeviceVO niciraNvpDeviceVO = niciraNvpElementService.addNiciraNvpDevice(this); - if (niciraNvpDeviceVO != null) { - NiciraNvpDeviceResponse response = niciraNvpElementService.createNiciraNvpDeviceResponse(niciraNvpDeviceVO); - response.setObjectName("niciranvpdevice"); - response.setResponseName(getCommandName()); - setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Nicira NVP device due to internal error."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_ADD; - } - - @Override - public String getEventDescription() { - return "Adding a Nicira Nvp Controller"; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java deleted file mode 100644 index 54b172e96511..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java +++ /dev/null @@ -1,106 +0,0 @@ -// -// 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.api.commands; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseAsyncCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; - -import com.cloud.api.response.NiciraNvpDeviceResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.element.NiciraNvpElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "deleteNiciraNvpDevice", responseObject = SuccessResponse.class, description = " delete a nicira nvp device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { - @Inject - protected NiciraNvpElementService niciraNvpElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID, - type = CommandType.UUID, - entityType = NiciraNvpDeviceResponse.class, - required = true, - description = "Nicira device ID") - private Long niciraNvpDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getNiciraNvpDeviceId() { - return niciraNvpDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - boolean result = niciraNvpElementService.deleteNiciraNvpDevice(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - setResponseObject(response); - } else { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete Nicira device."); - } - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public String getEventType() { - return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_DELETE; - } - - @Override - public String getEventDescription() { - return "Deleting Nicira NVP Controller with ID: " + getResourceUuid(ApiConstants.NICIRA_NVP_DEVICE_ID); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java deleted file mode 100644 index 82293290de5c..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java +++ /dev/null @@ -1,109 +0,0 @@ -// -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ResponseObject.ResponseView; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.NetworkResponse; - -import com.cloud.api.response.NiciraNvpDeviceResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.element.NiciraNvpElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listNiciraNvpDeviceNetworks", responseObject = NetworkResponse.class, description = "Lists network that are using a nicira nvp device", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { - - private static final String s_name = "listniciranvpdevicenetworks"; - @Inject - protected NiciraNvpElementService niciraNvpElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID, - type = CommandType.UUID, - entityType = NiciraNvpDeviceResponse.class, - required = true, - description = "nicira nvp device ID") - private Long niciraNvpDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getNiciraNvpDeviceId() { - return niciraNvpDeviceId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List networks = niciraNvpElementService.listNiciraNvpDeviceNetworks(this); - ListResponse response = new ListResponse(); - List networkResponses = new ArrayList(); - - if (networks != null && !networks.isEmpty()) { - for (Network network : networks) { - NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Full, network); - networkResponses.add(networkResponse); - } - } - - response.setResponses(networkResponses); - response.setResponseName(getCommandName()); - setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java deleted file mode 100644 index a30d09c19c60..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java +++ /dev/null @@ -1,108 +0,0 @@ -// -// 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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseListCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.api.response.PhysicalNetworkResponse; - -import com.cloud.api.response.NiciraNvpDeviceResponse; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.network.element.NiciraNvpElementService; -import com.cloud.utils.exception.CloudRuntimeException; - -@APICommand(name = "listNiciraNvpDevices", responseObject = NiciraNvpDeviceResponse.class, description = "Lists Nicira NVP devices", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListNiciraNvpDevicesCmd extends BaseListCmd { - private static final String s_name = "listniciranvpdeviceresponse"; - - @Inject - protected NiciraNvpElementService niciraNvpElementService; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "The Physical Network ID") - private Long physicalNetworkId; - - @Parameter(name = ApiConstants.NICIRA_NVP_DEVICE_ID, type = CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, description = "nicira nvp device ID") - private Long niciraNvpDeviceId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getNiciraNvpDeviceId() { - return niciraNvpDeviceId; - } - - public Long getPhysicalNetworkId() { - return physicalNetworkId; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { - try { - List niciraDevices = niciraNvpElementService.listNiciraNvpDevices(this); - ListResponse response = new ListResponse(); - List niciraDevicesResponse = new ArrayList(); - - if (niciraDevices != null && !niciraDevices.isEmpty()) { - for (NiciraNvpDeviceVO niciraDeviceVO : niciraDevices) { - NiciraNvpDeviceResponse niciraDeviceResponse = niciraNvpElementService.createNiciraNvpDeviceResponse(niciraDeviceVO); - niciraDevicesResponse.add(niciraDeviceResponse); - } - } - - response.setResponses(niciraDevicesResponse); - response.setResponseName(getCommandName()); - setResponseObject(response); - } catch (InvalidParameterValueException invalidParamExcp) { - throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage()); - } catch (CloudRuntimeException runtimeExcp) { - throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java deleted file mode 100644 index ceebcdf8808c..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/api/response/NiciraNvpDeviceResponse.java +++ /dev/null @@ -1,96 +0,0 @@ -// -// 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.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.serializer.Param; - -@EntityReference(value = NiciraNvpDeviceVO.class) -public class NiciraNvpDeviceResponse extends BaseResponse { - @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID) - @Param(description = "Device ID of the Nicire Nvp") - private String id; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) - @Param(description = "The physical Network to which this Nirica Nvp belongs to") - private String physicalNetworkId; - - @SerializedName(ApiConstants.PROVIDER) - @Param(description = "Name of the provider") - private String providerName; - - @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_NAME) - @Param(description = "Device name") - private String deviceName; - - @SerializedName(ApiConstants.HOST_NAME) - @Param(description = "The controller IP address") - private String hostName; - - @SerializedName(ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID) - @Param(description = "The transport zone UUID") - private String transportZoneUuid; - - @SerializedName(ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID) - @Param(description = "This L3 gateway service UUID") - private String l3GatewayServiceUuid; - - @SerializedName(ApiConstants.NICIRA_NVP_L2_GATEWAYSERVICE_UUID) - @Param(description = "This L2 gateway service UUID") - private String l2GatewayServiceUuid; - - public void setId(String nvpDeviceId) { - this.id = nvpDeviceId; - } - - public void setPhysicalNetworkId(final String physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } - - public void setProviderName(final String providerName) { - this.providerName = providerName; - } - - public void setDeviceName(final String deviceName) { - this.deviceName = deviceName; - } - - public void setHostName(final String hostName) { - this.hostName = hostName; - } - - public void setTransportZoneUuid(final String transportZoneUuid) { - this.transportZoneUuid = transportZoneUuid; - } - - public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - - public void setL2GatewayServiceUuid(final String l2GatewayServiceUuid) { - this.l2GatewayServiceUuid = l2GatewayServiceUuid; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java deleted file mode 100644 index 431e8558ae30..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpDeviceVO.java +++ /dev/null @@ -1,99 +0,0 @@ -// -// 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.network; - -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; - -@Entity -@Table(name = "external_nicira_nvp_devices") -public class NiciraNvpDeviceVO implements InternalIdentity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "host_id") - private long hostId; - - @Column(name = "physical_network_id") - private long physicalNetworkId; - - @Column(name = "provider_name") - private String providerName; - - @Column(name = "device_name") - private String deviceName; - - public NiciraNvpDeviceVO() { - uuid = UUID.randomUUID().toString(); - } - - public NiciraNvpDeviceVO(final long hostId, final long physicalNetworkId, final String providerName, final String deviceName) { - super(); - this.hostId = hostId; - this.physicalNetworkId = physicalNetworkId; - this.providerName = providerName; - this.deviceName = deviceName; - uuid = UUID.randomUUID().toString(); - } - - @Override - public long getId() { - return id; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public long getPhysicalNetworkId() { - return physicalNetworkId; - } - - public long getHostId() { - return hostId; - } - - public String getProviderName() { - return providerName; - } - - public String getDeviceName() { - return deviceName; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java deleted file mode 100644 index 9b137806a4a8..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpNicMappingVO.java +++ /dev/null @@ -1,87 +0,0 @@ -// -// 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.network; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; - -@Entity -@Table(name = "nicira_nvp_nic_map") -public class NiciraNvpNicMappingVO implements InternalIdentity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "logicalswitch") - private String logicalSwitchUuid; - - @Column(name = "logicalswitchport") - private String logicalSwitchPortUuid; - - @Column(name = "nic") - private String nicUuid; - - public NiciraNvpNicMappingVO() { - } - - public NiciraNvpNicMappingVO(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final String nicUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - this.logicalSwitchPortUuid = logicalSwitchPortUuid; - this.nicUuid = nicUuid; - } - - public String getLogicalSwitchUuid() { - return logicalSwitchUuid; - } - - public void setLogicalSwitchUuid(final String logicalSwitchUuid) { - this.logicalSwitchUuid = logicalSwitchUuid; - } - - public String getLogicalSwitchPortUuid() { - return logicalSwitchPortUuid; - } - - public void setLogicalSwitchPortUuid(final String logicalSwitchPortUuid) { - this.logicalSwitchPortUuid = logicalSwitchPortUuid; - } - - public String getNicUuid() { - return nicUuid; - } - - public void setNicUuid(String nicUuid) { - this.nicUuid = nicUuid; - } - - @Override - public long getId() { - return id; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java deleted file mode 100644 index 9fae3cd74657..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/NiciraNvpRouterMappingVO.java +++ /dev/null @@ -1,85 +0,0 @@ -// -// 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.network; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; - -@Entity -@Table(name = "nicira_nvp_router_map") -public class NiciraNvpRouterMappingVO implements InternalIdentity { - //FIXME the ddl for this table should be in one of the upgrade scripts - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "logicalrouter_uuid") - private String logicalRouterUuid; - - @Column(name = "network_id") - private long networkId; - - public NiciraNvpRouterMappingVO() { - } - - public NiciraNvpRouterMappingVO(final String logicalRouterUuid, final long networkId) { - this.logicalRouterUuid = logicalRouterUuid; - this.networkId = networkId; - } - - public NiciraNvpRouterMappingVO(final long id, final String logicalRouterUuid, final long networkId) { - this.id = id; - this.logicalRouterUuid = logicalRouterUuid; - this.networkId = networkId; - } - - @Override - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getLogicalRouterUuid() { - return logicalRouterUuid; - } - - public void setLogicalRouterUuid(final String logicalRouterUuid) { - this.logicalRouterUuid = logicalRouterUuid; - } - - public long getNetworkId() { - return networkId; - } - - public void setNetworkId(final long networkId) { - this.networkId = networkId; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java deleted file mode 100644 index f2a9754d5068..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDao.java +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.utils.db.GenericDao; - -public interface NiciraNvpDao extends GenericDao { - /** - * list all the nicira nvp devices added in to this physical network - * @param physicalNetworkId physical Network Id - * @return list of NiciraNvpDeviceVO for this physical network. - */ - List listByPhysicalNetwork(long physicalNetworkId); - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java deleted file mode 100644 index 34df10e2cf43..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpDaoImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class NiciraNvpDaoImpl extends GenericDaoBase implements NiciraNvpDao { - - protected final SearchBuilder physicalNetworkIdSearch; - - public NiciraNvpDaoImpl() { - physicalNetworkIdSearch = createSearchBuilder(); - physicalNetworkIdSearch.and("physicalNetworkId", physicalNetworkIdSearch.entity().getPhysicalNetworkId(), Op.EQ); - physicalNetworkIdSearch.done(); - } - - @Override - public List listByPhysicalNetwork(final long physicalNetworkId) { - SearchCriteria sc = physicalNetworkIdSearch.create(); - sc.setParameters("physicalNetworkId", physicalNetworkId); - return search(sc, null); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java deleted file mode 100644 index ff81b7598ede..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDao.java +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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.network.dao; - -import com.cloud.network.NiciraNvpNicMappingVO; -import com.cloud.utils.db.GenericDao; - -public interface NiciraNvpNicMappingDao extends GenericDao { - - /** find the mapping for a nic - * @param nicUuid the Uuid of a nic attached to a logical switch port - * @return NiciraNvpNicMapping for this nic uuid or null if it does not exist - */ - public NiciraNvpNicMappingVO findByNicUuid(String nicUuid); -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java deleted file mode 100644 index 0d256b0d51d0..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpNicMappingDaoImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -// -// 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.network.dao; - - -import org.springframework.stereotype.Component; - -import com.cloud.network.NiciraNvpNicMappingVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class NiciraNvpNicMappingDaoImpl extends GenericDaoBase implements NiciraNvpNicMappingDao { - - protected final SearchBuilder nicSearch; - - public NiciraNvpNicMappingDaoImpl() { - nicSearch = createSearchBuilder(); - nicSearch.and("nicUuid", nicSearch.entity().getNicUuid(), Op.EQ); - nicSearch.done(); - } - - @Override - public NiciraNvpNicMappingVO findByNicUuid(final String nicUuid) { - SearchCriteria sc = nicSearch.create(); - sc.setParameters("nicUuid", nicUuid); - return findOneBy(sc); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java deleted file mode 100644 index b7e999b30b76..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDao.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// 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.network.dao; - -import com.cloud.network.NiciraNvpRouterMappingVO; -import com.cloud.utils.db.GenericDao; - -public interface NiciraNvpRouterMappingDao extends GenericDao { - - public NiciraNvpRouterMappingVO findByNetworkId(long id); - - public boolean existsMappingForNetworkId(long id); -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java deleted file mode 100644 index ef6acb40df96..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -// -// 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.network.dao; - -import java.util.List; - -import org.springframework.stereotype.Component; - -import com.cloud.network.NiciraNvpRouterMappingVO; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -@Component -public class NiciraNvpRouterMappingDaoImpl extends GenericDaoBase implements NiciraNvpRouterMappingDao { - - protected final SearchBuilder networkSearch; - - public NiciraNvpRouterMappingDaoImpl() { - networkSearch = createSearchBuilder(); - networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ); - networkSearch.done(); - } - - @Override - public NiciraNvpRouterMappingVO findByNetworkId(final long id) { - SearchCriteria sc = networkSearch.create(); - sc.setParameters("network_id", id); - return findOneBy(sc); - } - - @Override - public boolean existsMappingForNetworkId(long id) { - SearchCriteria sc = networkSearch.create(); - sc.setParameters("network_id", id); - List mappings = search(sc, null); - return mappings.size() > 0; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java deleted file mode 100644 index 278d058a2892..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElement.java +++ /dev/null @@ -1,918 +0,0 @@ -// -// 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.network.element; - -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.springframework.stereotype.Component; -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; -import com.cloud.agent.api.ConfigureSharedNetworkUuidAnswer; -import com.cloud.agent.api.ConfigureSharedNetworkUuidCommand; -import com.cloud.agent.api.ConfigureSharedNetworkVlanIdAnswer; -import com.cloud.agent.api.ConfigureSharedNetworkVlanIdCommand; -import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand; -import com.cloud.agent.api.CreateLogicalRouterAnswer; -import com.cloud.agent.api.CreateLogicalRouterCommand; -import com.cloud.agent.api.CreateLogicalSwitchPortAnswer; -import com.cloud.agent.api.CreateLogicalSwitchPortCommand; -import com.cloud.agent.api.DeleteLogicalRouterAnswer; -import com.cloud.agent.api.DeleteLogicalRouterCommand; -import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchPortCommand; -import com.cloud.agent.api.FindLogicalSwitchPortAnswer; -import com.cloud.agent.api.FindLogicalSwitchPortCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupNiciraNvpCommand; -import com.cloud.agent.api.UpdateLogicalSwitchPortCommand; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddNiciraNvpDeviceCmd; -import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd; -import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd; -import com.cloud.api.commands.ListNiciraNvpDevicesCmd; -import com.cloud.api.response.NiciraNvpDeviceResponse; -import com.cloud.configuration.ConfigurationManager; -import com.cloud.dc.Vlan; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.DetailVO; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.IpAddress; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.network.NiciraNvpNicMappingVO; -import com.cloud.network.NiciraNvpRouterMappingVO; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.NiciraNvpDao; -import com.cloud.network.dao.NiciraNvpNicMappingDao; -import com.cloud.network.dao.NiciraNvpRouterMappingDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNat; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.resource.ResourceState; -import com.cloud.resource.ResourceStateAdapter; -import com.cloud.resource.ServerResource; -import com.cloud.resource.UnableDeleteHostException; -import com.cloud.user.Account; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallback; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.NetUtils; -import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.NicDao; - -@Component -public class NiciraNvpElement extends AdapterBase implements ConnectivityProvider, SourceNatServiceProvider, PortForwardingServiceProvider, StaticNatServiceProvider, -NiciraNvpElementService, ResourceStateAdapter, IpDeployer { - - private static final int MAX_PORT = 65535; - private static final int MIN_PORT = 0; - - - private static final Map> capabilities = setCapabilities(); - - @Inject - protected NicDao nicDao; - @Inject - protected ResourceManager resourceMgr; - @Inject - protected PhysicalNetworkDao physicalNetworkDao; - @Inject - protected PhysicalNetworkServiceProviderDao physicalNetworkServiceProviderDao; - @Inject - protected NiciraNvpDao niciraNvpDao; - @Inject - protected HostDetailsDao hostDetailsDao; - @Inject - protected HostDao hostDao; - @Inject - protected AgentManager agentMgr; - @Inject - protected NiciraNvpNicMappingDao niciraNvpNicMappingDao; - @Inject - protected NiciraNvpRouterMappingDao niciraNvpRouterMappingDao; - @Inject - protected NetworkDao networkDao; - @Inject - protected NetworkOrchestrationService networkManager; - @Inject - protected NetworkModel networkModel; - @Inject - protected ConfigurationManager configMgr; - @Inject - protected NetworkServiceMapDao ntwkSrvcDao; - @Inject - protected VlanDao vlanDao; - @Inject - protected IpAddressManager ipAddrMgr; - - @Override - public Map> getCapabilities() { - return capabilities; - } - - @Override - public Provider getProvider() { - return Provider.NiciraNvp; - } - - protected boolean canHandle(Network network, Service service) { - logger.debug(String.format("Checking if NiciraNvpElement can handle service %s on network %s", service.getName(), network)); - if (network.getBroadcastDomainType() != BroadcastDomainType.Lswitch) { - return false; - } - - if (!networkModel.isProviderForNetwork(getProvider(), network.getId())) { - logger.debug(String.format("NiciraNvpElement is not a provider for network %s", network)); - return false; - } - - if (!ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), service, Network.Provider.NiciraNvp)) { - logger.debug(String.format("NiciraNvpElement can't provide the %s service on network %s", service.getName(), network)); - return false; - } - - return true; - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - super.configure(name, params); - resourceMgr.registerResourceStateAdapter(name, this); - return true; - } - - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - logger.debug(String.format("entering NiciraNvpElement implement function for network %s (state %s)", network, network.getState())); - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - if (network.getBroadcastUri() == null) { - logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); - return false; - } - - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - hostDao.loadDetails(niciraNvpHost); - - Account owner = context.getAccount(); - - /* - * TODO Shouldn't we lock the network as we might need to do - * multiple operations that should be done only once. - */ - - if (network.getGuestType().equals(GuestType.Shared)){ - //Support Shared Networks - String lSwitchUuid = BroadcastDomainType.getValue(network.getBroadcastUri()); - String ownerName = context.getDomain().getName() + "-" + context.getAccount().getAccountName(); - return sharedNetworkSupport(network, lSwitchUuid, ownerName, niciraNvpHost); - } - else if (network.getGuestType().equals(GuestType.Isolated) && networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.NiciraNvp)) { - // Implement SourceNat immediately as we have al the info already - logger.debug("Apparently we are supposed to provide SourceNat on this network"); - - PublicIp sourceNatIp = ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network); - String publicCidr = sourceNatIp.getAddress().addr() + "/" + NetUtils.getCidrSize(sourceNatIp.getVlanNetmask()); - String internalCidr = network.getGateway() + "/" + network.getCidr().split("/")[1]; - // assuming a vlan: - String vtag = sourceNatIp.getVlanTag(); - BroadcastDomainType tiep = null; - try { - tiep = BroadcastDomainType.getTypeOf(vtag); - } catch (URISyntaxException use) { - throw new CloudRuntimeException("vlantag for sourceNatIp is not valid: " + vtag, use); - } - if (tiep == BroadcastDomainType.Vlan) { - vtag = BroadcastDomainType.Vlan.getValueFrom(BroadcastDomainType.fromString(vtag)); - } else if (!(tiep == BroadcastDomainType.UnDecided || tiep == BroadcastDomainType.Native)) { - throw new CloudRuntimeException("only vlans are supported for sourceNatIp, at this moment: " + vtag); - } - long vlanid = (Vlan.UNTAGGED.equals(vtag)) ? 0 : Long.parseLong(vtag); - - CreateLogicalRouterCommand cmd = - new CreateLogicalRouterCommand(niciraNvpHost.getDetail("l3gatewayserviceuuid"), vlanid, BroadcastDomainType.getValue(network.getBroadcastUri()), - "router-" + network.getDisplayText(), publicCidr, sourceNatIp.getGateway(), internalCidr, context.getDomain().getName() + "-" + - context.getAccount().getAccountName()); - CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - if (answer.getResult() == false) { - logger.error(String.format("Failed to create Logical Router for network %s", network)); - return false; - } - - NiciraNvpRouterMappingVO routermapping = new NiciraNvpRouterMappingVO(answer.getLogicalRouterUuid(), network.getId()); - niciraNvpRouterMappingDao.persist(routermapping); - - } - - return true; - } - - private boolean sharedNetworkSupport(Network network, String lSwitchUuid, String ownerName, HostVO niciraNvpHost) { - //Support Shared Networks, we won’t be creating logical router, 2 cases: - //Case 1) UUID Supplied for VLAN -> This is UUID of the logical router to attach lswitch - //Case 2) Numerical ID supplied for VLAN -> lswitch is connected to L2 gateway service that we have as an attribute of the NVP device. If no L2 gateway attribute exists then exception. - - if (niciraNvpRouterMappingDao.existsMappingForNetworkId(network.getId())){ - //Case 1) - return sharedNetworkSupportUUIDVlanId(network, lSwitchUuid, ownerName, niciraNvpHost); - } - else { - //Case 2) - return sharedNetworkSupportNumericalVlanId(network, lSwitchUuid, ownerName, niciraNvpHost); - } - } - - private boolean sharedNetworkSupportUUIDVlanId(Network network, String lSwitchUuid, String ownerName, HostVO niciraNvpHost) { - String networkCidr = network.getCidr(); - String vlanGateway = network.getGateway(); - String portIpAddress = createLogicalRouterPortIpAddress(networkCidr, vlanGateway); - NiciraNvpRouterMappingVO mapRouterNetwork = niciraNvpRouterMappingDao.findByNetworkId(network.getId()); - String lRouterUuid = mapRouterNetwork.getLogicalRouterUuid(); - ConfigureSharedNetworkUuidCommand cmd = - new ConfigureSharedNetworkUuidCommand(lRouterUuid, lSwitchUuid, portIpAddress, ownerName, network.getId()); - ConfigureSharedNetworkUuidAnswer answer = (ConfigureSharedNetworkUuidAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - if (answer.getResult() == false) { - logger.error(String.format("Failed to configure Logical Router for Shared network %s", network)); - return false; - } - return true; - } - - private boolean sharedNetworkSupportNumericalVlanId(Network network, String lSwitchUuid, String ownerName, HostVO niciraNvpHost) { - List networkVlans = vlanDao.listVlansByNetworkId(network.getId()); - if (networkVlans.size() == 1){ - for (VlanVO vlanVO : networkVlans) { - long vlanId = Long.parseLong(vlanVO.getVlanTag()); - String l2GatewayServiceUuid = niciraNvpHost.getDetail("l2gatewayserviceuuid"); - if (l2GatewayServiceUuid == null){ - throw new CloudRuntimeException("No L2 Gateway Service Uuid found on " + niciraNvpHost.getName()); - } - ConfigureSharedNetworkVlanIdCommand cmd = - new ConfigureSharedNetworkVlanIdCommand(lSwitchUuid, l2GatewayServiceUuid , vlanId, ownerName, network.getId()); - ConfigureSharedNetworkVlanIdAnswer answer = (ConfigureSharedNetworkVlanIdAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - if (answer.getResult() == false) { - logger.error(String.format("Failed to configure Shared network %s", network)); - return false; - } - } - } - return true; - } - - - private String createLogicalRouterPortIpAddress(String networkCidr, String vlanGateway) { - if (networkCidr != null && vlanGateway != null){ - return networkCidr.replaceFirst("[\\d]{1,3}.[\\d]{1,3}.[\\d]{1,3}.[\\d]{1,3}", vlanGateway); - } - return null; - } - - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - if (network.getBroadcastUri() == null) { - logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); - return false; - } - - NicVO nicVO = nicDao.findById(nic.getId()); - - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - - NiciraNvpNicMappingVO existingNicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid()); - if (existingNicMap != null) { - FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchUuid(), existingNicMap.getLogicalSwitchPortUuid()); - FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), findCmd); - - if (answer.getResult()) { - logger.warn("Existing Logical Switchport found for nic " + nic.getName() + " with uuid " + existingNicMap.getLogicalSwitchPortUuid()); - UpdateLogicalSwitchPortCommand cmd = - new UpdateLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchPortUuid(), BroadcastDomainType.getValue(network.getBroadcastUri()), - nicVO.getUuid(), context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName()); - agentMgr.easySend(niciraNvpHost.getId(), cmd); - return true; - } else { - logger.error("Stale entry found for nic " + nic.getName() + " with logical switchport uuid " + existingNicMap.getLogicalSwitchPortUuid()); - niciraNvpNicMappingDao.remove(existingNicMap.getId()); - } - } - - CreateLogicalSwitchPortCommand cmd = - new CreateLogicalSwitchPortCommand(BroadcastDomainType.getValue(network.getBroadcastUri()), nicVO.getUuid(), context.getDomain().getName() + "-" + - context.getAccount().getAccountName(), nic.getName()); - CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("CreateLogicalSwitchPortCommand failed"); - return false; - } - - NiciraNvpNicMappingVO nicMap = - new NiciraNvpNicMappingVO(BroadcastDomainType.getValue(network.getBroadcastUri()), answer.getLogicalSwitchPortUuid(), nicVO.getUuid()); - niciraNvpNicMappingDao.persist(nicMap); - - return true; - } - - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - if (network.getBroadcastUri() == null) { - logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); - return false; - } - - NicVO nicVO = nicDao.findById(nic.getId()); - - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - - NiciraNvpNicMappingVO nicMap = niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid()); - if (nicMap == null) { - logger.error(String.format("No mapping for nic %s", nic)); - return false; - } - - DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand(nicMap.getLogicalSwitchUuid(), nicMap.getLogicalSwitchPortUuid()); - DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("DeleteLogicalSwitchPortCommand failed"); - return false; - } - - niciraNvpNicMappingDao.remove(nicMap.getId()); - - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - - //Dont destroy logical router when removing Shared Networks - if (! network.getGuestType().equals(GuestType.Shared) && networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, Provider.NiciraNvp)) { - logger.debug("Apparently we were providing SourceNat on this network"); - - // Deleting the LogicalRouter will also take care of all provisioned - // nat rules. - NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId()); - if (routermapping == null) { - logger.warn(String.format("No logical router uuid found for network %s", network)); - // This might be cause by a failed deployment, so don't make shutdown fail as well. - return true; - } - - DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid()); - DeleteLogicalRouterAnswer answer = (DeleteLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - if (answer.getResult() == false) { - logger.error(String.format("Failed to delete LogicalRouter for network %s", network)); - return false; - } - - niciraNvpRouterMappingDao.remove(routermapping.getId()); - } - - return true; - } - - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network, Service.Connectivity)) { - return false; - } - - return true; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - // Nothing to do here. - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return true; - } - - @Override - public boolean verifyServicesCombination(Set services) { - // This element can only function in a Nicra Nvp based - // SDN network, so Connectivity needs to be present here - if (!services.contains(Service.Connectivity)) { - logger.warn("Unable to provide services without Connectivity service enabled for this element"); - return false; - } - if ((services.contains(Service.PortForwarding) || services.contains(Service.StaticNat)) && !services.contains(Service.SourceNat)) { - logger.warn("Unable to provide StaticNat and/or PortForwarding without the SourceNat service"); - return false; - } - return true; - } - - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); - - // L2 Support : SDN provisioning - capabilities.put(Service.Connectivity, null); - - // L3 Support : Generic? - capabilities.put(Service.Gateway, null); - - // L3 Support : SourceNat - Map sourceNatCapabilities = new HashMap(); - sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, "peraccount"); - sourceNatCapabilities.put(Capability.RedundantRouter, "false"); - capabilities.put(Service.SourceNat, sourceNatCapabilities); - - // L3 Support : Port Forwarding - capabilities.put(Service.PortForwarding, null); - - // L3 support : StaticNat - capabilities.put(Service.StaticNat, null); - - return capabilities; - } - - @Override - public List> getCommands() { - List> cmdList = new ArrayList>(); - cmdList.add(AddNiciraNvpDeviceCmd.class); - cmdList.add(DeleteNiciraNvpDeviceCmd.class); - cmdList.add(ListNiciraNvpDeviceNetworksCmd.class); - cmdList.add(ListNiciraNvpDevicesCmd.class); - return cmdList; - } - - @Override - @DB - public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) { - ServerResource resource = new NiciraNvpResource(); - final String deviceName = Network.Provider.NiciraNvp.getName(); - NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName); - if (networkDevice == null) { - throw new CloudRuntimeException("No network device found for " + deviceName); - } - final Long physicalNetworkId = cmd.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); - } - long zoneId = physicalNetwork.getDataCenterId(); - - final PhysicalNetworkServiceProviderVO ntwkSvcProvider = - physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder()); - if (ntwkSvcProvider == null) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is not enabled in the physical network: %s to add this device", networkDevice.getNetworkServiceProvder(), physicalNetwork)); - } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException(String.format("Network Service Provider: %s is in shutdown state in the physical network: %s to add this device", ntwkSvcProvider.getProviderName(), physicalNetwork)); - } - - if (niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) { - throw new CloudRuntimeException("A NiciraNvp device is already configured on this physical network"); - } - - Map params = new HashMap(); - params.put("guid", UUID.randomUUID().toString()); - params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); - params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); - params.put("name", "Nicira Controller - " + cmd.getHost()); - params.put("ip", cmd.getHost()); - params.put("adminuser", cmd.getUsername()); - params.put("adminpass", cmd.getPassword()); - params.put("transportzoneuuid", cmd.getTransportzoneUuid()); - // FIXME What to do with multiple isolation types - params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase()); - if (cmd.getL3GatewayServiceUuid() != null) { - params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid()); - } - if (cmd.getL2GatewayServiceUuid() != null) { - params.put("l2gatewayserviceuuid", cmd.getL2GatewayServiceUuid()); - } - - Map hostdetails = new HashMap(); - hostdetails.putAll(params); - - try { - resource.configure(cmd.getHost(), hostdetails); - - final Host host = resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params); - if (host != null) { - return Transaction.execute(new TransactionCallback() { - @Override - public NiciraNvpDeviceVO doInTransaction(TransactionStatus status) { - NiciraNvpDeviceVO niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName); - niciraNvpDao.persist(niciraNvpDevice); - - DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice.getId())); - hostDetailsDao.persist(detail); - - return niciraNvpDevice; - } - }); - } else { - throw new CloudRuntimeException("Failed to add Nicira Nvp Device due to internal error."); - } - } catch (ConfigurationException e) { - throw new CloudRuntimeException(e.getMessage()); - } - } - - @Override - public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(NiciraNvpDeviceVO niciraNvpDeviceVO) { - HostVO niciraNvpHost = hostDao.findById(niciraNvpDeviceVO.getHostId()); - hostDao.loadDetails(niciraNvpHost); - - NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse(); - response.setDeviceName(niciraNvpDeviceVO.getDeviceName()); - PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(niciraNvpDeviceVO.getPhysicalNetworkId()); - if (pnw != null) { - response.setPhysicalNetworkId(pnw.getUuid()); - } - response.setId(niciraNvpDeviceVO.getUuid()); - response.setProviderName(niciraNvpDeviceVO.getProviderName()); - response.setHostName(niciraNvpHost.getDetail("ip")); - response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid")); - response.setL3GatewayServiceUuid(niciraNvpHost.getDetail("l3gatewayserviceuuid")); - response.setL2GatewayServiceUuid(niciraNvpHost.getDetail("l2gatewayserviceuuid")); - response.setObjectName("niciranvpdevice"); - return response; - } - - @Override - public boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd) { - Long niciraDeviceId = cmd.getNiciraNvpDeviceId(); - NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraDeviceId); - if (niciraNvpDevice == null) { - throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId); - } - - // Find the physical network we work for - Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork != null) { - // Lets see if there are networks that use us - // Find the nicira networks on this physical network - List networkList = networkDao.listByPhysicalNetwork(physicalNetworkId); - if (networkList != null) { - // Networks with broadcast type lswitch are ours - for (NetworkVO network : networkList) { - if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { - if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) { - throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); - } - } - } - } - } - - HostVO niciraHost = hostDao.findById(niciraNvpDevice.getHostId()); - Long hostId = niciraHost.getId(); - - niciraHost.setResourceState(ResourceState.Maintenance); - hostDao.update(hostId, niciraHost); - resourceMgr.deleteHost(hostId, false, false); - - niciraNvpDao.remove(niciraDeviceId); - return true; - } - - @Override - public List listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd) { - Long physicalNetworkId = cmd.getPhysicalNetworkId(); - Long niciraNvpDeviceId = cmd.getNiciraNvpDeviceId(); - List responseList = new ArrayList(); - - if (physicalNetworkId == null && niciraNvpDeviceId == null) { - throw new InvalidParameterValueException("Either physical network Id or nicira device Id must be specified"); - } - - if (niciraNvpDeviceId != null) { - NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraNvpDeviceId); - if (niciraNvpDevice == null) { - throw new InvalidParameterValueException("Could not find Nicira Nvp device with id: " + niciraNvpDevice); - } - responseList.add(niciraNvpDevice); - } else { - PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); - } - responseList = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId); - } - - return responseList; - } - - @Override - public List listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd) { - Long niciraDeviceId = cmd.getNiciraNvpDeviceId(); - NiciraNvpDeviceVO niciraNvpDevice = niciraNvpDao.findById(niciraDeviceId); - if (niciraNvpDevice == null) { - throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId); - } - - // Find the physical network we work for - Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = physicalNetworkDao.findById(physicalNetworkId); - if (physicalNetwork == null) { - // No such physical network, so no provisioned networks - return Collections.emptyList(); - } - - // Find the nicira networks on this physical network - List networkList = networkDao.listByPhysicalNetwork(physicalNetworkId); - if (networkList == null) { - return Collections.emptyList(); - } - - // Networks with broadcast type lswitch are ours - List responseList = new ArrayList(); - for (NetworkVO network : networkList) { - if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { - responseList.add(network); - } - } - - return responseList; - } - - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { - if (!(startup[0] instanceof StartupNiciraNvpCommand)) { - return null; - } - host.setType(Host.Type.L2Networking); - return host; - } - - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (!(host.getType() == Host.Type.L2Networking)) { - return null; - } - return new DeleteHostAnswer(true); - } - - /** - * From interface SourceNatServiceProvider - */ - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } - - /** - * From interface IpDeployer - * - * @param network - * @param ipAddress - * @param services - * @return - * @throws ResourceUnavailableException - */ - @Override - public boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException { - if (services.contains(Service.SourceNat)) { - // Only if we need to provide SourceNat we need to configure the logical router - // SourceNat is required for StaticNat and PortForwarding - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - hostDao.loadDetails(niciraNvpHost); - - NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId()); - if (routermapping == null) { - logger.error(String.format("No logical router uuid found for network %s", network)); - return false; - } - - List cidrs = new ArrayList(); - for (PublicIpAddress ip : ipAddress) { - if (ip.getState() == IpAddress.State.Releasing) { - // If we are releasing we don't need to push this ip to - // the Logical Router - continue; - } - cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask())); - } - ConfigurePublicIpsOnLogicalRouterCommand cmd = - new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); - ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - //FIXME answer can be null if the host is down - return answer.getResult(); - } else { - logger.debug("No need to provision ip addresses as we are not providing L3 services."); - } - - return true; - } - - /** - * From interface StaticNatServiceProvider - */ - @Override - public boolean applyStaticNats(Network network, List rules) throws ResourceUnavailableException { - if (!canHandle(network, Service.StaticNat)) { - return false; - } - - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - - NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId()); - if (routermapping == null) { - logger.error(String.format("No logical router uuid found for network %s", network)); - return false; - } - - List staticNatRules = new ArrayList(); - for (StaticNat rule : rules) { - IpAddress sourceIp = networkModel.getIp(rule.getSourceIpAddressId()); - // Force the nat rule into the StaticNatRuleTO, no use making a new TO object - // we only need the source and destination ip. Unfortunately no mention if a rule - // is new. - StaticNatRuleTO ruleTO = - new StaticNatRuleTO(1, sourceIp.getAddress().addr(), MIN_PORT, MAX_PORT, rule.getDestIpAddress(), MIN_PORT, MAX_PORT, "any", rule.isForRevoke(), false); - staticNatRules.add(ruleTO); - } - - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules); - ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - - return answer.getResult(); - } - - /** - * From interface PortForwardingServiceProvider - */ - @Override - public boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException { - if (!canHandle(network, Service.PortForwarding)) { - return false; - } - - List devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); - return false; - } - NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - - NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId()); - if (routermapping == null) { - logger.error(String.format("No logical router uuid found for network %s", network)); - return false; - } - - List portForwardingRules = new ArrayList(); - for (PortForwardingRule rule : rules) { - IpAddress sourceIp = networkModel.getIp(rule.getSourceIpAddressId()); - Vlan vlan = vlanDao.findById(sourceIp.getVlanId()); - PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); - portForwardingRules.add(ruleTO); - } - - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = - new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); - ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer)agentMgr.easySend(niciraNvpHost.getId(), cmd); - - return answer.getResult(); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java deleted file mode 100644 index dae1a0f28031..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/element/NiciraNvpElementService.java +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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.network.element; - -import java.util.List; - -import com.cloud.api.commands.AddNiciraNvpDeviceCmd; -import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd; -import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd; -import com.cloud.api.commands.ListNiciraNvpDevicesCmd; -import com.cloud.api.response.NiciraNvpDeviceResponse; -import com.cloud.network.Network; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.utils.component.PluggableService; - -public interface NiciraNvpElementService extends PluggableService { - - public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd); - - public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse(NiciraNvpDeviceVO niciraDeviceVO); - - boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd); - - List listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd); - - List listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd); - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java deleted file mode 100644 index d366169fcc7a..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuru.java +++ /dev/null @@ -1,368 +0,0 @@ -// -// 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.network.guru; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.CreateLogicalSwitchAnswer; -import com.cloud.agent.api.CreateLogicalSwitchCommand; -import com.cloud.agent.api.DeleteLogicalRouterPortAnswer; -import com.cloud.agent.api.DeleteLogicalRouterPortCommand; -import com.cloud.agent.api.DeleteLogicalSwitchAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchCommand; -import com.cloud.agent.api.FindL2GatewayServiceAnswer; -import com.cloud.agent.api.FindL2GatewayServiceCommand; -import com.cloud.agent.api.FindLogicalRouterPortAnswer; -import com.cloud.agent.api.FindLogicalRouterPortCommand; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Service; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkModel; -import com.cloud.network.NetworkProfile; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.network.NiciraNvpNicMappingVO; -import com.cloud.network.NiciraNvpRouterMappingVO; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetwork.IsolationMethod; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.NiciraNvpDao; -import com.cloud.network.dao.NiciraNvpNicMappingDao; -import com.cloud.network.dao.NiciraNvpRouterMappingDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.network.nicira.L2GatewayServiceConfig; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; -import com.cloud.resource.ResourceManager; -import com.cloud.user.Account; -import com.cloud.user.dao.AccountDao; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru implements NetworkGuruAdditionalFunctions{ - private static final int MAX_NAME_LENGTH = 40; - - - @Inject - protected NetworkModel networkModel; - @Inject - protected NetworkDao networkDao; - @Inject - protected DataCenterDao zoneDao; - @Inject - protected PhysicalNetworkDao physicalNetworkDao; - @Inject - protected AccountDao accountDao; - @Inject - protected NiciraNvpDao niciraNvpDao; - @Inject - protected HostDao hostDao; - @Inject - protected ResourceManager resourceMgr; - @Inject - protected AgentManager agentMgr; - @Inject - protected HostDetailsDao hostDetailsDao; - @Inject - protected NetworkOfferingServiceMapDao ntwkOfferingSrvcDao; - @Inject - protected NiciraNvpRouterMappingDao niciraNvpRouterMappingDao; - @Inject - protected NiciraNvpNicMappingDao niciraNvpNicMappingDao; - - public NiciraNvpGuestNetworkGuru() { - super(); - _isolationMethods = new IsolationMethod[] { new IsolationMethod("STT", "NiciraNvp"), new IsolationMethod("VXLAN","NiciraNvp") }; - } - - @Override - protected boolean canHandle(final NetworkOffering offering, final NetworkType networkType, final PhysicalNetwork physicalNetwork) { - // This guru handles only Guest Isolated network that supports Source nat service - if (networkType == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) - && supportedGuestTypes(offering, Network.GuestType.Isolated, Network.GuestType.Shared) - && isMyIsolationMethod(physicalNetwork) && ntwkOfferingSrvcDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Connectivity)) { - return true; - } else { - return false; - } - } - - private boolean supportedGuestTypes(NetworkOffering offering, GuestType... types) { - for (GuestType guestType : types) { - if (offering.getGuestType().equals(guestType)){ - return true; - } - } - return false; - } - - @Override - public Network design(final NetworkOffering offering, final DeploymentPlan plan, final Network userSpecified, String name, Long vpcId, final Account owner) { - // Check of the isolation type of the related physical network is supported - final PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId()); - final DataCenter dc = _dcDao.findById(plan.getDataCenterId()); - if (!canHandle(offering, dc.getNetworkType(), physnet)) { - logger.debug("Refusing to design this network"); - return null; - } - - final List devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network {}", physnet); - return null; - } - logger.debug("Nicira Nvp {} found on physical network {}", devices.get(0).getUuid(), physnet); - - logger.debug("Physical isolation type is supported, asking GuestNetworkGuru to design this network"); - final NetworkVO networkObject = (NetworkVO) super.design(offering, plan, userSpecified, name, vpcId, owner); - if (networkObject == null) { - return null; - } - networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch); - if (offering.getGuestType().equals(GuestType.Shared)){ - networkObject.setState(State.Allocated); - } - - return networkObject; - } - - @Override - public Network implement(final Network network, final NetworkOffering offering, final DeployDestination dest, final ReservationContext context) - throws InsufficientVirtualNetworkCapacityException { - assert network.getState() == State.Implementing : "Why are we implementing " + network; - - final long dcId = dest.getDataCenter().getId(); - - Long physicalNetworkId = network.getPhysicalNetworkId(); - - // physical network id can be null in Guest Network in Basic zone, so locate the physical network - if (physicalNetworkId == null) { - physicalNetworkId = networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType()); - } - - final NetworkVO implemented = new NetworkVO(network.getTrafficType(), network.getMode(), network.getBroadcastDomainType(), network.getNetworkOfferingId(), - State.Allocated, network.getDataCenterId(), physicalNetworkId, offering.isRedundantRouter()); - - if (network.getGateway() != null) { - implemented.setGateway(network.getGateway()); - } - - if (network.getCidr() != null) { - implemented.setCidr(network.getCidr()); - } - - // Name is either the given name or the uuid - String name = network.getName(); - if (name == null || name.isEmpty()) { - name = ((NetworkVO) network).getUuid(); - } - if (name.length() > MAX_NAME_LENGTH) { - name = name.substring(0, MAX_NAME_LENGTH - 1); - } - - final List devices = niciraNvpDao.listByPhysicalNetwork(physicalNetworkId); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + physicalNetworkId); - return null; - } - final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - hostDao.loadDetails(niciraNvpHost); - final String transportzoneuuid = niciraNvpHost.getDetail("transportzoneuuid"); - final String transportzoneisotype = niciraNvpHost.getDetail("transportzoneisotype"); - - if (offering.getGuestType().equals(GuestType.Shared)) { - try { - checkL2GatewayServiceSharedNetwork(niciraNvpHost); - } - catch (Exception e){ - logger.error("L2 Gateway Service Issue: " + e.getMessage()); - return null; - } - } - - final CreateLogicalSwitchCommand cmd = new CreateLogicalSwitchCommand(transportzoneuuid, transportzoneisotype, name, context.getDomain().getName() + "-" - + context.getAccount().getAccountName()); - final CreateLogicalSwitchAnswer answer = (CreateLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("CreateLogicalSwitchCommand failed"); - return null; - } - - try { - implemented.setBroadcastUri(new URI("lswitch", answer.getLogicalSwitchUuid(), null)); - implemented.setBroadcastDomainType(BroadcastDomainType.Lswitch); - logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString()); - } catch (final URISyntaxException e) { - logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e); - return null; - } - - return implemented; - } - - private void checkL2GatewayServiceSharedNetwork(HostVO niciraNvpHost) throws Exception { - String l2GatewayServiceUuid = niciraNvpHost.getDetail("l2gatewayserviceuuid"); - if (l2GatewayServiceUuid == null){ - throw new Exception("No L2 Gateway Service found"); - } - else { - final FindL2GatewayServiceCommand cmdL2GWService = new FindL2GatewayServiceCommand(new L2GatewayServiceConfig(l2GatewayServiceUuid)); - final FindL2GatewayServiceAnswer answerL2GWService = (FindL2GatewayServiceAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmdL2GWService); - if (answerL2GWService == null || !answerL2GWService.getResult()){ - throw new Exception("No L2 Gateway Service found with uuid " + l2GatewayServiceUuid); - } - else { - String uuidFound = answerL2GWService.getGatewayServiceUuid(); - if (! uuidFound.equals(l2GatewayServiceUuid)){ - throw new Exception("Found L2 Gateway Service " + uuidFound + " instead of " + l2GatewayServiceUuid); - } - } - } - } - - @Override - public void reserve(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final DeployDestination dest, final ReservationContext context) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { - super.reserve(nic, network, vm, dest, context); - } - - @Override - public boolean release(final NicProfile nic, final VirtualMachineProfile vm, final String reservationId) { - return super.release(nic, vm, reservationId); - } - - @Override - public void shutdown(final NetworkProfile profile, final NetworkOffering offering) { - final NetworkVO networkObject = networkDao.findById(profile.getId()); - if (networkObject.getBroadcastDomainType() != BroadcastDomainType.Lswitch || networkObject.getBroadcastUri() == null) { - logger.warn(String.format("BroadcastUri is empty or incorrect for guest network %s", networkObject)); - return; - } - - final List devices = niciraNvpDao.listByPhysicalNetwork(networkObject.getPhysicalNetworkId()); - if (devices.isEmpty()) { - logger.error("No NiciraNvp Controller on physical network " + networkObject.getPhysicalNetworkId()); - return; - } - final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); - final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId()); - - String logicalSwitchUuid = BroadcastDomainType.getValue(networkObject.getBroadcastUri()); - - if (offering.getGuestType().equals(GuestType.Shared)){ - sharedNetworksCleanup(networkObject, logicalSwitchUuid, niciraNvpHost); - } - - final DeleteLogicalSwitchCommand cmd = new DeleteLogicalSwitchCommand(logicalSwitchUuid); - final DeleteLogicalSwitchAnswer answer = (DeleteLogicalSwitchAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd); - - if (answer == null || !answer.getResult()) { - logger.error("DeleteLogicalSwitchCommand failed"); - } - - super.shutdown(profile, offering); - } - - private void sharedNetworksCleanup(NetworkVO networkObject, String logicalSwitchUuid, HostVO niciraNvpHost) { - NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(networkObject.getId()); - if (routermapping == null) { - // Case 1: Numerical Vlan Provided -> No lrouter used. - logger.info(String.format("Shared Network %s didn't use Logical Router", networkObject)); - } - else { - //Case 2: Logical Router's UUID provided as Vlan id -> Remove lrouter port but not lrouter. - String lRouterUuid = routermapping.getLogicalRouterUuid(); - logger.debug("Finding Logical Router Port on Logical Router " + lRouterUuid + " with attachment_lswitch_uuid=" + logicalSwitchUuid + " to delete it"); - final FindLogicalRouterPortCommand cmd = new FindLogicalRouterPortCommand(lRouterUuid, logicalSwitchUuid); - final FindLogicalRouterPortAnswer answer = (FindLogicalRouterPortAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd); - - if (answer != null && answer.getResult()) { - String logicalRouterPortUuid = answer.getLogicalRouterPortUuid(); - logger.debug("Found Logical Router Port " + logicalRouterPortUuid + ", deleting it"); - final DeleteLogicalRouterPortCommand cmdDeletePort = new DeleteLogicalRouterPortCommand(lRouterUuid, logicalRouterPortUuid); - final DeleteLogicalRouterPortAnswer answerDelete = (DeleteLogicalRouterPortAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmdDeletePort); - - if (answerDelete != null && answerDelete.getResult()){ - logger.info("Successfully deleted Logical Router Port " + logicalRouterPortUuid); - } - else { - logger.error("Could not delete Logical Router Port " + logicalRouterPortUuid); - } - } - else { - logger.error("Find Logical Router Port failed"); - } - } - } - - @Override - public boolean trash(final Network network, final NetworkOffering offering) { - //Since NVP Plugin supports Shared networks, remove mapping when deleting network implemented or allocated - if (network.getGuestType() == GuestType.Shared && niciraNvpRouterMappingDao.existsMappingForNetworkId(network.getId())){ - NiciraNvpRouterMappingVO mappingVO = niciraNvpRouterMappingDao.findByNetworkId(network.getId()); - niciraNvpRouterMappingDao.remove(mappingVO.getId()); - } - return super.trash(network, offering); - } - - @Override - public void finalizeNetworkDesign(long networkId, String vlanIdAsUUID) { - if (vlanIdAsUUID == null) return; - NiciraNvpRouterMappingVO routermapping = new NiciraNvpRouterMappingVO(vlanIdAsUUID, networkId); - niciraNvpRouterMappingDao.persist(routermapping); - } - - @Override - public Map listAdditionalNicParams(String nicUuid) { - NiciraNvpNicMappingVO mapping = niciraNvpNicMappingDao.findByNicUuid(nicUuid); - if (mapping != null){ - Map result = new HashMap(); - result.put(NetworkGuruAdditionalFunctions.NSX_LSWITCH_UUID, mapping.getLogicalSwitchUuid()); - result.put(NetworkGuruAdditionalFunctions.NSX_LSWITCHPORT_UUID, mapping.getLogicalSwitchPortUuid()); - return result; - } - return null; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java deleted file mode 100644 index b5291dc3627f..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessConfiguration.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.network.nicira; - -import java.util.List; - -public abstract class AccessConfiguration extends BaseNiciraNamedEntity { - - protected List logicalPortEgressRules; - protected List logicalPortIngressRules; - - public List getLogicalPortEgressRules() { - return logicalPortEgressRules; - } - - public void setLogicalPortEgressRules(final List logicalPortEgressRules) { - this.logicalPortEgressRules = logicalPortEgressRules; - } - - public List getLogicalPortIngressRules() { - return logicalPortIngressRules; - } - - public void setLogicalPortIngressRules(final List logicalPortIngressRules) { - this.logicalPortIngressRules = logicalPortIngressRules; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java deleted file mode 100644 index e614db6e43aa..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AccessRule.java +++ /dev/null @@ -1,58 +0,0 @@ -// -// 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.network.nicira; - -import java.io.Serializable; - -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -@SuppressWarnings("serial") -public abstract class AccessRule implements Serializable { - - public static final String ETHERTYPE_IPV4 = "IPv4"; - public static final String ETHERTYPE_IPV6 = "IPv6"; - - protected String ethertype = ETHERTYPE_IPV4; - - protected int protocol; - - - public String getEthertype() { - return ethertype; - } - - public void setEthertype(String ethertype) { - this.ethertype = ethertype; - } - - public int getProtocol() { - return protocol; - } - - public void setProtocol(int protocol) { - this.protocol = protocol; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java deleted file mode 100644 index 870124ed6039..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Acl.java +++ /dev/null @@ -1,23 +0,0 @@ -// -// 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.network.nicira; - -public class Acl extends AccessConfiguration { -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java deleted file mode 100644 index 8a4c05332cf8..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/AclRule.java +++ /dev/null @@ -1,209 +0,0 @@ -// -// 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.network.nicira; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; - -@SuppressWarnings("serial") -public class AclRule extends AccessRule { - - public static final String ETHERTYPE_ARP = "ARP"; - - /** - * @TODO Convert this String into Enum and check the JSON communication still works - */ - protected String action; - - protected String sourceIpPrefix; - - protected String destinationIpPrefix; - - protected String sourceMacAddress; - - protected String destinationMacAddress; - - protected Integer sourcePortRangeMin; - - protected Integer destinationPortRangeMin; - - protected Integer sourcePortRangeMax; - - protected Integer destinationPortRangeMax; - - protected Integer icmpProtocolCode; - - protected Integer icmpProtocolType; - - protected int order; - - - /** - * Default constructor - */ - public AclRule() { - } - - /** - * Fully parameterized constructor - */ - public AclRule(String ethertype, int protocol, String action, String sourceMacAddress, - String destinationMacAddress, String sourceIpPrefix, String destinationIpPrefix, - Integer sourcePortRangeMin, Integer sourcePortRangeMax, - Integer destinationPortRangeMin, Integer destinationPortRangeMax, - int order, Integer icmpProtocolCode, Integer icmpProtocolType) { - this.ethertype = ethertype; - this.protocol = protocol; - this.action = action; - this.sourceMacAddress = sourceMacAddress; - this.destinationMacAddress = destinationMacAddress; - this.sourceIpPrefix = sourceIpPrefix; - this.destinationIpPrefix = destinationIpPrefix; - this.sourcePortRangeMin = sourcePortRangeMin; - this.sourcePortRangeMax = sourcePortRangeMax; - this.destinationPortRangeMin = destinationPortRangeMin; - this.destinationPortRangeMax = destinationPortRangeMax; - this.order = order; - this.icmpProtocolCode = icmpProtocolCode; - this.icmpProtocolType = icmpProtocolType; - } - - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getSourceIpPrefix() { - return sourceIpPrefix; - } - - public void setSourceIpPrefix(String sourceIpPrefix) { - this.sourceIpPrefix = sourceIpPrefix; - } - - public String getDestinationIpPrefix() { - return destinationIpPrefix; - } - - public void setDestinationIpPrefix(String destinationIpPrefix) { - this.destinationIpPrefix = destinationIpPrefix; - } - - public String getSourceMacAddress() { - return sourceMacAddress; - } - - public void setSourceMacAddress(String sourceMacAddress) { - this.sourceMacAddress = sourceMacAddress; - } - - public String getDestinationMacAddress() { - return destinationMacAddress; - } - - public void setDestinationMacAddress(String destinationMacAddress) { - this.destinationMacAddress = destinationMacAddress; - } - - public Integer getSourcePortRangeMin() { - return sourcePortRangeMin; - } - - public void setSourcePortRangeMin(Integer sourcePortRangeMin) { - this.sourcePortRangeMin = sourcePortRangeMin; - } - - public Integer getDestinationPortRangeMin() { - return destinationPortRangeMin; - } - - public void setDestinationPortRangeMin(Integer destinationPortRangeMin) { - this.destinationPortRangeMin = destinationPortRangeMin; - } - - public Integer getSourcePortRangeMax() { - return sourcePortRangeMax; - } - - public void setSourcePortRangeMax(Integer sourcePortRangeMax) { - this.sourcePortRangeMax = sourcePortRangeMax; - } - - public Integer getDestinationPortRangeMax() { - return destinationPortRangeMax; - } - - public void setDestinationPortRangeMax(Integer destinationPortRangeMax) { - this.destinationPortRangeMax = destinationPortRangeMax; - } - - public Integer getIcmpProtocolCode() { - return icmpProtocolCode; - } - - public void setIcmpProtocolCode(Integer icmpProtocolCode) { - this.icmpProtocolCode = icmpProtocolCode; - } - - public Integer getIcmpProtocolType() { - return icmpProtocolType; - } - - public void setIcmpProtocolType(Integer icmpProtocolType) { - this.icmpProtocolType = icmpProtocolType; - } - - public int getOrder() { - return order; - } - - public void setOrder(int order) { - this.order = order; - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 31) - .append(ethertype).append(protocol) - .toHashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof AclRule)) { - return false; - } - AclRule another = (AclRule) obj; - return new EqualsBuilder() - .append(ethertype, another.ethertype) - .append(protocol, another.protocol) - .isEquals(); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java deleted file mode 100644 index 90ff131ff884..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Attachment.java +++ /dev/null @@ -1,24 +0,0 @@ -// -// 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.network.nicira; - -public abstract class Attachment { - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java deleted file mode 100644 index afcd23339593..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraEntity.java +++ /dev/null @@ -1,85 +0,0 @@ -// -// 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.network.nicira; - -import java.io.Serializable; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -public abstract class BaseNiciraEntity implements Serializable { - protected String href; - protected String schema; - protected String uuid; - - public String getUuid() { - return uuid; - } - - public void setUuid(final String uuid) { - this.uuid = uuid; - } - - public String getHref() { - return href; - } - - public void setHref(final String href) { - this.href = href; - } - - public String getSchema() { - return schema; - } - - public void setSchema(final String schema) { - this.schema = schema; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 31) - .append(this.getClass()) - .append(uuid) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(this.getClass().isInstance(obj))) { - return false; - } - final BaseNiciraEntity another = (BaseNiciraEntity) obj; - return new EqualsBuilder().append(uuid, another.uuid).isEquals(); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java deleted file mode 100644 index 0e21ddb74c4e..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/BaseNiciraNamedEntity.java +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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.network.nicira; - -import java.util.List; - -public abstract class BaseNiciraNamedEntity extends BaseNiciraEntity { - - protected String displayName; - protected List tags; - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(final String displayName) { - this.displayName = displayName; - } - - public List getTags() { - return tags; - } - - public void setTags(final List tags) { - this.tags = tags; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java deleted file mode 100644 index 1ed7039343d2..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ControlClusterStatus.java +++ /dev/null @@ -1,105 +0,0 @@ -// -// 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.network.nicira; - -public class ControlClusterStatus { - private String clusterStatus; - private Stats nodeStats; - private Stats queueStats; - private Stats portStats; - private Stats routerportStats; - private Stats switchStats; - private Stats zoneStats; - private Stats routerStats; - private Stats securityProfileStats; - private ClusterRoleConfig[] configuredRoles; - - public ClusterRoleConfig[] getConfiguredRoles() { - return configuredRoles; - } - - public String getClusterStatus() { - return clusterStatus; - } - - public Stats getNodeStats() { - return nodeStats; - } - - public Stats getLqueueStats() { - return queueStats; - } - - public Stats getLportStats() { - return portStats; - } - - public Stats getLrouterportStats() { - return routerportStats; - } - - public Stats getLswitchStats() { - return switchStats; - } - - public Stats getZoneStats() { - return zoneStats; - } - - public Stats getLrouterStats() { - return routerStats; - } - - public Stats getSecurityProfileStats() { - return securityProfileStats; - } - - public class Stats { - private int errorStateCount; - private int registeredCount; - private int activeCount; - - public int getErrorStateCount() { - return errorStateCount; - } - - public int getRegisteredCount() { - return registeredCount; - } - - public int getActiveCount() { - return activeCount; - } - - } - - public class ClusterRoleConfig { - public String majorityVersion; - public String role; - - public String getMajorityVersion(){ - return majorityVersion; - } - - public String getRole(){ - return role; - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java deleted file mode 100644 index a0d5afcaa842..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/DestinationNatRule.java +++ /dev/null @@ -1,113 +0,0 @@ -// -// 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.network.nicira; - -public class DestinationNatRule extends NatRule { - private String toDestinationIpAddress; - private Integer toDestinationPort; - - public DestinationNatRule() { - setType("DestinationNatRule"); - } - - public String getToDestinationIpAddress() { - return toDestinationIpAddress; - } - - public void setToDestinationIpAddress(final String toDestinationIpAddress) { - this.toDestinationIpAddress = toDestinationIpAddress; - } - - public Integer getToDestinationPort() { - return toDestinationPort; - } - - public void setToDestinationPort(final Integer toDestinationPort) { - this.toDestinationPort = toDestinationPort; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((toDestinationIpAddress == null) ? 0 : toDestinationIpAddress.hashCode()); - result = prime * result + ((toDestinationPort == null) ? 0 : toDestinationPort.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - DestinationNatRule other = (DestinationNatRule)obj; - if (toDestinationIpAddress == null) { - if (other.toDestinationIpAddress != null) { - return false; - } - } else if (!toDestinationIpAddress.equals(other.toDestinationIpAddress)) { - return false; - } - if (toDestinationPort == null) { - if (other.toDestinationPort != null) { - return false; - } - } else if (!toDestinationPort.equals(other.toDestinationPort)) { - return false; - } - return true; - } - - @Override - public boolean equalsIgnoreUuid(Object obj) { - if (this == obj) { - return true; - } - if (!super.equalsIgnoreUuid(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - DestinationNatRule other = (DestinationNatRule)obj; - if (toDestinationIpAddress == null) { - if (other.toDestinationIpAddress != null) { - return false; - } - } else if (!toDestinationIpAddress.equals(other.toDestinationIpAddress)) { - return false; - } - if (toDestinationPort == null) { - if (other.toDestinationPort != null) { - return false; - } - } else if (!toDestinationPort.equals(other.toDestinationPort)) { - return false; - } - return true; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java deleted file mode 100644 index 7eedebbf1d9d..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/ExecutionCounter.java +++ /dev/null @@ -1,54 +0,0 @@ -// -// 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.network.nicira; - -public class ExecutionCounter { - - private final int executionLimit; - private final ThreadLocal executionCount; - - public ExecutionCounter(final int executionLimit) { - this.executionLimit = executionLimit; - executionCount = new ThreadLocal() { - @Override - protected Integer initialValue() { - return new Integer(0); - } - }; - } - - public ExecutionCounter resetExecutionCounter() { - executionCount.set(0); - return this; - } - - public boolean hasReachedExecutionLimit() { - return executionCount.get() >= executionLimit; - } - - public ExecutionCounter incrementExecutionCounter() { - executionCount.set(executionCount.get() + 1); - return this; - } - - public int getValue() { - return executionCount.get(); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/GatewayServiceConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/GatewayServiceConfig.java deleted file mode 100644 index abfd273683d7..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/GatewayServiceConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -// -// 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.network.nicira; - -import java.io.Serializable; - -public abstract class GatewayServiceConfig implements Serializable { - - private String uuid; - private String displayName; - private String type; - - public GatewayServiceConfig(String uuid, String type) { - this.uuid = uuid; - this.type = type; - } - - public String getUuid() { - return uuid; - } - - public String getDisplayName() { - return displayName; - } - - public String getType() { - return type; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayAttachment.java deleted file mode 100644 index 2ef294ed7a1c..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayAttachment.java +++ /dev/null @@ -1,53 +0,0 @@ -// -// 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.network.nicira; - -public class L2GatewayAttachment extends Attachment { - - private String l2GatewayServiceUuid; - private final String type = "L2GatewayAttachment"; - private Long vlanId; - - public L2GatewayAttachment(String l2GatewayServiceUuid) { - this.l2GatewayServiceUuid = l2GatewayServiceUuid; - } - - public L2GatewayAttachment(final String l2GatewayServiceUuid, final long vlanId) { - this.l2GatewayServiceUuid = l2GatewayServiceUuid; - this.vlanId = vlanId; - } - - public String getL2GatewayServiceUuid() { - return l2GatewayServiceUuid; - } - public void setL2GatewayServiceUuid(String l2GatewayServiceUuid) { - this.l2GatewayServiceUuid = l2GatewayServiceUuid; - } - public Long getVlanId() { - return vlanId; - } - public void setVlanId(Long vlanId) { - this.vlanId = vlanId; - } - public String getType() { - return type; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayServiceConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayServiceConfig.java deleted file mode 100644 index 7f2a41aec99f..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L2GatewayServiceConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// 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.network.nicira; - -public class L2GatewayServiceConfig extends GatewayServiceConfig { - - private static final String L2GWTServiceConfigType = "L2GatewayServiceConfig"; - - public L2GatewayServiceConfig(String uuid) { - super(uuid, L2GWTServiceConfigType); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java deleted file mode 100644 index a1d5ce4a9904..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/L3GatewayAttachment.java +++ /dev/null @@ -1,55 +0,0 @@ -// -// 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.network.nicira; - -/** - * - */ -public class L3GatewayAttachment extends Attachment { - private String l3GatewayServiceUuid; - private final String type = "L3GatewayAttachment"; - private Long vlanId; - - public L3GatewayAttachment(String l3GatewayServiceUuid) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - - public L3GatewayAttachment(final String l3GatewayServiceUuid, final long vlanId) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - this.vlanId = vlanId; - } - - public String getL3GatewayServiceUuid() { - return l3GatewayServiceUuid; - } - - public void setL3GatewayServiceUuid(final String l3GatewayServiceUuid) { - this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - - public long getVlanId() { - return vlanId; - } - - public void setVlanId(long vlanId) { - this.vlanId = vlanId; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java deleted file mode 100644 index edc935122295..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouter.java +++ /dev/null @@ -1,71 +0,0 @@ -// -// 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.network.nicira; - - -/** - * - */ -public class LogicalRouter extends BaseNiciraNamedEntity { - public static final String REPLICATION_MODE_SERVICE = "service"; - public static final String REPLICATION_MODE_SOURCE = "source"; - - private final String type = "LogicalRouterConfig"; - private RoutingConfig routingConfig; - private boolean distributed; - private boolean natSynchronizationEnabled; - private String replicationMode; - - public String getType() { - return type; - } - - public RoutingConfig getRoutingConfig() { - return routingConfig; - } - - public void setRoutingConfig(final RoutingConfig routingConfig) { - this.routingConfig = routingConfig; - } - - public boolean isDistributed() { - return distributed; - } - - public void setDistributed(final boolean distributed) { - this.distributed = distributed; - } - - public boolean isNatSynchronizationEnabled() { - return natSynchronizationEnabled; - } - - public void setNatSynchronizationEnabled(final boolean natSynchronizationEnabled) { - this.natSynchronizationEnabled = natSynchronizationEnabled; - } - - public String getReplicationMode() { - return replicationMode; - } - - public void setReplicationMode(final String replicationMode) { - this.replicationMode = replicationMode; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java deleted file mode 100644 index d125011f8419..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalRouterPort.java +++ /dev/null @@ -1,62 +0,0 @@ -// -// 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.network.nicira; - -import java.util.List; - -public class LogicalRouterPort extends BaseNiciraNamedEntity { - private Integer portno; - private boolean adminStatusEnabled; - private List ipAddresses; - private String macAddress; - private final String type = "LogicalRouterPortConfig"; - - public int getPortno() { - return portno; - } - - public void setPortno(final int portno) { - this.portno = portno; - } - - public boolean isAdminStatusEnabled() { - return adminStatusEnabled; - } - - public void setAdminStatusEnabled(final boolean adminStatusEnabled) { - this.adminStatusEnabled = adminStatusEnabled; - } - - public List getIpAddresses() { - return ipAddresses; - } - - public void setIpAddresses(final List ipAddresses) { - this.ipAddresses = ipAddresses; - } - - public String getMacAddress() { - return macAddress; - } - - public void setMacAddress(final String macAddress) { - this.macAddress = macAddress; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java deleted file mode 100644 index b527d94107db..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitch.java +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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.network.nicira; - -import java.util.List; - -public class LogicalSwitch extends BaseNiciraNamedEntity { - public static final String REPLICATION_MODE_SERVICE = "service"; - public static final String REPLICATION_MODE_SOURCE = "source"; - - private final String type = "LogicalSwitchConfig"; - private boolean portIsolationEnabled; - private List transportZones; - private String replicationMode; - - public boolean isPortIsolationEnabled() { - return portIsolationEnabled; - } - - public void setPortIsolationEnabled(final boolean portIsolationEnabled) { - this.portIsolationEnabled = portIsolationEnabled; - } - - public String getType() { - return type; - } - - public List getTransportZones() { - return transportZones; - } - - public void setTransportZones(final List transportZones) { - this.transportZones = transportZones; - } - - public String getReplicationMode() { - return replicationMode; - } - - public void setReplicationMode(final String replicationMode) { - this.replicationMode = replicationMode; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java deleted file mode 100644 index 5e074235a742..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/LogicalSwitchPort.java +++ /dev/null @@ -1,82 +0,0 @@ -// -// 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.network.nicira; - -import java.util.List; - -public class LogicalSwitchPort extends BaseNiciraNamedEntity { - private Integer portno; - private boolean adminStatusEnabled; - private String queueUuid; - private List securityProfiles; - private List mirrorTargets; - private final String type = "LogicalSwitchPortConfig"; - - public LogicalSwitchPort() { - super(); - } - - public LogicalSwitchPort(final String displayName, final List tags, final boolean adminStatusEnabled) { - super(); - this.displayName = displayName; - this.tags = tags; - this.adminStatusEnabled = adminStatusEnabled; - } - - public Integer getPortno() { - return portno; - } - - public void setPortno(final Integer portno) { - this.portno = portno; - } - - public boolean isAdminStatusEnabled() { - return adminStatusEnabled; - } - - public void setAdminStatusEnabled(final boolean adminStatusEnabled) { - this.adminStatusEnabled = adminStatusEnabled; - } - - public String getQueueUuid() { - return queueUuid; - } - - public void setQueueUuid(final String queueUuid) { - this.queueUuid = queueUuid; - } - - public List getSecurityProfiles() { - return securityProfiles; - } - - public void setSecurityProfiles(final List securityProfiles) { - this.securityProfiles = securityProfiles; - } - - public List getMirrorTargets() { - return mirrorTargets; - } - - public void setMirrorTargets(final List mirrorTargets) { - this.mirrorTargets = mirrorTargets; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java deleted file mode 100644 index ae3a86c42ee2..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/Match.java +++ /dev/null @@ -1,146 +0,0 @@ -// -// 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.network.nicira; - -/** - * - */ -public class Match { - private Integer protocol; - private String sourceIpAddresses; - private String destinationIpAddresses; - private Integer sourcePort; - private Integer destinationPort; - private String ethertype = "IPv4"; - - public Integer getProtocol() { - return protocol; - } - - public void setProtocol(final Integer protocol) { - this.protocol = protocol; - } - - public Integer getSourcePort() { - return sourcePort; - } - - public void setSourcePort(final Integer sourcePort) { - this.sourcePort = sourcePort; - } - - public Integer getDestinationPort() { - return destinationPort; - } - - public void setDestinationPort(final Integer destinationPort) { - this.destinationPort = destinationPort; - } - - public String getEthertype() { - return ethertype; - } - - public void setEthertype(final String ethertype) { - this.ethertype = ethertype; - } - - public String getSourceIpAddresses() { - return sourceIpAddresses; - } - - public void setSourceIpAddresses(final String sourceIpAddresses) { - this.sourceIpAddresses = sourceIpAddresses; - } - - public String getDestinationIpAddresses() { - return destinationIpAddresses; - } - - public void setDestinationIpAddresses(final String destinationIpAddresses) { - this.destinationIpAddresses = destinationIpAddresses; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((destinationIpAddresses == null) ? 0 : destinationIpAddresses.hashCode()); - result = prime * result + ((destinationPort == null) ? 0 : destinationPort.hashCode()); - result = prime * result + ((ethertype == null) ? 0 : ethertype.hashCode()); - result = prime * result + ((protocol == null) ? 0 : protocol.hashCode()); - result = prime * result + ((sourceIpAddresses == null) ? 0 : sourceIpAddresses.hashCode()); - result = prime * result + ((sourcePort == null) ? 0 : sourcePort.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Match other = (Match)obj; - if (destinationIpAddresses == null) { - if (other.destinationIpAddresses != null) - return false; - } else if (!destinationIpAddresses.equals(other.destinationIpAddresses)) { - return false; - } - if (destinationPort == null) { - if (other.destinationPort != null) { - return false; - } - } else if (!destinationPort.equals(other.destinationPort)) { - return false; - } - if (ethertype == null) { - if (other.ethertype != null) - return false; - } else if (!ethertype.equals(other.ethertype)) { - return false; - } - if (protocol == null) { - if (other.protocol != null) - return false; - } else if (!protocol.equals(other.protocol)) { - return false; - } - if (sourceIpAddresses == null) { - if (other.sourceIpAddresses != null) - return false; - } else if (!sourceIpAddresses.equals(other.sourceIpAddresses)) { - return false; - } - if (sourcePort == null) { - if (other.sourcePort != null) - return false; - } else if (!sourcePort.equals(other.sourcePort)) { - return false; - } - return true; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java deleted file mode 100644 index 912e352e2733..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRule.java +++ /dev/null @@ -1,130 +0,0 @@ -// -// 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.network.nicira; - -import java.util.UUID; - -/** - * - */ -public abstract class NatRule { - protected Match match; - protected UUID uuid; - protected String type; - protected int order; - - public NatRule() { - } - - public Match getMatch() { - return match; - } - - public void setMatch(final Match match) { - this.match = match; - } - - public UUID getUuid() { - return uuid; - } - - public void setUuid(final UUID uuid) { - this.uuid = uuid; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - - public int getOrder() { - return order; - } - - public void setOrder(final int order) { - this.order = order; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((match == null) ? 0 : match.hashCode()); - result = prime * result + order; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - NatRule other = (NatRule)obj; - if (match == null) { - if (other.match != null) - return false; - } else if (!match.equals(other.match)) - return false; - if (order != other.order) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - if (uuid == null) { - if (other.uuid != null) - return false; - } else if (!uuid.equals(other.uuid)) - return false; - return true; - } - - public boolean equalsIgnoreUuid(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - NatRule other = (NatRule)obj; - if (match == null) { - if (other.match != null) - return false; - } else if (!match.equals(other.match)) - return false; - if (order != other.order) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java deleted file mode 100644 index bb68397dc87f..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NatRuleAdapter.java +++ /dev/null @@ -1,49 +0,0 @@ -// -// 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.network.nicira; - -import java.lang.reflect.Type; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -public class NatRuleAdapter implements JsonDeserializer { - - @Override - public NatRule deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { - final JsonObject jsonObject = jsonElement.getAsJsonObject(); - - if (!jsonObject.has("type")) { - throw new JsonParseException("Deserializing as a NatRule, but no type present in the json object"); - } - - final String natRuleType = jsonObject.get("type").getAsString(); - if ("SourceNatRule".equals(natRuleType)) { - return context.deserialize(jsonElement, SourceNatRule.class); - } else if ("DestinationNatRule".equals(natRuleType)) { - return context.deserialize(jsonElement, DestinationNatRule.class); - } - - throw new JsonParseException("Failed to deserialize type \"" + natRuleType + "\""); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java deleted file mode 100644 index f89b8ad09312..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraConstants.java +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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.network.nicira; - -public class NiciraConstants { - - public static final String SEC_PROFILE_URI_PREFIX = "/ws.v1/security-profile"; - public static final String ACL_URI_PREFIX = "/ws.v1/acl"; - public static final String SWITCH_URI_PREFIX = "/ws.v1/lswitch"; - public static final String ROUTER_URI_PREFIX = "/ws.v1/lrouter"; - public static final String GATEWAY_SERVICE_PREFIX = "/ws.v1/gateway-service"; - public static final String LOGIN_URL = "/ws.v1/login"; - public static final String CONTROL_CLUSTER_STATUS_URL = "/ws.v1/control-cluster/status"; - - public static final String ATTACHMENT_PATH_SEGMENT = "/attachment"; - public static final String NAT_PATH_SEGMENT = "/nat"; - public static final String LPORT_PATH_SEGMENT = "/lport"; - - public static final String ATTACHMENT_VIF_UUID_QUERY_PARAMETER_NAME = "attachment_vif_uuid"; - public static final String ATTACHMENT_VLAN_PARAMETER = "attachment_vlan"; - public static final String ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER = "attachment_gwsvc_uuid"; - public static final String ATTACHMENT_LSWITCH_UUID = "attachment_lswitch_uuid"; - public static final String WILDCARD_QUERY_PARAMETER = "*"; - public static final String UUID_QUERY_PARAMETER = "uuid"; - public static final String FIELDS_QUERY_PARAMETER = "fields"; - public static final String TYPES_QUERY_PARAMETER = "types"; - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java deleted file mode 100644 index 293c5a857639..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApi.java +++ /dev/null @@ -1,663 +0,0 @@ -// -// 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.network.nicira; - -import java.lang.reflect.Type; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.CloseableHttpClient; - -import com.cloud.utils.rest.CloudstackRESTException; -import com.cloud.utils.rest.RESTServiceConnector; -import com.google.common.base.Optional; -import com.google.gson.JsonDeserializer; -import com.google.gson.reflect.TypeToken; - -@SuppressWarnings("rawtypes") -public class NiciraNvpApi { - - private static final Optional ABSENT = Optional.absent(); - - private static final String SWITCH_URI_PREFIX = NiciraConstants.SWITCH_URI_PREFIX; - private static final String ROUTER_URI_PREFIX = NiciraConstants.ROUTER_URI_PREFIX; - private static final String GATEWAY_SERVICE_PREFIX = NiciraConstants.GATEWAY_SERVICE_PREFIX; - - private static final String ATTACHMENT_PATH_SEGMENT = NiciraConstants.ATTACHMENT_PATH_SEGMENT; - private static final String NAT_PATH_SEGMENT = NiciraConstants.NAT_PATH_SEGMENT; - private static final String LPORT_PATH_SEGMENT = NiciraConstants.LPORT_PATH_SEGMENT; - - private static final String ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER = NiciraConstants.ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER; - private static final String WILDCARD_QUERY_PARAMETER = NiciraConstants.WILDCARD_QUERY_PARAMETER; - private static final String UUID_QUERY_PARAMETER = NiciraConstants.UUID_QUERY_PARAMETER; - private static final String FIELDS_QUERY_PARAMETER = NiciraConstants.FIELDS_QUERY_PARAMETER; - private static final String TYPES_QUERY_PARAMETER = NiciraConstants.TYPES_QUERY_PARAMETER; - - private static final int DEFAULT_MAX_RETRIES = 5; - - private final RESTServiceConnector restConnector; - - protected final static Map prefixMap; - - protected final static Map listTypeMap; - - protected final static Map defaultListParams; - - static { - prefixMap = new HashMap(); - prefixMap.put(SecurityProfile.class, NiciraConstants.SEC_PROFILE_URI_PREFIX); - prefixMap.put(Acl.class, NiciraConstants.ACL_URI_PREFIX); - prefixMap.put(LogicalSwitch.class, SWITCH_URI_PREFIX); - prefixMap.put(LogicalRouter.class, ROUTER_URI_PREFIX); - - listTypeMap = new HashMap(); - listTypeMap.put(SecurityProfile.class, new TypeToken>() { - }.getType()); - listTypeMap.put(Acl.class, new TypeToken>() { - }.getType()); - listTypeMap.put(LogicalSwitch.class, new TypeToken>() { - }.getType()); - listTypeMap.put(LogicalRouter.class, new TypeToken>() { - }.getType()); - - defaultListParams = new HashMap(); - defaultListParams.put(FIELDS_QUERY_PARAMETER, WILDCARD_QUERY_PARAMETER); - } - - private NiciraNvpApi(final Builder builder) { - final Map, JsonDeserializer> classToDeserializerMap = new HashMap<>(); - classToDeserializerMap.put(NatRule.class, new NatRuleAdapter()); - classToDeserializerMap.put(RoutingConfig.class, new RoutingConfigAdapter()); - - final NiciraRestClient niciraRestClient = NiciraRestClient.create() - .client(builder.httpClient) - .clientContext(builder.httpClientContext) - .hostname(builder.host) - .username(builder.username) - .password(builder.password) - .loginUrl(NiciraConstants.LOGIN_URL) - .executionLimit(DEFAULT_MAX_RETRIES) - .build(); - restConnector = RESTServiceConnector.create() - .classToDeserializerMap(classToDeserializerMap) - .client(niciraRestClient) - .build(); - } - - public static Builder create() { - return new Builder(); - } - - /** - * POST - * - * @param entity - * @return - * @throws NiciraNvpApiException - */ - private T create(final T entity) throws NiciraNvpApiException { - final String uri = prefixMap.get(entity.getClass()); - return createWithUri(entity, uri); - } - - /** - * POST - * - * @param entity - * @return - * @throws NiciraNvpApiException - */ - private T createWithUri(final T entity, final String uri) throws NiciraNvpApiException { - T createdEntity; - try { - createdEntity = restConnector.executeCreateObject(entity, uri, Collections. emptyMap()); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - - return createdEntity; - } - - /** - * GET list of items - * - * @param uuid - * - * @return - * @throws NiciraNvpApiException - */ - private List find(final Optional uuid, final Class clazz) throws NiciraNvpApiException { - final String uri = prefixMap.get(clazz); - Map params = defaultListParams; - if (uuid.isPresent()) { - params = new HashMap(defaultListParams); - params.put(UUID_QUERY_PARAMETER, uuid.get()); - } - - NiciraNvpList entities; - try { - entities = restConnector.executeRetrieveObject(listTypeMap.get(clazz), uri, params); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - - if (entities == null) { - throw new NiciraNvpApiException("Unexpected response from API"); - } - - return entities.getResults(); - } - - /** - * PUT item given a UUID as key and an item object with the new data - * - * @param item - * @param uuid - * @throws NiciraNvpApiException - */ - private void update(final T item, final String uuid) throws NiciraNvpApiException { - final String uri = prefixMap.get(item.getClass()) + "/" + uuid; - updateWithUri(item, uri); - } - - /** - * PUT item given a UUID as key and an item object with the new data - * - * @param item - * @param uuid - * @throws NiciraNvpApiException - */ - private void updateWithUri(final T item, final String uri) throws NiciraNvpApiException { - try { - restConnector.executeUpdateObject(item, uri, Collections. emptyMap()); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - /** - * DELETE Security Profile given a UUID as key - * - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - private void delete(final String uuid, final Class clazz) throws NiciraNvpApiException { - final String uri = prefixMap.get(clazz) + "/" + uuid; - deleteWithUri(uri); - } - - /** - * DELETE Security Profile given a UUID as key - * - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - private void deleteWithUri(final String uri) throws NiciraNvpApiException { - try { - restConnector.executeDeleteObject(uri); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - /** - * POST {@link SecurityProfile} - * - * @param securityProfile - * @return - * @throws NiciraNvpApiException - */ - public SecurityProfile createSecurityProfile(final SecurityProfile securityProfile) throws NiciraNvpApiException { - return create(securityProfile); - } - - /** - * GET list of {@link SecurityProfile} - * - * @return - * @throws NiciraNvpApiException - */ - public List findSecurityProfile() throws NiciraNvpApiException { - return find(ABSENT, SecurityProfile.class); - } - - /** - * GET list of {@link SecurityProfile} filtered by UUID - * - * We could have invoked the service: SEC_PROFILE_URI_PREFIX + "/" + securityProfileUuid but it is not working currently - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public List findSecurityProfile(final String uuid) throws NiciraNvpApiException { - return find(Optional.fromNullable(uuid), SecurityProfile.class); - } - - /** - * PUT {@link SecurityProfile} given a UUID as key and a {@link SecurityProfile} with the new data - * - * @param securityProfile - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - public void updateSecurityProfile(final SecurityProfile securityProfile, final String securityProfileUuid) throws NiciraNvpApiException { - update(securityProfile, securityProfileUuid); - } - - /** - * DELETE Security Profile given a UUID as key - * - * @param securityProfileUuid - * @throws NiciraNvpApiException - */ - public void deleteSecurityProfile(final String securityProfileUuid) throws NiciraNvpApiException { - delete(securityProfileUuid, SecurityProfile.class); - } - - /** - * POST {@link Acl} - * - * @param acl - * @return - * @throws NiciraNvpApiException - */ - public Acl createAcl(final Acl acl) throws NiciraNvpApiException { - return create(acl); - } - - /** - * GET list of {@link Acl} - * - * @return - * @throws NiciraNvpApiException - */ - public List findAcl() throws NiciraNvpApiException { - return findAcl(null); - } - - /** - * GET list of {@link Acl} filtered by UUID - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public List findAcl(final String uuid) throws NiciraNvpApiException { - return find(Optional.fromNullable(uuid), Acl.class); - } - - /** - * PUT {@link Acl} given a UUID as key and a {@link Acl} with the new data - * - * @param acl - * @param aclUuid - * @throws NiciraNvpApiException - */ - public void updateAcl(final Acl acl, final String aclUuid) throws NiciraNvpApiException { - update(acl, aclUuid); - } - - /** - * DELETE Acl given a UUID as key - * - * @param acl - * @throws NiciraNvpApiException - */ - public void deleteAcl(final String aclUuid) throws NiciraNvpApiException { - delete(aclUuid, Acl.class); - } - - public LogicalSwitch createLogicalSwitch(final LogicalSwitch logicalSwitch) throws NiciraNvpApiException { - return create(logicalSwitch); - } - - /** - * GET list of {@link LogicalSwitch} - * - * @return - * @throws NiciraNvpApiException - */ - public List findLogicalSwitch() throws NiciraNvpApiException { - return findLogicalSwitch(null); - } - - /** - * GET list of {@link LogicalSwitch} filtered by UUID - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public List findLogicalSwitch(final String uuid) throws NiciraNvpApiException { - return find(Optional.fromNullable(uuid), LogicalSwitch.class); - } - - /** - * PUT {@link LogicalSwitch} given a UUID as key and a {@link LogicalSwitch} with the new data - * - * @param logicalSwitch - * @param logicalSwitchUuid - * @throws NiciraNvpApiException - */ - public void updateLogicalSwitch(final LogicalSwitch logicalSwitch, final String logicalSwitchUuid) throws NiciraNvpApiException { - update(logicalSwitch, logicalSwitchUuid); - } - - public void deleteLogicalSwitch(final String uuid) throws NiciraNvpApiException { - delete(uuid, LogicalSwitch.class); - } - - public LogicalSwitchPort createLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { - return createWithUri(logicalSwitchPort, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT)); - } - - public void updateLogicalSwitchPort(final String logicalSwitchUuid, final LogicalSwitchPort logicalSwitchPort) throws NiciraNvpApiException { - updateWithUri(logicalSwitchPort, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPort.getUuid().toString())); - } - - public void updateLogicalSwitchPortAttachment(final String logicalSwitchUuid, final String logicalSwitchPortUuid, final Attachment attachment) throws NiciraNvpApiException { - updateWithUri(attachment, buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPortUuid) + ATTACHMENT_PATH_SEGMENT); - } - - public void deleteLogicalSwitchPort(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { - deleteWithUri(buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT, logicalSwitchPortUuid)); - } - - public String findLogicalSwitchPortUuidByVifAttachmentUuid(final String logicalSwitchUuid, final String vifAttachmentUuid) throws NiciraNvpApiException { - final String uri = buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(UUID_QUERY_PARAMETER); - params.put(NiciraConstants.ATTACHMENT_VIF_UUID_QUERY_PARAMETER_NAME, vifAttachmentUuid); - - NiciraNvpList niciraList; - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - niciraList = restConnector.executeRetrieveObject(niciraListType, uri, params); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - - final List lspl = niciraList.getResults(); - - final int listSize = lspl.size(); - if (listSize != 1) { - throw new NiciraNvpApiException("Expected 1 LogicalSwitchPort, but got " + listSize); - } - - final LogicalSwitchPort lsp = lspl.get(0); - return lsp.getUuid(); - } - - public ControlClusterStatus getControlClusterStatus() throws NiciraNvpApiException { - final String uri = NiciraConstants.CONTROL_CLUSTER_STATUS_URL; - try { - return restConnector.executeRetrieveObject(ControlClusterStatus.class, uri, new HashMap()); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public List findLogicalSwitchPortsByUuid(final String logicalSwitchUuid, final String logicalSwitchPortUuid) throws NiciraNvpApiException { - final String uri = buildLogicalSwitchElementUri(logicalSwitchUuid, LPORT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(UUID_QUERY_PARAMETER); - params.put(UUID_QUERY_PARAMETER, logicalSwitchPortUuid); - - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public List findLogicalRouterPortsByUuid(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { - final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(UUID_QUERY_PARAMETER); - params.put(UUID_QUERY_PARAMETER, logicalRouterPortUuid); - - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public LogicalRouter createLogicalRouter(final LogicalRouter logicalRouter) throws NiciraNvpApiException { - return create(logicalRouter); - } - - /** - * GET list of {@link LogicalRouter} - * - * @return - * @throws NiciraNvpApiException - */ - public List findLogicalRouter() throws NiciraNvpApiException { - return findLogicalRouter(null); - } - - /** - * GET list of {@link LogicalRouter} filtered by UUID - * - * @param uuid - * @return - * @throws NiciraNvpApiException - */ - public List findLogicalRouter(final String uuid) throws NiciraNvpApiException { - return find(Optional.fromNullable(uuid), LogicalRouter.class); - } - - public LogicalRouter findOneLogicalRouterByUuid(final String logicalRouterUuid) throws NiciraNvpApiException { - return findLogicalRouter(logicalRouterUuid).get(0); - } - - public void updateLogicalRouter(final LogicalRouter logicalRouter, final String logicalRouterUuid) throws NiciraNvpApiException { - update(logicalRouter, logicalRouterUuid); - } - - public void deleteLogicalRouter(final String logicalRouterUuid) throws NiciraNvpApiException { - deleteWithUri(buildLogicalRouterUri(logicalRouterUuid)); - } - - public LogicalRouterPort createLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - return createWithUri(logicalRouterPort, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT)); - } - - public void deleteLogicalRouterPort(final String logicalRouterUuid, final String logicalRouterPortUuid) throws NiciraNvpApiException { - deleteWithUri(buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPortUuid)); - } - - public void updateLogicalRouterPort(final String logicalRouterUuid, final LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { - updateWithUri(logicalRouterPort, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPort.getUuid().toString())); - } - - public void updateLogicalRouterPortAttachment(final String logicalRouterUuid, final String logicalRouterPortUuid, final Attachment attachment) throws NiciraNvpApiException { - updateWithUri(attachment, buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT, logicalRouterPortUuid) + ATTACHMENT_PATH_SEGMENT); - } - - public NatRule createLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { - return createWithUri(natRule, buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT)); - } - - public void updateLogicalRouterNatRule(final String logicalRouterUuid, final NatRule natRule) throws NiciraNvpApiException { - updateWithUri(natRule, buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT, natRule.getUuid().toString())); - } - - public void deleteLogicalRouterNatRule(final String logicalRouterUuid, final UUID natRuleUuid) throws NiciraNvpApiException { - deleteWithUri(buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT, natRuleUuid.toString())); - } - - public List findLogicalRouterPortByGatewayServiceAndVlanId(final String logicalRouterUuid, final String gatewayServiceUuid, final long vlanId) - throws NiciraNvpApiException { - final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); - params.put(ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER, gatewayServiceUuid); - params.put(NiciraConstants.ATTACHMENT_VLAN_PARAMETER, Long.toString(vlanId)); - - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public List findLogicalRouterPortByAttachmentLSwitchUuid(final String logicalRouterUuid, final String attachmentLSwitchUuid) throws NiciraNvpApiException{ - final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); - params.put(NiciraConstants.ATTACHMENT_LSWITCH_UUID, attachmentLSwitchUuid); - - try{ - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public List findNatRulesByLogicalRouterUuid(final String logicalRouterUuid) throws NiciraNvpApiException { - final String uri = buildLogicalRouterElementUri(logicalRouterUuid, NAT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); - - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public List findLogicalRouterPortByGatewayServiceUuid(final String logicalRouterUuid, final String l3GatewayServiceUuid) - throws NiciraNvpApiException { - final String uri = buildLogicalRouterElementUri(logicalRouterUuid, LPORT_PATH_SEGMENT); - final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); - params.put(ATTACHMENT_GWSVC_UUID_QUERY_PARAMETER, l3GatewayServiceUuid); - - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } catch (final CloudstackRESTException e) { - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - public List findL2GatewayServiceByUuidAndType(final String gatewayServiceUuid, final String serviceConfigType) throws NiciraNvpApiException{ - final String uri = buildGatewayServiceUri(); - final Map params = buildBasicParametersMap(WILDCARD_QUERY_PARAMETER); - params.put(UUID_QUERY_PARAMETER, gatewayServiceUuid); - params.put(TYPES_QUERY_PARAMETER, serviceConfigType); - - try { - final Type niciraListType = new TypeToken>() { - }.getType(); - return restConnector.> executeRetrieveObject(niciraListType, uri, params).getResults(); - } - catch (final CloudstackRESTException e){ - throw new NiciraNvpApiException(e, e.getErrorCode()); - } - } - - private static String buildGatewayServiceUri(){ - return GATEWAY_SERVICE_PREFIX; - } - - private static Map buildBasicParametersMap(final String fieldsQueryValue) { - final Map params = new HashMap(); - params.put(FIELDS_QUERY_PARAMETER, fieldsQueryValue); - return params; - } - - private static String buildUri(final String uriPrefix, final String uuid) { - return uriPrefix + "/" + uuid; - } - - private static String buildLogicalSwitchUri(final String logicalSwitchUuid) { - return buildUri(SWITCH_URI_PREFIX, logicalSwitchUuid); - } - - private static String buildLogicalSwitchElementUri(final String logicalSwitchUuid, final String logicalElementType) { - return buildLogicalSwitchUri(logicalSwitchUuid) + logicalElementType; - } - - private static String buildLogicalSwitchElementUri(final String logicalSwitchUuid, final String logicalElementType, final String elementUuid) { - return buildLogicalSwitchElementUri(logicalSwitchUuid, logicalElementType) + "/" + elementUuid.toString(); - } - - private static String buildLogicalRouterUri(final String logicalRouterUuid) { - return buildUri(ROUTER_URI_PREFIX, logicalRouterUuid); - } - - private static String buildLogicalRouterElementUri(final String logicalRouterUuid, final String logicalElementType) { - return buildLogicalRouterUri(logicalRouterUuid) + logicalElementType; - } - - private static String buildLogicalRouterElementUri(final String logicalRouterUuid, final String logicalRouterElementType, final String elementUuid) { - return buildLogicalRouterElementUri(logicalRouterUuid, logicalRouterElementType) + "/" + elementUuid.toString(); - } - - public static class Builder { - private String host; - private String username; - private String password; - private CloseableHttpClient httpClient; - private HttpClientContext httpClientContext = HttpClientContext.create(); - - public Builder host(final String host) { - this.host = host; - return this; - } - - public Builder username(final String username) { - this.username = username; - return this; - } - - public Builder password(final String password) { - this.password = password; - return this; - } - - public Builder httpClient(final CloseableHttpClient httpClient) { - this.httpClient = httpClient; - return this; - } - - public Builder httpClientContext(final HttpClientContext httpClientContext) { - this.httpClientContext = httpClientContext; - return this; - } - - public NiciraNvpApi build() { - return new NiciraNvpApi(this); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java deleted file mode 100644 index f8b3c0763cb2..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpApiException.java +++ /dev/null @@ -1,64 +0,0 @@ -// -// 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.network.nicira; - -public class NiciraNvpApiException extends Exception { - - private int errorCode; - - public NiciraNvpApiException() { - } - - public NiciraNvpApiException(final String message) { - super(message); - } - - public NiciraNvpApiException(final Throwable cause) { - super(cause); - } - - public NiciraNvpApiException(final String message, final Throwable cause) { - super(message, cause); - } - - public NiciraNvpApiException(final String message, final int errorCode){ - super(message); - this.errorCode = errorCode; - } - - public NiciraNvpApiException(final Throwable cause, final int errorCode) { - super(cause); - this.errorCode = errorCode; - } - - public NiciraNvpApiException(final String message, final Throwable cause, final int errorCode) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - public void setErrorCode(int errorCode) { - this.errorCode = errorCode; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java deleted file mode 100644 index 34b5e19c8c16..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpList.java +++ /dev/null @@ -1,48 +0,0 @@ -// -// 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.network.nicira; - -import java.util.List; - -public class NiciraNvpList { - private List results; - private int resultCount; - - public List getResults() { - return this.results; - } - - public void setResults(List results) { - this.results = results; - } - - public int getResultCount() { - return resultCount; - } - - public void setResultCount(int resultCount) { - this.resultCount = resultCount; - } - - public boolean isEmpty() { - return this.resultCount == 0; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java deleted file mode 100644 index 1c1fd7f3ace6..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraNvpTag.java +++ /dev/null @@ -1,65 +0,0 @@ -// -// 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.network.nicira; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -public class NiciraNvpTag { - private static final int TAG_MAX_LEN = 40; - protected Logger logger = LogManager.getLogger(getClass()); - private String scope; - private String tag; - - public NiciraNvpTag() { - } - - public NiciraNvpTag(String scope, String tag) { - this.scope = scope; - if (tag.length() > 40) { - logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters"); - this.tag = tag.substring(0, TAG_MAX_LEN); - } else { - this.tag = tag; - } - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - public String getTag() { - return tag; - } - - public void setTag(String tag) { - if (tag.length() > 40) { - logger.warn("tag \"" + tag + "\" too long, truncating to 40 characters"); - this.tag = tag.substring(0, 40); - } else { - this.tag = tag; - } - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java deleted file mode 100644 index f9c86be9d08f..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/NiciraRestClient.java +++ /dev/null @@ -1,204 +0,0 @@ -// -// 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.network.nicira; - -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.http.HttpEntity; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -import com.cloud.utils.rest.BasicRestClient; -import com.cloud.utils.rest.CloudstackRESTException; -import com.cloud.utils.rest.HttpConstants; -import com.cloud.utils.rest.HttpMethods; -import com.cloud.utils.rest.HttpStatusCodeHelper; -import com.cloud.utils.rest.HttpUriRequestBuilder; - -public class NiciraRestClient extends BasicRestClient { - - - private static final String CONTENT_TYPE = HttpConstants.CONTENT_TYPE; - private static final String TEXT_HTML_CONTENT_TYPE = HttpConstants.TEXT_HTML_CONTENT_TYPE; - - private static final int DEFAULT_BODY_RESP_MAX_LEN = 1024; - private static final int DEFAULT_EXECUTION_LIMIT = 5; - - private final ExecutionCounter counter; - private final int maxResponseErrorMesageLength; - private final int executionLimit; - - private final String username; - private final String password; - private final String loginUrl; - - private NiciraRestClient(final Builder builder) { - super(builder.client, builder.clientContext, builder.hostname); - executionLimit = builder.executionLimit; - counter = new ExecutionCounter(executionLimit); - maxResponseErrorMesageLength = builder.maxResponseErrorMesageLength; - username = builder.username; - password = builder.password; - loginUrl = builder.loginUrl; - } - - public static Builder create() { - return new Builder(); - } - - @Override - public CloseableHttpResponse execute(final HttpUriRequest request) throws CloudstackRESTException { - return execute(request, 0); - } - - CloseableHttpResponse execute(final HttpUriRequest request, final int previousStatusCode) throws CloudstackRESTException { - if (counter.hasReachedExecutionLimit()) { - throw new CloudstackRESTException("Reached max executions limit of " + executionLimit); - } - counter.incrementExecutionCounter(); - logger.debug("Executing " + request.getMethod() + " request [execution count = " + counter.getValue() + "]"); - final CloseableHttpResponse response = super.execute(request); - - final StatusLine statusLine = response.getStatusLine(); - final int statusCode = statusLine.getStatusCode(); - logger.debug("Status of last request: " + statusLine.toString()); - if (HttpStatusCodeHelper.isUnauthorized(statusCode)) { - return handleUnauthorizedResponse(request, previousStatusCode, response, statusCode); - } else if (HttpStatusCodeHelper.isSuccess(statusCode)) { - return handleSuccessResponse(request, response); - } else if (HttpStatusCodeHelper.isConflict(statusCode)) { - throw new CloudstackRESTException("Conflict: " + statusLine.getReasonPhrase(), statusCode); - } else { - throw new CloudstackRESTException("Unexpected status code: " + statusCode, statusCode); - } - } - - private CloseableHttpResponse handleUnauthorizedResponse(final HttpUriRequest request, final int previousStatusCode, final CloseableHttpResponse response, final int statusCode) - throws CloudstackRESTException { - super.closeResponse(response); - if (HttpStatusCodeHelper.isUnauthorized(previousStatusCode)) { - logger.error(responseToErrorMessage(response)); - throw new CloudstackRESTException("Two consecutive failed attempts to authenticate against REST server"); - } - final HttpUriRequest authenticateRequest = createAuthenticationRequest(); - final CloseableHttpResponse loginResponse = execute(authenticateRequest, statusCode); - final int loginStatusCode = loginResponse.getStatusLine().getStatusCode(); - super.closeResponse(loginResponse); - return execute(request, loginStatusCode); - } - - private CloseableHttpResponse handleSuccessResponse(final HttpUriRequest request, final CloseableHttpResponse response) { - if (!request.getURI().getPath().contains(loginUrl)) { - counter.resetExecutionCounter(); - } - return response; - } - - private HttpUriRequest createAuthenticationRequest() { - final Map parameters = new LinkedHashMap<>(); - parameters.put("username", username); - parameters.put("password", password); - return HttpUriRequestBuilder.create() - .method(HttpMethods.POST) - .methodParameters(parameters) - .path(loginUrl) - .build(); - } - - private String responseToErrorMessage(final CloseableHttpResponse response) { - String errorMessage = response.getStatusLine().toString(); - if (response.containsHeader(CONTENT_TYPE) && TEXT_HTML_CONTENT_TYPE.equals(response.getFirstHeader(CONTENT_TYPE).getValue())) { - try { - final HttpEntity entity = response.getEntity(); - final String respobnseBody = EntityUtils.toString(entity); - errorMessage = respobnseBody.subSequence(0, maxResponseErrorMesageLength).toString(); - } catch (final IOException e) { - logger.debug("Could not read response body. Response: " + response, e); - } - } - - return errorMessage; - } - - protected static class Builder extends BasicRestClient.Builder { - private CloseableHttpClient client; - private HttpClientContext clientContext; - private String hostname; - private String username; - private String password; - private String loginUrl; - private int executionLimit = DEFAULT_EXECUTION_LIMIT; - private int maxResponseErrorMesageLength = DEFAULT_BODY_RESP_MAX_LEN; - - public Builder hostname(final String hostname) { - this.hostname = hostname; - return this; - } - - public Builder username(final String username) { - this.username = username; - return this; - } - - public Builder password(final String password) { - this.password = password; - return this; - } - - public Builder loginUrl(final String loginUrl) { - this.loginUrl = loginUrl; - return this; - } - - @Override - public Builder client(final CloseableHttpClient client) { - this.client = client; - return this; - } - - @Override - public Builder clientContext(final HttpClientContext clientContext) { - this.clientContext = clientContext; - return this; - } - - public Builder executionLimit(final int executionLimit) { - this.executionLimit = executionLimit; - return this; - } - - public Builder maxResponseErrorMesageLength(final int maxResponseErrorMesageLength) { - this.maxResponseErrorMesageLength = maxResponseErrorMesageLength; - return this; - } - - @Override - public NiciraRestClient build() { - return new NiciraRestClient(this); - } - - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java deleted file mode 100644 index 26fa04861132..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/PatchAttachment.java +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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.network.nicira; - -/** - * - */ -public class PatchAttachment extends Attachment { - private final String type = "PatchAttachment"; - private String peerPortUuid; - - public PatchAttachment(String peerPortUuid) { - this.peerPortUuid = peerPortUuid; - } - - public String getPeerPortUuid() { - return peerPortUuid; - } - - public void setPeerPortUuid(String peerPortUuid) { - this.peerPortUuid = peerPortUuid; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java deleted file mode 100644 index 8dd884072be3..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RouterNextHop.java +++ /dev/null @@ -1,40 +0,0 @@ -// -// 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.network.nicira; - -/** - * - */ -public class RouterNextHop { - private String gatewayIpAddress; - private final String type = "RouterNextHop"; - - public RouterNextHop(String gatewayIpAddress) { - this.gatewayIpAddress = gatewayIpAddress; - } - - public String getGatewayIpAddress() { - return gatewayIpAddress; - } - - public void setGatewayIpAddress(String gatewayIpAddress) { - this.gatewayIpAddress = gatewayIpAddress; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java deleted file mode 100644 index 5eaef0a699dd..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -// -// 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.network.nicira; - -public class RoutingConfig { - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java deleted file mode 100644 index db6a6b61e49d..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingConfigAdapter.java +++ /dev/null @@ -1,52 +0,0 @@ -// -// 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.network.nicira; - -import java.lang.reflect.Type; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; - -public class RoutingConfigAdapter implements JsonDeserializer { - - private static final String ROUTING_TABLE_ROUTING_CONFIG = "RoutingTableRoutingConfig"; - private static final String SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG = "SingleDefaultRouteImplicitRoutingConfig"; - - @Override - public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { - final JsonObject jsonObject = jsonElement.getAsJsonObject(); - - if (!jsonObject.has("type")) { - throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object"); - } - - final String routingConfigType = jsonObject.get("type").getAsString(); - if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) { - return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class); - } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) { - return context.deserialize(jsonElement, RoutingTableRoutingConfig.class); - } - - throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\""); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java deleted file mode 100644 index f0a80b85e5b3..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/RoutingTableRoutingConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -// -// 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.network.nicira; - -/** - * - */ -public class RoutingTableRoutingConfig extends RoutingConfig { - public final String type = "RoutingTableRoutingConfig"; - - public RoutingTableRoutingConfig() { - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java deleted file mode 100644 index d83ce49db12e..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityProfile.java +++ /dev/null @@ -1,24 +0,0 @@ -// -// 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.network.nicira; - -@SuppressWarnings("serial") -public class SecurityProfile extends AccessConfiguration { -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java deleted file mode 100644 index e23593cb3d62..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SecurityRule.java +++ /dev/null @@ -1,138 +0,0 @@ -// -// 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.network.nicira; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; - -@SuppressWarnings("serial") -public class SecurityRule extends AccessRule { - - protected String ipPrefix; - - protected int portRangeMin; - - protected int portRangeMax; - - protected String profileUuid; - - - /** - * Default constructor - */ - public SecurityRule() { - } - - /** - * Fully parameterized constructor - */ - public SecurityRule(final String ethertype, final String ipPrefix, final String profileUuid, - final int portRangeMin, final int portRangeMax, final int protocol) { - this.ethertype = ethertype; - this.ipPrefix = ipPrefix; - this.portRangeMin = portRangeMin; - this.portRangeMax = portRangeMax; - this.profileUuid = profileUuid; - this.protocol = protocol; - } - - @Override - public String getEthertype() { - return ethertype; - } - - @Override - public void setEthertype(final String ethertype) { - this.ethertype = ethertype; - } - - public String getIpPrefix() { - return ipPrefix; - } - - public void setIpPrefix(final String ipPrefix) { - this.ipPrefix = ipPrefix; - } - - public int getPortRangeMin() { - return portRangeMin; - } - - public void setPortRangeMin(final int portRangeMin) { - this.portRangeMin = portRangeMin; - } - - public int getPortRangeMax() { - return portRangeMax; - } - - public void setPortRangeMax(final int portRangeMax) { - this.portRangeMax = portRangeMax; - } - - public String getProfileUuid() { - return profileUuid; - } - - public void setProfileUuid(final String profileUuid) { - this.profileUuid = profileUuid; - } - - @Override - public int getProtocol() { - return protocol; - } - - @Override - public void setProtocol(final int protocol) { - this.protocol = protocol; - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 31) - .append(ethertype).append(ipPrefix) - .append(portRangeMin).append(portRangeMax) - .append(profileUuid).append(protocol) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(obj instanceof SecurityRule)) { - return false; - } - final SecurityRule another = (SecurityRule) obj; - return new EqualsBuilder() - .append(ethertype, another.ethertype) - .append(ipPrefix, another.ipPrefix) - .append(portRangeMin, another.portRangeMin) - .append(portRangeMax, another.portRangeMax) - .append(profileUuid, another.profileUuid) - .append(protocol, another.protocol) - .isEquals(); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java deleted file mode 100644 index ea5df2cd1fd1..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SingleDefaultRouteImplicitRoutingConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -// -// 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.network.nicira; - -/** - * - */ -public class SingleDefaultRouteImplicitRoutingConfig extends RoutingConfig { - public RouterNextHop defaultRouteNextHop; - public final String type = "SingleDefaultRouteImplicitRoutingConfig"; - - public SingleDefaultRouteImplicitRoutingConfig(final RouterNextHop routerNextHop) { - defaultRouteNextHop = routerNextHop; - } - - public RouterNextHop getDefaultRouteNextHop() { - return defaultRouteNextHop; - } - - public void setDefaultRouteNextHop(final RouterNextHop defaultRouteNextHop) { - this.defaultRouteNextHop = defaultRouteNextHop; - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java deleted file mode 100644 index b95cb9aeb5d4..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/SourceNatRule.java +++ /dev/null @@ -1,119 +0,0 @@ -// -// 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.network.nicira; - -public class SourceNatRule extends NatRule { - private String toSourceIpAddressMax; - private String toSourceIpAddressMin; - private Integer toSourcePort; - - public SourceNatRule() { - setType("SourceNatRule"); - } - - public String getToSourceIpAddressMax() { - return toSourceIpAddressMax; - } - - public void setToSourceIpAddressMax(final String toSourceIpAddressMax) { - this.toSourceIpAddressMax = toSourceIpAddressMax; - } - - public String getToSourceIpAddressMin() { - return toSourceIpAddressMin; - } - - public void setToSourceIpAddressMin(final String toSourceIpAddressMin) { - this.toSourceIpAddressMin = toSourceIpAddressMin; - } - - public Integer getToSourcePort() { - return toSourcePort; - } - - public void setToSourcePort(final Integer toSourcePort) { - this.toSourcePort = toSourcePort; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((toSourceIpAddressMax == null) ? 0 : toSourceIpAddressMax.hashCode()); - result = prime * result + ((toSourceIpAddressMin == null) ? 0 : toSourceIpAddressMin.hashCode()); - result = prime * result + ((toSourcePort == null) ? 0 : toSourcePort.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - SourceNatRule other = (SourceNatRule)obj; - if (toSourceIpAddressMax == null) { - if (other.toSourceIpAddressMax != null) - return false; - } else if (!toSourceIpAddressMax.equals(other.toSourceIpAddressMax)) - return false; - if (toSourceIpAddressMin == null) { - if (other.toSourceIpAddressMin != null) - return false; - } else if (!toSourceIpAddressMin.equals(other.toSourceIpAddressMin)) - return false; - if (toSourcePort == null) { - if (other.toSourcePort != null) - return false; - } else if (!toSourcePort.equals(other.toSourcePort)) - return false; - return true; - } - - @Override - public boolean equalsIgnoreUuid(final Object obj) { - if (this == obj) - return true; - if (!super.equalsIgnoreUuid(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - SourceNatRule other = (SourceNatRule)obj; - if (toSourceIpAddressMax == null) { - if (other.toSourceIpAddressMax != null) - return false; - } else if (!toSourceIpAddressMax.equals(other.toSourceIpAddressMax)) - return false; - if (toSourceIpAddressMin == null) { - if (other.toSourceIpAddressMin != null) - return false; - } else if (!toSourceIpAddressMin.equals(other.toSourceIpAddressMin)) - return false; - if (toSourcePort == null) { - if (other.toSourcePort != null) - return false; - } else if (!toSourcePort.equals(other.toSourcePort)) - return false; - return true; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java deleted file mode 100644 index c643876d93cf..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/TransportZoneBinding.java +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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.network.nicira; - -public class TransportZoneBinding { - private String zoneUuid; - private String transportType; - - public TransportZoneBinding() { - } - - public TransportZoneBinding(String zoneUuid, String transportType) { - this.zoneUuid = zoneUuid; - this.transportType = transportType; - } - - public String getZoneUuid() { - return zoneUuid; - } - - public void setZoneUuid(String zoneUuid) { - this.zoneUuid = zoneUuid; - } - - public String getTransportType() { - return transportType; - } - - public void setTransportType(String transportType) { - this.transportType = transportType; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java deleted file mode 100644 index fe7d93adead8..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/nicira/VifAttachment.java +++ /dev/null @@ -1,78 +0,0 @@ -// -// 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.network.nicira; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -public class VifAttachment extends Attachment { - private final String type = "VifAttachment"; - private String vifUuid; - - public VifAttachment() { - } - - public VifAttachment(final String vifUuid) { - this.vifUuid = vifUuid; - } - - public String getVifUuid() { - return vifUuid; - } - - public void setVifUuid(final String vifUuid) { - this.vifUuid = vifUuid; - } - - public String getType() { - return type; - } - - - @Override - public String toString() { - return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE, false); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 31) - .append(this.getClass()) - .append(vifUuid) - .toHashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (!(this.getClass().isInstance(obj))) { - return false; - } - final VifAttachment another = (VifAttachment) obj; - return new EqualsBuilder().append(vifUuid, another.vifUuid).isEquals(); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java deleted file mode 100644 index 00e423806d81..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpRequestWrapper.java +++ /dev/null @@ -1,77 +0,0 @@ -// -// 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.network.resource; - -import java.util.Hashtable; -import java.util.Set; - -import org.reflections.Reflections; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.RequestWrapper; -import com.cloud.resource.ServerResource; - -public class NiciraNvpRequestWrapper extends RequestWrapper { - - private static NiciraNvpRequestWrapper instance; - - static { - instance = new NiciraNvpRequestWrapper(); - } - - Reflections baseWrappers = new Reflections("com.cloud.network.resource.wrapper"); - @SuppressWarnings("rawtypes") - Set> baseSet = baseWrappers.getSubTypesOf(CommandWrapper.class); - - private NiciraNvpRequestWrapper() { - init(); - } - - @SuppressWarnings("rawtypes") - private void init() { - // NiciraNvpResource commands - final Hashtable, CommandWrapper> niciraCommands = processAnnotations(baseSet); - - resources.put(NiciraNvpResource.class, niciraCommands); - } - - public static NiciraNvpRequestWrapper getInstance() { - return instance; - } - - @SuppressWarnings({"rawtypes" }) - @Override - public Answer execute(final Command command, final ServerResource serverResource) { - final Class resourceClass = serverResource.getClass(); - - final Hashtable, CommandWrapper> resourceCommands = retrieveResource(command, resourceClass); - - CommandWrapper commandWrapper = retrieveCommands(command.getClass(), resourceCommands); - - while (commandWrapper == null) { - //Could not find the command in the given resource, will traverse the family tree. - commandWrapper = retryWhenAllFails(command, resourceClass, resourceCommands); - } - - return commandWrapper.execute(command, serverResource); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java deleted file mode 100644 index c2841f18c1cb..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpResource.java +++ /dev/null @@ -1,357 +0,0 @@ -// -// 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.network.resource; - -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.util.Map; - -import javax.naming.ConfigurationException; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.IAgentControl; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.StartupNiciraNvpCommand; -import com.cloud.host.Host; -import com.cloud.host.Host.Type; -import com.cloud.network.nicira.ControlClusterStatus; -import com.cloud.network.nicira.ControlClusterStatus.ClusterRoleConfig; -import com.cloud.network.nicira.DestinationNatRule; -import com.cloud.network.nicira.Match; -import com.cloud.network.nicira.NatRule; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.SourceNatRule; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.ServerResource; -import com.cloud.utils.rest.CloudstackRESTException; -import com.cloud.utils.rest.HttpClientHelper; -import com.cloud.utils.nicira.nvp.plugin.NiciraNvpApiVersion; - -public class NiciraNvpResource implements ServerResource { - - protected Logger logger = LogManager.getLogger(getClass()); - - public static final int NAME_MAX_LEN = 40; - public static final int NUM_RETRIES = 2; - private static final int MAX_REDIRECTS = 5; - - private String name; - private String guid; - private String zoneId; - - private NiciraNvpApi niciraNvpApi; - private NiciraNvpUtilities niciraNvpUtilities; - private CommandRetryUtility retryUtility; - - protected NiciraNvpApi createNiciraNvpApi(final String host, final String username, final String password) throws CloudstackRESTException { - try { - return NiciraNvpApi.create().host(host).username(username).password(password).httpClient(HttpClientHelper.createHttpClient(MAX_REDIRECTS)).build(); - } catch (final KeyManagementException e) { - throw new CloudstackRESTException("Could not create HTTP client", e); - } catch (final NoSuchAlgorithmException e) { - throw new CloudstackRESTException("Could not create HTTP client", e); - } catch (final KeyStoreException e) { - throw new CloudstackRESTException("Could not create HTTP client", e); - } - } - - @Override - public boolean configure(final String ignoredName, final Map params) throws ConfigurationException { - - name = (String) params.get("name"); - if (name == null) { - throw new ConfigurationException("Unable to find name"); - } - - guid = (String) params.get("guid"); - if (guid == null) { - throw new ConfigurationException("Unable to find the guid"); - } - - zoneId = (String) params.get("zoneId"); - if (zoneId == null) { - throw new ConfigurationException("Unable to find zone"); - } - - final String ip = (String) params.get("ip"); - if (ip == null) { - throw new ConfigurationException("Unable to find IP"); - } - - final String adminuser = (String) params.get("adminuser"); - if (adminuser == null) { - throw new ConfigurationException("Unable to find admin username"); - } - - final String adminpass = (String) params.get("adminpass"); - if (adminpass == null) { - throw new ConfigurationException("Unable to find admin password"); - } - - niciraNvpUtilities = NiciraNvpUtilities.getInstance(); - retryUtility = CommandRetryUtility.getInstance(); - retryUtility.setServerResource(this); - - try { - niciraNvpApi = createNiciraNvpApi(ip, adminuser, adminpass); - } catch (final CloudstackRESTException e) { - throw new ConfigurationException("Could not create a Nicira Nvp API client: " + e.getMessage()); - } - - return true; - } - - public NiciraNvpApi getNiciraNvpApi() { - return niciraNvpApi; - } - - public NiciraNvpUtilities getNiciraNvpUtilities() { - return niciraNvpUtilities; - } - - public CommandRetryUtility getRetryUtility() { - return retryUtility; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public String getName() { - return name; - } - - @Override - public Type getType() { - // Think up a better name for this Type? - return Host.Type.L2Networking; - } - - @Override - public StartupCommand[] initialize() { - final StartupNiciraNvpCommand sc = new StartupNiciraNvpCommand(); - sc.setGuid(guid); - sc.setName(name); - sc.setDataCenter(zoneId); - sc.setPod(""); - sc.setPrivateIpAddress(""); - sc.setStorageIpAddress(""); - sc.setVersion(NiciraNvpResource.class.getPackage().getImplementationVersion()); - return new StartupCommand[] { sc }; - } - - @Override - public PingCommand getCurrentStatus(final long id) { - try { - final ControlClusterStatus ccs = niciraNvpApi.getControlClusterStatus(); - getApiProviderMajorityVersion(ccs); - if (!"stable".equals(ccs.getClusterStatus())) { - logger.error("ControlCluster state is not stable: " + ccs.getClusterStatus()); - return null; - } - } catch (final NiciraNvpApiException e) { - logger.error("getControlClusterStatus failed", e); - return null; - } - return new PingCommand(Host.Type.L2Networking, id); - } - - private void getApiProviderMajorityVersion(ControlClusterStatus ccs) { - ClusterRoleConfig[] configuredRoles = ccs.getConfiguredRoles(); - if (configuredRoles != null){ - String apiProviderMajorityVersion = searchApiProvider(configuredRoles); - NiciraNvpApiVersion.setNiciraApiVersion(apiProviderMajorityVersion); - NiciraNvpApiVersion.logNiciraApiVersion(); - } - } - - private String searchApiProvider(ClusterRoleConfig[] configuredRoles) { - for (int i = 0; i < configuredRoles.length; i++) { - if (configuredRoles[i].getRole() != null && configuredRoles[i].getRole().equals("api_provider")){ - return configuredRoles[i].getMajorityVersion(); - } - } - return null; - } - - @Override - public Answer executeRequest(final Command cmd) { - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - try { - return wrapper.execute(cmd, this); - } catch (final Exception e) { - logger.debug("Received unsupported command " + cmd.toString()); - return Answer.createUnsupportedCommandAnswer(cmd); - } - } - - @Override - public void disconnected() { - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public void setAgentControl(final IAgentControl agentControl) { - } - - public String natRuleToString(final NatRule rule) { - - final StringBuilder natRuleStr = new StringBuilder(); - natRuleStr.append("Rule "); - natRuleStr.append(rule.getUuid()); - natRuleStr.append(" ("); - natRuleStr.append(rule.getType()); - natRuleStr.append(") :"); - final Match m = rule.getMatch(); - natRuleStr.append("match ("); - natRuleStr.append(m.getProtocol()); - natRuleStr.append(" "); - natRuleStr.append(m.getSourceIpAddresses()); - natRuleStr.append(" ["); - natRuleStr.append(m.getSourcePort()); - natRuleStr.append(" ] -> "); - natRuleStr.append(m.getDestinationIpAddresses()); - natRuleStr.append(" ["); - natRuleStr.append(m.getDestinationPort()); - natRuleStr.append(" ]) -->"); - if ("SourceNatRule".equals(rule.getType())) { - natRuleStr.append(((SourceNatRule) rule).getToSourceIpAddressMin()); - natRuleStr.append("-"); - natRuleStr.append(((SourceNatRule) rule).getToSourceIpAddressMax()); - natRuleStr.append(" ["); - natRuleStr.append(((SourceNatRule) rule).getToSourcePort()); - natRuleStr.append(" ])"); - } else { - natRuleStr.append(((DestinationNatRule) rule).getToDestinationIpAddress()); - natRuleStr.append(" ["); - natRuleStr.append(((DestinationNatRule) rule).getToDestinationPort()); - natRuleStr.append(" ])"); - } - return natRuleStr.toString(); - } - - public String truncate(final String string, final int length) { - if (string.length() <= length) { - return string; - } else { - return string.substring(0, length); - } - } - - public NatRule[] generateStaticNatRulePair(final String insideIp, final String outsideIp) { - final NatRule[] rulepair = new NatRule[2]; - rulepair[0] = new DestinationNatRule(); - rulepair[0].setType("DestinationNatRule"); - rulepair[0].setOrder(100); - rulepair[1] = new SourceNatRule(); - rulepair[1].setType("SourceNatRule"); - rulepair[1].setOrder(100); - - Match m = new Match(); - m.setDestinationIpAddresses(outsideIp); - rulepair[0].setMatch(m); - ((DestinationNatRule) rulepair[0]).setToDestinationIpAddress(insideIp); - - // create matching snat rule - m = new Match(); - m.setSourceIpAddresses(insideIp); - rulepair[1].setMatch(m); - ((SourceNatRule) rulepair[1]).setToSourceIpAddressMin(outsideIp); - ((SourceNatRule) rulepair[1]).setToSourceIpAddressMax(outsideIp); - - return rulepair; - - } - - public NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts, - final String protocol) { - // Start with a basic static nat rule, then add port and protocol details - final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp); - - ((DestinationNatRule) rulepair[0]).setToDestinationPort(insidePorts[0]); - rulepair[0].getMatch().setDestinationPort(outsidePorts[0]); - rulepair[0].setOrder(50); - rulepair[0].getMatch().setEthertype("IPv4"); - if ("tcp".equals(protocol)) { - rulepair[0].getMatch().setProtocol(6); - } else if ("udp".equals(protocol)) { - rulepair[0].getMatch().setProtocol(17); - } - - ((SourceNatRule) rulepair[1]).setToSourcePort(outsidePorts[0]); - rulepair[1].getMatch().setSourcePort(insidePorts[0]); - rulepair[1].setOrder(50); - rulepair[1].getMatch().setEthertype("IPv4"); - if ("tcp".equals(protocol)) { - rulepair[1].getMatch().setProtocol(6); - } else if ("udp".equals(protocol)) { - rulepair[1].getMatch().setProtocol(17); - } - - return rulepair; - - } - - @Override - public void setName(final String name) { - // TODO Auto-generated method stub - } - - @Override - public void setConfigParams(final Map params) { - // TODO Auto-generated method stub - } - - @Override - public Map getConfigParams() { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getRunLevel() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void setRunLevel(final int level) { - // TODO Auto-generated method stub - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java deleted file mode 100644 index 42dbeebaebe3..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/NiciraNvpUtilities.java +++ /dev/null @@ -1,65 +0,0 @@ -// -// 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.network.resource; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.agent.api.CreateLogicalSwitchPortCommand; -import com.cloud.network.nicira.LogicalSwitch; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.NiciraNvpTag; -import com.cloud.network.nicira.VifAttachment; - -public class NiciraNvpUtilities { - - private static NiciraNvpUtilities instance; - - static { - instance = new NiciraNvpUtilities(); - } - - private NiciraNvpUtilities() { - } - - public static NiciraNvpUtilities getInstance() { - return instance; - } - - public LogicalSwitch createLogicalSwitch() { - final LogicalSwitch logicalSwitch = new LogicalSwitch(); - return logicalSwitch; - } - - public LogicalSwitchPort createLogicalSwitchPort(final CreateLogicalSwitchPortCommand command) { - final String attachmentUuid = command.getAttachmentUuid(); - - // Tags set to scope cs_account and account name - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", command.getOwnerName())); - - final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true); - return logicalSwitchPort; - } - - public VifAttachment createVifAttachment(final String attachmentUuid) { - return new VifAttachment(attachmentUuid); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapper.java deleted file mode 100644 index 821b9f6d87c0..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapper.java +++ /dev/null @@ -1,61 +0,0 @@ -// -// 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.network.resource.wrapper; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckHealthAnswer; -import com.cloud.agent.api.CheckHealthCommand; -import com.cloud.network.nicira.ControlClusterStatus; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = CheckHealthCommand.class) -public class NiciraCheckHealthCommandWrapper extends CommandWrapper { - - private static final String CONTROL_CLUSTER_STATUS_IS_STABLE = "stable"; - - @Override - public Answer execute(final CheckHealthCommand command, final NiciraNvpResource serverResource) { - final NiciraNvpApi niciraNvpApi = serverResource.getNiciraNvpApi(); - boolean healthy = true; - try { - final ControlClusterStatus clusterStatus = niciraNvpApi.getControlClusterStatus(); - final String status = clusterStatus.getClusterStatus(); - if (clusterIsUnstable(status)) { - logger.warn("Control cluster is not stable. Current status is " + status); - healthy = false; - } - } catch (final NiciraNvpApiException e) { - logger.error("Exception caught while checking control cluster status during health check", e); - healthy = false; - } - - return new CheckHealthAnswer(command, healthy); - } - - protected boolean clusterIsUnstable(final String clusterStatus) { - return !CONTROL_CLUSTER_STATUS_IS_STABLE.equals(clusterStatus); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java deleted file mode 100644 index 7b7108c3d419..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java +++ /dev/null @@ -1,120 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.network.nicira.NatRule; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = ConfigurePortForwardingRulesOnLogicalRouterCommand.class) -public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(final ConfigurePortForwardingRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - try { - final List existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid()); - // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) - // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule - // Any other SourceNat rule should have a corresponding DestinationNat rule - - for (final PortForwardingRuleTO rule : command.getRules()) { - if (rule.isAlreadyAdded() && !rule.revoked()) { - // Don't need to do anything - continue; - } - - if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1]) { - return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, false, "Nicira NVP doesn't support port ranges for port forwarding"); - } - - final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), - rule.getProtocol()); - - NatRule incoming = null; - NatRule outgoing = null; - - for (final NatRule storedRule : existingRules) { - if (storedRule.equalsIgnoreUuid(rulepair[1])) { - // The outgoing rule exists - outgoing = storedRule; - logger.debug("Found matching outgoing rule " + outgoing.getUuid()); - if (incoming != null) { - break; - } - } else if (storedRule.equalsIgnoreUuid(rulepair[0])) { - // The incoming rule exists - incoming = storedRule; - logger.debug("Found matching incoming rule " + incoming.getUuid()); - if (outgoing != null) { - break; - } - } - } - if (incoming != null && outgoing != null) { - if (rule.revoked()) { - logger.debug("Deleting incoming rule " + incoming.getUuid()); - niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid()); - - logger.debug("Deleting outgoing rule " + outgoing.getUuid()); - niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid()); - } - } else { - if (rule.revoked()) { - logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp()); - break; - } - - rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]); - logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0])); - - try { - rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]); - logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1])); - } catch (final NiciraNvpApiException ex) { - logger.warn("NiciraNvpApiException during create call, rolling back previous create"); - niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid()); - throw ex; // Rethrow the original exception - } - - } - } - return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " PortForwarding rules applied"); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, ConfigurePortForwardingRulesOnLogicalRouterAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java deleted file mode 100644 index b851af8bd48d..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java +++ /dev/null @@ -1,61 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.List; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; -import com.cloud.network.nicira.LogicalRouterPort; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = ConfigurePublicIpsOnLogicalRouterCommand.class) -public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final ConfigurePublicIpsOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - final List ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid()); - if (ports.size() != 1) { - return new ConfigurePublicIpsOnLogicalRouterAnswer(command, false, "No logical router ports found, unable to set ip addresses"); - } - final LogicalRouterPort lrp = ports.get(0); - lrp.setIpAddresses(command.getPublicCidrs()); - niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp); - - return new ConfigurePublicIpsOnLogicalRouterAnswer(command, true, "Configured " + command.getPublicCidrs().size() + " ip addresses on logical router uuid " + - command.getLogicalRouterUuid()); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, ConfigurePublicIpsOnLogicalRouterAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkUuidCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkUuidCommandWrapper.java deleted file mode 100644 index bdbf612d3afd..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkUuidCommandWrapper.java +++ /dev/null @@ -1,194 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NAME_MAX_LEN; -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.ArrayList; -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ConfigureSharedNetworkUuidAnswer; -import com.cloud.agent.api.ConfigureSharedNetworkUuidCommand; -import com.cloud.network.nicira.LogicalRouterPort; -import com.cloud.network.nicira.LogicalSwitch; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpTag; -import com.cloud.network.nicira.PatchAttachment; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.rest.HttpStatusCodeHelper; - -@ResourceWrapper(handles = ConfigureSharedNetworkUuidCommand.class) -public final class NiciraNvpConfigureSharedNetworkUuidCommandWrapper extends CommandWrapper{ - - - @Override - public Answer execute(ConfigureSharedNetworkUuidCommand command, NiciraNvpResource niciraNvpResource) { - final String logicalRouterUuid = command.getLogicalRouterUuid(); - final String logicalSwitchUuid = command.getLogicalSwitchUuid(); - final String portIpAddress = command.getPortIpAddress(); - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", command.getOwnerName())); - final long networkId = command.getNetworkId(); - - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - logger.debug("Attaching Logical Switch " + logicalSwitchUuid + " on Logical Router " + logicalRouterUuid + " for Shared Network " + networkId); - - //Step 1: Get lSwitch displayName - logger.info("Looking for Logical Switch " + logicalSwitchUuid + " display name"); - String logicalSwitchDisplayName; - try{ - List lSwitchList = niciraNvpApi.findLogicalSwitch(logicalSwitchUuid); - if (lSwitchList != null){ - if (lSwitchList.size() == 1){ - logicalSwitchDisplayName = lSwitchList.get(0).getDisplayName(); - } - else { - logger.error("More than one Logical Switch found with uuid " + logicalSwitchUuid); - throw new CloudRuntimeException("More than one Logical Switch found with uuid=" + logicalSwitchUuid); - } - } - else { - logger.error("Logical Switch " + logicalSwitchUuid + " not found"); - throw new CloudRuntimeException("Logical Switch " + logicalSwitchUuid + " not found"); - } - } - catch (NiciraNvpApiException e){ - logger.warn("Logical Switch " + logicalSwitchUuid + " not found, retrying"); - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, ConfigureSharedNetworkUuidAnswer.class, e); - } - catch (CloudRuntimeException e){ - logger.info("Shared network UUID vlan id failed due to : " + e.getMessage()); - return new ConfigureSharedNetworkUuidAnswer(command, false, e.getMessage()); - } - logger.info("Found display name " + logicalSwitchDisplayName + " for Logical Switch " + logicalSwitchUuid); - - - //Step 2: Create lRouterPort - logger.debug("Creating Logical Router Port in Logical Router " + logicalRouterUuid); - LogicalRouterPort lRouterPort = null; - try { - lRouterPort = new LogicalRouterPort(); - lRouterPort.setAdminStatusEnabled(true); - lRouterPort.setDisplayName(niciraNvpResource.truncate(logicalSwitchDisplayName + "-uplink", NAME_MAX_LEN)); - lRouterPort.setTags(tags); - final List ipAddresses = new ArrayList(); - ipAddresses.add(portIpAddress); - lRouterPort.setIpAddresses(ipAddresses); - lRouterPort = niciraNvpApi.createLogicalRouterPort(logicalRouterUuid, lRouterPort); - } - catch (NiciraNvpApiException e){ - logger.warn("Could not create Logical Router Port on Logical Router " + logicalRouterUuid + " due to: " + e.getMessage() + ", retrying"); - return handleException(e, command, niciraNvpResource); - } - logger.debug("Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") successfully created in Logical Router " + logicalRouterUuid); - - - //Step 3: Create lSwitchPort - logger.debug("Creating Logical Switch Port in Logical Switch " + logicalSwitchUuid + " (" + logicalSwitchDisplayName + ")"); - LogicalSwitchPort lSwitchPort = null; - try { - lSwitchPort = new LogicalSwitchPort(niciraNvpResource.truncate("lrouter-uplink", NAME_MAX_LEN), tags, true); - lSwitchPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lSwitchPort); - } - catch (NiciraNvpApiException e){ - logger.warn("Could not create Logical Switch Port on Logical Switch " + logicalSwitchUuid + " (" + logicalSwitchDisplayName + ") due to: " + e.getMessage()); - cleanupLRouterPort(logicalRouterUuid, lRouterPort, niciraNvpApi); - return handleException(e, command, niciraNvpResource); - } - logger.debug("Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") successfully created in Logical Switch " + logicalSwitchUuid + " (" + logicalSwitchDisplayName + ")"); - - - //Step 4: Attach lRouterPort to lSwitchPort with a PatchAttachment - logger.debug("Attaching Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") to Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") with a PatchAttachment"); - try { - niciraNvpApi.updateLogicalRouterPortAttachment(logicalRouterUuid, lRouterPort.getUuid(), new PatchAttachment(lSwitchPort.getUuid())); - } - catch (NiciraNvpApiException e) { - logger.warn("Could not attach Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") to Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") due to: " + e.getMessage() + ", retrying"); - cleanupLRouterPort(logicalRouterUuid, lRouterPort, niciraNvpApi); - cleanupLSwitchPort(logicalSwitchUuid, lSwitchPort, niciraNvpApi); - return handleException(e, command, niciraNvpResource); - } - logger.debug("Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") successfully attached to Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") with a PatchAttachment"); - - - //Step 5: Attach lSwitchPort to lRouterPort with a PatchAttachment - logger.debug("Attaching Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") to Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") with a PatchAttachment"); - try { - niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lSwitchPort.getUuid(), new PatchAttachment(lRouterPort.getUuid())); - } - catch (NiciraNvpApiException e){ - logger.warn("Could not attach Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") to Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") due to: " + e.getMessage() + ", retrying"); - cleanupLRouterPort(logicalRouterUuid, lRouterPort, niciraNvpApi); - cleanupLSwitchPort(logicalSwitchUuid, lSwitchPort, niciraNvpApi); - return handleException(e, command, niciraNvpResource); - } - logger.debug("Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") successfully attached to Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") with a PatchAttachment"); - - logger.info("Successfully attached Logical Switch " + logicalSwitchUuid + " on Logical Router " + logicalRouterUuid + " for Shared Network " + networkId); - return new ConfigureSharedNetworkUuidAnswer(command, true, "OK"); - } - - private void cleanupLSwitchPort(String logicalSwitchUuid, LogicalSwitchPort lSwitchPort, NiciraNvpApi niciraNvpApi) { - logger.warn("Deleting previously created Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") from Logical Switch " + logicalSwitchUuid); - try { - niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lSwitchPort.getUuid()); - } catch (NiciraNvpApiException exceptionDeleteLSwitchPort) { - logger.error("Error while deleting Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") from Logical Switch " + logicalSwitchUuid + " due to: " + exceptionDeleteLSwitchPort.getMessage()); - } - logger.warn("Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") successfully deleted"); - } - - private void cleanupLRouterPort(String logicalRouterUuid, LogicalRouterPort lRouterPort, NiciraNvpApi niciraNvpApi) { - logger.warn("Deleting previously created Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") from Logical Router " + logicalRouterUuid + " and retrying"); - try { - niciraNvpApi.deleteLogicalRouterPort(logicalRouterUuid, lRouterPort.getUuid()); - } catch (NiciraNvpApiException exceptionDelete) { - logger.error("Error while deleting Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") from Logical Router " + logicalRouterUuid + " due to: " + exceptionDelete.getMessage()); - } - logger.warn("Logical Router Port " + lRouterPort.getUuid() + " (" + lRouterPort.getDisplayName() + ") successfully deleted"); - } - - private Answer handleException(NiciraNvpApiException e, ConfigureSharedNetworkUuidCommand command, NiciraNvpResource niciraNvpResource) { - if (HttpStatusCodeHelper.isConflict(e.getErrorCode())){ - logger.warn("There's been a conflict in NSX side, aborting implementation"); - return new ConfigureSharedNetworkUuidAnswer(command, false, "FAILED: There's been a conflict in NSX side"); - } - else { - logger.warn("Error code: " + e.getErrorCode() + ", retrying"); - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, ConfigureSharedNetworkUuidAnswer.class, e); - } - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkVlanIdCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkVlanIdCommandWrapper.java deleted file mode 100644 index ebc84f23754c..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureSharedNetworkVlanIdCommandWrapper.java +++ /dev/null @@ -1,116 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NAME_MAX_LEN; -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.ArrayList; -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ConfigureSharedNetworkVlanIdAnswer; -import com.cloud.agent.api.ConfigureSharedNetworkVlanIdCommand; -import com.cloud.network.nicira.L2GatewayAttachment; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpTag; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; -import com.cloud.utils.rest.HttpStatusCodeHelper; - -@ResourceWrapper(handles = ConfigureSharedNetworkVlanIdCommand.class) -public class NiciraNvpConfigureSharedNetworkVlanIdCommandWrapper extends CommandWrapper{ - - - @Override - public Answer execute(ConfigureSharedNetworkVlanIdCommand command, NiciraNvpResource niciraNvpResource) { - final String logicalSwitchUuid = command.getLogicalSwitchUuid(); - final String l2GatewayServiceUuid = command.getL2GatewayServiceUuid(); - long vlanId = command.getVlanId(); - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", command.getOwnerName())); - final long networkId = command.getNetworkId(); - - logger.debug("Connecting Logical Switch " + logicalSwitchUuid + " to L2 Gateway Service " + l2GatewayServiceUuid + ", vlan id " + vlanId + " network " + networkId); - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - logger.debug("Creating Logical Switch Port in Logical Switch " + logicalSwitchUuid); - LogicalSwitchPort lSwitchPort = null; - try { - lSwitchPort = new LogicalSwitchPort(); - lSwitchPort.setAdminStatusEnabled(true); - lSwitchPort.setDisplayName(niciraNvpResource.truncate(networkId + "-l2Gateway-port", NAME_MAX_LEN)); - lSwitchPort.setTags(tags); - lSwitchPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lSwitchPort); - } - catch (NiciraNvpApiException e){ - logger.warn("Could not create Logical Switch Port on Logical Switch " + logicalSwitchUuid + " due to: " + e.getMessage() + ", retrying"); - return handleException(e, command, niciraNvpResource); - } - logger.debug("Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") successfully created in Logical Switch " + logicalSwitchUuid); - - logger.debug("Attaching Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") on VLAN " + command.getVlanId() + " using L2GatewayAttachment"); - try { - final L2GatewayAttachment attachment = new L2GatewayAttachment(l2GatewayServiceUuid); - if (command.getVlanId() != 0) { - attachment.setVlanId(command.getVlanId()); - } - niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lSwitchPort.getUuid(), attachment); - } - catch (NiciraNvpApiException e){ - logger.warn("Could not attach Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") to Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") due to: " + e.getMessage() + ", errorCode: " + e.getErrorCode()); - cleanup(logicalSwitchUuid, lSwitchPort, niciraNvpApi); - return handleException(e, command, niciraNvpResource); - } - logger.debug("Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") successfully attached on VLAN " + command.getVlanId() + " using L2GatewayAttachment"); - - logger.debug("Successfully connected Logical Switch " + logicalSwitchUuid + " to L2 Gateway Service " + l2GatewayServiceUuid + ", vlan id " + vlanId + ", network " + networkId + ", through Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ")"); - return new ConfigureSharedNetworkVlanIdAnswer(command, true, "OK"); - } - - private void cleanup(String logicalSwitchUuid, LogicalSwitchPort lSwitchPort, NiciraNvpApi niciraNvpApi) { - logger.warn("Deleting previously created Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") from Logical Switch " + logicalSwitchUuid); - try { - niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lSwitchPort.getUuid()); - } catch (NiciraNvpApiException exceptionDeleteLSwitchPort) { - logger.error("Error while deleting Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") from Logical Switch " + logicalSwitchUuid + " due to: " + exceptionDeleteLSwitchPort.getMessage()); - } - logger.warn("Logical Switch Port " + lSwitchPort.getUuid() + " (" + lSwitchPort.getDisplayName() + ") successfully deteled"); - } - - private Answer handleException(NiciraNvpApiException e, ConfigureSharedNetworkVlanIdCommand command, NiciraNvpResource niciraNvpResource) { - if (HttpStatusCodeHelper.isConflict(e.getErrorCode())){ - logger.warn("There's been a conflict in NSX side, aborting implementation"); - return new ConfigureSharedNetworkVlanIdAnswer(command, false, "FAILED: There's been a conflict in NSX side"); - } - else { - logger.warn("Error code: " + e.getErrorCode() + ", retrying"); - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, ConfigureSharedNetworkVlanIdAnswer.class, e); - } - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java deleted file mode 100644 index bc6c03f87aac..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java +++ /dev/null @@ -1,112 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.network.nicira.NatRule; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = ConfigureStaticNatRulesOnLogicalRouterCommand.class) -public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(final ConfigureStaticNatRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - final List existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid()); - // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) - // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule - // Any other SourceNat rule should have a corresponding DestinationNat rule - - for (final StaticNatRuleTO rule : command.getRules()) { - - final NatRule[] rulepair = niciraNvpResource.generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp()); - - NatRule incoming = null; - NatRule outgoing = null; - - for (final NatRule storedRule : existingRules) { - if (storedRule.equalsIgnoreUuid(rulepair[1])) { - // The outgoing rule exists - outgoing = storedRule; - logger.debug("Found matching outgoing rule " + outgoing.getUuid()); - if (incoming != null) { - break; - } - } else if (storedRule.equalsIgnoreUuid(rulepair[0])) { - // The incoming rule exists - incoming = storedRule; - logger.debug("Found matching incoming rule " + incoming.getUuid()); - if (outgoing != null) { - break; - } - } - } - if (incoming != null && outgoing != null) { - if (rule.revoked()) { - logger.debug("Deleting incoming rule " + incoming.getUuid()); - niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid()); - - logger.debug("Deleting outgoing rule " + outgoing.getUuid()); - niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid()); - } - } else { - if (rule.revoked()) { - logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp()); - break; - } - - rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]); - logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0])); - - try { - rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]); - logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1])); - } catch (final NiciraNvpApiException ex) { - logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule"); - niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid()); - throw ex; // Rethrow original exception - } - - } - } - return new ConfigureStaticNatRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " StaticNat rules applied"); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, ConfigureStaticNatRulesOnLogicalRouterAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java deleted file mode 100644 index 267a59da09eb..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java +++ /dev/null @@ -1,150 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NAME_MAX_LEN; -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.ArrayList; -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateLogicalRouterAnswer; -import com.cloud.agent.api.CreateLogicalRouterCommand; -import com.cloud.network.nicira.L3GatewayAttachment; -import com.cloud.network.nicira.LogicalRouter; -import com.cloud.network.nicira.LogicalRouterPort; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.Match; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpTag; -import com.cloud.network.nicira.PatchAttachment; -import com.cloud.network.nicira.RouterNextHop; -import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig; -import com.cloud.network.nicira.SourceNatRule; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = CreateLogicalRouterCommand.class) -public final class NiciraNvpCreateLogicalRouterCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(final CreateLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) { - final String routerName = command.getName(); - final String gatewayServiceUuid = command.getGatewayServiceUuid(); - final String logicalSwitchUuid = command.getLogicalSwitchUuid(); - - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", command.getOwnerName())); - - final String publicNetworkNextHopIp = command.getPublicNextHop(); - final String publicNetworkIpAddress = command.getPublicIpCidr(); - final String internalNetworkAddress = command.getInternalIpCidr(); - - logger.debug("Creating a logical router with external ip " + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + "on gateway service " + - gatewayServiceUuid); - - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - // Create the Router - LogicalRouter lrc = new LogicalRouter(); - lrc.setDisplayName(niciraNvpResource.truncate(routerName, NAME_MAX_LEN)); - lrc.setTags(tags); - lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp))); - lrc = niciraNvpApi.createLogicalRouter(lrc); - - // store the switchport for rollback - LogicalSwitchPort lsp = null; - - try { - // Create the outside port for the router - LogicalRouterPort lrpo = new LogicalRouterPort(); - lrpo.setAdminStatusEnabled(true); - lrpo.setDisplayName(niciraNvpResource.truncate(routerName + "-outside-port", NAME_MAX_LEN)); - lrpo.setTags(tags); - final List outsideIpAddresses = new ArrayList(); - outsideIpAddresses.add(publicNetworkIpAddress); - lrpo.setIpAddresses(outsideIpAddresses); - lrpo = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpo); - - // Attach the outside port to the gateway service on the correct VLAN - final L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid); - if (command.getVlanId() != 0) { - attachment.setVlanId(command.getVlanId()); - } - niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); - - // Create the inside port for the router - LogicalRouterPort lrpi = new LogicalRouterPort(); - lrpi.setAdminStatusEnabled(true); - lrpi.setDisplayName(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN)); - lrpi.setTags(tags); - final List insideIpAddresses = new ArrayList(); - insideIpAddresses.add(internalNetworkAddress); - lrpi.setIpAddresses(insideIpAddresses); - lrpi = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpi); - - // Create the inside port on the lswitch - lsp = new LogicalSwitchPort(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN), tags, true); - lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp); - - // Attach the inside router port to the lswitch port with a PatchAttachment - niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid())); - - // Attach the inside lswitch port to the router with a PatchAttachment - niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid())); - - // Setup the source nat rule - final SourceNatRule snr = new SourceNatRule(); - snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]); - snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]); - final Match match = new Match(); - match.setSourceIpAddresses(internalNetworkAddress); - snr.setMatch(match); - snr.setOrder(200); - niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr); - } catch (final NiciraNvpApiException e) { - // We need to destroy the router if we already created it - // this will also take care of any router ports and rules - try { - niciraNvpApi.deleteLogicalRouter(lrc.getUuid()); - if (lsp != null) { - niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid()); - } - } catch (final NiciraNvpApiException ex) { - } - - throw e; - } - - return new CreateLogicalRouterAnswer(command, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid()); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, CreateLogicalRouterAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java deleted file mode 100644 index bec6b0e094ea..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java +++ /dev/null @@ -1,73 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateLogicalSwitchAnswer; -import com.cloud.agent.api.CreateLogicalSwitchCommand; -import com.cloud.network.nicira.LogicalSwitch; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpTag; -import com.cloud.network.nicira.TransportZoneBinding; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.resource.NiciraNvpUtilities; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = CreateLogicalSwitchCommand.class) -public final class NiciraNvpCreateLogicalSwitchCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final CreateLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities(); - - LogicalSwitch logicalSwitch = niciraNvpUtilities.createLogicalSwitch(); - logicalSwitch.setDisplayName(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN)); - logicalSwitch.setPortIsolationEnabled(false); - - // Set transport binding - final List ltzb = new ArrayList(); - ltzb.add(new TransportZoneBinding(command.getTransportUuid(), command.getTransportType())); - logicalSwitch.setTransportZones(ltzb); - - // Tags set to scope cs_account and account name - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", command.getOwnerName())); - logicalSwitch.setTags(tags); - - try { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - logicalSwitch = niciraNvpApi.createLogicalSwitch(logicalSwitch); - final String switchUuid = logicalSwitch.getUuid(); - return new CreateLogicalSwitchAnswer(command, true, "Logicalswitch " + switchUuid + " created", switchUuid); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, CreateLogicalSwitchAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java deleted file mode 100644 index a0d30542fd6d..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java +++ /dev/null @@ -1,68 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateLogicalSwitchPortAnswer; -import com.cloud.agent.api.CreateLogicalSwitchPortCommand; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.VifAttachment; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.resource.NiciraNvpUtilities; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = CreateLogicalSwitchPortCommand.class) -public final class NiciraNvpCreateLogicalSwitchPortCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(final CreateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities(); - - final String logicalSwitchUuid = command.getLogicalSwitchUuid(); - final String attachmentUuid = command.getAttachmentUuid(); - - try { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - final LogicalSwitchPort logicalSwitchPort = niciraNvpUtilities.createLogicalSwitchPort(command); - final LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort); - try { - niciraNvpApi.updateLogicalSwitchPortAttachment(command.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid)); - } catch (final NiciraNvpApiException ex) { - logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport"); - niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), newPort.getUuid()); - throw ex; // Rethrow the original exception - } - return new CreateLogicalSwitchPortAnswer(command, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid()); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, CreateLogicalSwitchPortAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java deleted file mode 100644 index 842bf3f08611..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteLogicalRouterAnswer; -import com.cloud.agent.api.DeleteLogicalRouterCommand; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = DeleteLogicalRouterCommand.class) -public final class NiciraNvpDeleteLogicalRouterCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final DeleteLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - niciraNvpApi.deleteLogicalRouter(command.getLogicalRouterUuid()); - return new DeleteLogicalRouterAnswer(command, true, "Logical Router deleted (uuid " + command.getLogicalRouterUuid() + ")"); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, DeleteLogicalRouterAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterPortCommandWrapper.java deleted file mode 100644 index a585641bebfd..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterPortCommandWrapper.java +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteLogicalRouterPortAnswer; -import com.cloud.agent.api.DeleteLogicalRouterPortCommand; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = DeleteLogicalRouterPortCommand.class) -public class NiciraNvpDeleteLogicalRouterPortCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(DeleteLogicalRouterPortCommand command, NiciraNvpResource niciraNvpResource) { - final String logicalRouterUuid = command.getLogicalRouterUuid(); - final String logicalRouterPortUuid = command.getLogicalRouterPortUuid(); - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - logger.debug("Deleting Logical Router Port " + logicalRouterPortUuid + " in Logical Router " + logicalRouterUuid); - try { - niciraNvpApi.deleteLogicalRouterPort(logicalRouterUuid, logicalRouterPortUuid); - return new DeleteLogicalRouterPortAnswer(command, true, "Logical Router Port " + logicalRouterPortUuid + " deleted"); - } - catch (NiciraNvpApiException e){ - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, DeleteLogicalRouterPortAnswer.class, e); - } - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java deleted file mode 100644 index 224d641d30d3..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java +++ /dev/null @@ -1,49 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteLogicalSwitchAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchCommand; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = DeleteLogicalSwitchCommand.class) -public final class NiciraNvpDeleteLogicalSwitchCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final DeleteLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) { - try { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - niciraNvpApi.deleteLogicalSwitch(command.getLogicalSwitchUuid()); - return new DeleteLogicalSwitchAnswer(command, true, "Logicalswitch " + command.getLogicalSwitchUuid() + " deleted"); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, DeleteLogicalSwitchAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java deleted file mode 100644 index 90193e29b265..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchPortCommand; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = DeleteLogicalSwitchPortCommand.class) -public final class NiciraNvpDeleteLogicalSwitchPortCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final DeleteLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid()); - return new DeleteLogicalSwitchPortAnswer(command, true, "Logical switch port " + command.getLogicalSwitchPortUuid() + " deleted"); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, DeleteLogicalSwitchPortAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindL2GatewayServiceCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindL2GatewayServiceCommandWrapper.java deleted file mode 100644 index 03858d197305..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindL2GatewayServiceCommandWrapper.java +++ /dev/null @@ -1,67 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.FindL2GatewayServiceAnswer; -import com.cloud.agent.api.FindL2GatewayServiceCommand; -import com.cloud.network.nicira.GatewayServiceConfig; -import com.cloud.network.nicira.L2GatewayServiceConfig; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = FindL2GatewayServiceCommand.class) -public class NiciraNvpFindL2GatewayServiceCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(FindL2GatewayServiceCommand command, NiciraNvpResource niciraNvpResource) { - final GatewayServiceConfig config = command.getGatewayServiceConfig(); - final String uuid = config.getUuid(); - final String type = config.getType(); - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - logger.info("Looking for L2 Gateway Service " + uuid + " of type " + type); - - try { - List lstGW = niciraNvpApi.findL2GatewayServiceByUuidAndType(uuid, type); - if (lstGW.size() == 0) { - return new FindL2GatewayServiceAnswer(command, false, "L2 Gateway Service not found", null); - } else { - return new FindL2GatewayServiceAnswer(command, true, "L2 Gateway Service " + lstGW.get(0).getDisplayName()+ " found", lstGW.get(0).getUuid()); - } - } catch (NiciraNvpApiException e) { - logger.error("Error finding Gateway Service due to: " + e.getMessage()); - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, FindL2GatewayServiceAnswer.class, e); - } - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalRouterPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalRouterPortCommandWrapper.java deleted file mode 100644 index f0ee21662985..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalRouterPortCommandWrapper.java +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.List; - - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.FindLogicalRouterPortAnswer; -import com.cloud.agent.api.FindLogicalRouterPortCommand; -import com.cloud.network.nicira.LogicalRouterPort; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = FindLogicalRouterPortCommand.class) -public class NiciraNvpFindLogicalRouterPortCommandWrapper extends CommandWrapper { - - - @Override - public Answer execute(FindLogicalRouterPortCommand command, NiciraNvpResource niciraNvpResource) { - final String logicalRouterUuid = command.getLogicalRouterUuid(); - final String attachmentLswitchUuid = command.getAttachmentLswitchUuid(); - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - logger.debug("Finding Logical Router Port in Logical Router " + logicalRouterUuid + " and attachmentLSwitchUuid " + attachmentLswitchUuid); - - try{ - List lRouterPorts = niciraNvpApi.findLogicalRouterPortByAttachmentLSwitchUuid(logicalRouterUuid, attachmentLswitchUuid); - if (lRouterPorts.size() == 0) { - return new FindLogicalRouterPortAnswer(command, false, "Logical Router Port not found", null); - } else { - return new FindLogicalRouterPortAnswer(command, true, "Logical Router Port found", lRouterPorts.get(0).getUuid()); - } - } - catch (NiciraNvpApiException e){ - logger.error("Error finding Logical Router Port due to: " + e.getMessage()); - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, FindLogicalRouterPortAnswer.class, e); - } - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java deleted file mode 100644 index 9975553ba375..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.List; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.FindLogicalSwitchPortAnswer; -import com.cloud.agent.api.FindLogicalSwitchPortCommand; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = FindLogicalSwitchPortCommand.class) -public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final FindLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) { - final String logicalSwitchUuid = command.getLogicalSwitchUuid(); - final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid(); - - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - final List ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid); - if (ports.size() == 0) { - return new FindLogicalSwitchPortAnswer(command, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null); - } else { - return new FindLogicalSwitchPortAnswer(command, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid); - } - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, FindLogicalSwitchPortAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java deleted file mode 100644 index 3db6cb6a9c67..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java +++ /dev/null @@ -1,36 +0,0 @@ -// -// 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.network.resource.wrapper; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.MaintainAnswer; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = MaintainCommand.class) -public final class NiciraNvpMaintainCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final MaintainCommand command, final NiciraNvpResource niciraNvpResource) { - return new MaintainAnswer(command); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java deleted file mode 100644 index 48864a99a7ef..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java +++ /dev/null @@ -1,36 +0,0 @@ -// -// 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.network.resource.wrapper; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ReadyAnswer; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = ReadyCommand.class) -public final class NiciraNvpReadyCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final ReadyCommand command, final NiciraNvpResource niciraNvpResource) { - return new ReadyAnswer(command); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java deleted file mode 100644 index a923f6beff0b..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java +++ /dev/null @@ -1,68 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES; - -import java.util.ArrayList; -import java.util.List; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer; -import com.cloud.agent.api.UpdateLogicalSwitchPortCommand; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.NiciraNvpTag; -import com.cloud.network.nicira.VifAttachment; -import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.resource.NiciraNvpUtilities; -import com.cloud.network.utils.CommandRetryUtility; -import com.cloud.resource.CommandWrapper; -import com.cloud.resource.ResourceWrapper; - -@ResourceWrapper(handles = UpdateLogicalSwitchPortCommand.class) -public final class NiciraNvpUpdateLogicalSwitchPortCommandWrapper extends CommandWrapper { - - @Override - public Answer execute(final UpdateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) { - final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities(); - - final String logicalSwitchUuid = command.getLogicalSwitchUuid(); - final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid(); - final String attachmentUuid = command.getAttachmentUuid(); - - final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi(); - - try { - // Tags set to scope cs_account and account name - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", command.getOwnerName())); - - final VifAttachment vifAttachment = niciraNvpUtilities.createVifAttachment(attachmentUuid); - - niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment); - return new UpdateLogicalSwitchPortAnswer(command, true, "Attachment for " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid); - } catch (final NiciraNvpApiException e) { - final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility(); - retryUtility.addRetry(command, NUM_RETRIES); - return retryUtility.retry(command, UpdateLogicalSwitchPortAnswer.class, e); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java deleted file mode 100644 index 3fd933ccbe13..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/java/com/cloud/network/utils/CommandRetryUtility.java +++ /dev/null @@ -1,90 +0,0 @@ -// -// 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.network.utils; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.resource.ServerResource; - -public class CommandRetryUtility { - - protected Logger logger = LogManager.getLogger(getClass()); - - private static final int ZERO = 0; - private static CommandRetryUtility instance; - - static { - instance = new CommandRetryUtility(); - } - - private final ConcurrentHashMap commandsToRetry; - private ServerResource serverResource; - - private CommandRetryUtility() { - commandsToRetry = new ConcurrentHashMap(); - } - - public static CommandRetryUtility getInstance() { - return instance; - } - - public void setServerResource(final ServerResource serverResource) { - this.serverResource = serverResource; - } - - public boolean addRetry(final Command command, final int retries) { - if (commandsToRetry.containsKey(command)) { - // A retry already exists for this command, do not add it again. - // Once all retries are executed, the command will be removed from the map. - return false; - } - commandsToRetry.put(command, retries); - return true; - } - - public Answer retry(final Command command, final Class answerClass, final Exception error) { - if (commandsToRetry.containsKey(command)) { - Integer numRetries = commandsToRetry.get(command); - - if (numRetries > ZERO) { - commandsToRetry.put(command, --numRetries); - - logger.warn("Retrying " + command.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries); - - return serverResource.executeRequest(command); - } else { - commandsToRetry.remove(command); - } - } - try { - final Constructor answerConstructor = answerClass.getConstructor(Command.class, Exception.class); - return answerConstructor.newInstance(command, error); - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - return Answer.createUnsupportedCommandAnswer(command); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties deleted file mode 100644 index 11bc471e92cc..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/module.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# 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. -# - -name=nvp -parent=network diff --git a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml b/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml deleted file mode 100644 index 2960c975bbef..000000000000 --- a/plugins/network-elements/nicira-nvp/src/main/resources/META-INF/cloudstack/nvp/spring-nvp-context.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java deleted file mode 100644 index 4c3288d73448..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/element/NiciraNvpElementTest.java +++ /dev/null @@ -1,421 +0,0 @@ -// -// 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.network.element; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.naming.ConfigurationException; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatcher; -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; -import com.cloud.agent.api.ConfigureSharedNetworkUuidAnswer; -import com.cloud.agent.api.ConfigureSharedNetworkVlanIdAnswer; -import com.cloud.agent.api.CreateLogicalRouterAnswer; -import com.cloud.dc.VlanVO; -import com.cloud.dc.dao.VlanDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.domain.Domain; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.IpAddress; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.IpAddressManager; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.network.NiciraNvpRouterMappingVO; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.NiciraNvpDao; -import com.cloud.network.dao.NiciraNvpRouterMappingDao; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.user.Account; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.Ip; -import com.cloud.vm.ReservationContext; - -public class NiciraNvpElementTest { - - private static final long NETWORK_ID = 42L; - private static final long NICIRA_NVP_HOST_ID = 9L; - private static final String NETWORK_CIDR = "10.0.0.0/24"; - private static final String NETWORK_GATEWAY = "10.0.0.1"; - NiciraNvpElement element = new NiciraNvpElement(); - NetworkOrchestrationService networkManager = mock(NetworkOrchestrationService.class); - NetworkModel networkModel = mock(NetworkModel.class); - NetworkServiceMapDao ntwkSrvcDao = mock(NetworkServiceMapDao.class); - AgentManager agentManager = mock(AgentManager.class); - HostDao hostDao = mock(HostDao.class); - NiciraNvpDao niciraNvpDao = mock(NiciraNvpDao.class); - NiciraNvpRouterMappingDao niciraNvpRouterMappingDao = mock(NiciraNvpRouterMappingDao.class); - VlanDao vlanDao = mock(VlanDao.class); - IpAddressManager ipAddressManager = mock(IpAddressManager.class); - - @Before - public void setUp() throws ConfigurationException { - element.resourceMgr = mock(ResourceManager.class); - element.networkManager = networkManager; - element.ntwkSrvcDao = ntwkSrvcDao; - element.networkModel = networkModel; - element.agentMgr = agentManager; - element.hostDao = hostDao; - element.niciraNvpDao = niciraNvpDao; - element.niciraNvpRouterMappingDao = niciraNvpRouterMappingDao; - element.vlanDao = vlanDao; - element.ipAddrMgr = ipAddressManager; - - // Standard responses - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); - - element.configure("NiciraNvpTestElement", Collections. emptyMap()); - } - - @Test - public void canHandleTest() { - final Network net = mock(Network.class); - when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(net.getId()).thenReturn(NETWORK_ID); - - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); - // Golden path - assertTrue(element.canHandle(net, Service.Connectivity)); - - when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); - // Only broadcastdomaintype lswitch is supported - assertFalse(element.canHandle(net, Service.Connectivity)); - - when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(false); - // No nvp provider in the network - assertFalse(element.canHandle(net, Service.Connectivity)); - - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(false); - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); - // NVP provider does not provide Connectivity for this network - assertFalse(element.canHandle(net, Service.Connectivity)); - - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); - // Only service Connectivity is supported - assertFalse(element.canHandle(net, Service.Dhcp)); - - } - - @Test - public void implementIsolatedNetworkTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, URISyntaxException { - final Network network = mock(Network.class); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getGuestType()).thenReturn(GuestType.Isolated); - - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - when(device.getHostId()).thenReturn(NICIRA_NVP_HOST_ID); - - HostVO niciraNvpHost = mock(HostVO.class); - when(niciraNvpHost.getId()).thenReturn(NICIRA_NVP_HOST_ID); - when(hostDao.findById(NICIRA_NVP_HOST_ID)).thenReturn(niciraNvpHost); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final DeployDestination dest = mock(DeployDestination.class); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext context = mock(ReservationContext.class); - when(context.getDomain()).thenReturn(dom); - when(context.getAccount()).thenReturn(acc); - - //ISOLATED NETWORK - when(networkModel.isProviderSupportServiceInNetwork(NETWORK_ID, Service.SourceNat, Provider.NiciraNvp)).thenReturn(true); - - PublicIp sourceNatIp = mock(PublicIp.class); - Ip ip = mock(Ip.class); - when(ip.addr()).thenReturn("10.0.0.0"); - when(sourceNatIp.getAddress()).thenReturn(ip); - when(sourceNatIp.getVlanNetmask()).thenReturn("255.255.255.0"); - when(sourceNatIp.getVlanTag()).thenReturn("111"); - - when(ipAddressManager.assignSourceNatIpAddressToGuestNetwork(acc, network)).thenReturn(sourceNatIp); - when(network.getGateway()).thenReturn(NETWORK_GATEWAY); - when(network.getCidr()).thenReturn(NETWORK_CIDR); - - final CreateLogicalRouterAnswer answer = mock(CreateLogicalRouterAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentManager.easySend(eq(NICIRA_NVP_HOST_ID), (Command)any())).thenReturn(answer); - - assertTrue(element.implement(network, offering, dest, context)); - } - - @Test - public void applyIpTest() throws ResourceUnavailableException { - final Network network = mock(Network.class); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final List ipAddresses = new ArrayList(); - final PublicIpAddress pipReleased = mock(PublicIpAddress.class); - final PublicIpAddress pipAllocated = mock(PublicIpAddress.class); - final Ip ipReleased = new Ip("42.10.10.10"); - final Ip ipAllocated = new Ip("10.10.10.10"); - when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated); - when(pipAllocated.getAddress()).thenReturn(ipAllocated); - when(pipAllocated.getNetmask()).thenReturn("255.255.255.0"); - when(pipReleased.getState()).thenReturn(IpAddress.State.Releasing); - when(pipReleased.getAddress()).thenReturn(ipReleased); - when(pipReleased.getNetmask()).thenReturn("255.255.255.0"); - ipAddresses.add(pipAllocated); - ipAddresses.add(pipReleased); - - final Set services = new HashSet(); - services.add(Service.SourceNat); - services.add(Service.StaticNat); - services.add(Service.PortForwarding); - - final List deviceList = new ArrayList(); - final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class); - final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class); - when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO); - when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde"); - when(nndVO.getHostId()).thenReturn(NETWORK_ID); - final HostVO hvo = mock(HostVO.class); - when(hvo.getId()).thenReturn(NETWORK_ID); - when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde"); - when(hostDao.findById(NETWORK_ID)).thenReturn(hvo); - deviceList.add(nndVO); - when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList); - - final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer); - - assertTrue(element.applyIps(network, ipAddresses, services)); - - verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final ConfigurePublicIpsOnLogicalRouterCommand command) { - return command.getPublicCidrs().size() == 1; - } - })); - } - - @Test - public void implementSharedNetworkUuidVlanIdTest() throws URISyntaxException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // SHARED NETWORKS CASE 1: loggerICAL ROUTER'S UUID AS VLAN ID - final Network network = mock(Network.class); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getGuestType()).thenReturn(GuestType.Shared); - - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - when(device.getHostId()).thenReturn(NICIRA_NVP_HOST_ID); - - HostVO niciraNvpHost = mock(HostVO.class); - when(niciraNvpHost.getId()).thenReturn(NICIRA_NVP_HOST_ID); - when(hostDao.findById(NICIRA_NVP_HOST_ID)).thenReturn(niciraNvpHost); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Shared); - - final DeployDestination dest = mock(DeployDestination.class); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext context = mock(ReservationContext.class); - when(context.getDomain()).thenReturn(dom); - when(context.getAccount()).thenReturn(acc); - - //SHARED NETWORKS CASE 1 - when(niciraNvpRouterMappingDao.existsMappingForNetworkId(NETWORK_ID)).thenReturn(true); - when(network.getCidr()).thenReturn(NETWORK_CIDR); - when(network.getGateway()).thenReturn(NETWORK_GATEWAY); - - NiciraNvpRouterMappingVO mapping = mock(NiciraNvpRouterMappingVO.class); - when(mapping.getLogicalRouterUuid()).thenReturn("xxxx-xxxx-xxxx"); - when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(mapping); - - final ConfigureSharedNetworkUuidAnswer answer = mock(ConfigureSharedNetworkUuidAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentManager.easySend(eq(NICIRA_NVP_HOST_ID), (Command)any())).thenReturn(answer); - - assertTrue(element.implement(network, offering, dest, context)); - } - - @Test - public void implementSharedNetworkNumericalVlanIdTest() throws URISyntaxException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - // SHARED NETWORKS CASE 2: NUMERICAL VLAN ID - final Network network = mock(Network.class); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getGuestType()).thenReturn(GuestType.Shared); - - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - when(device.getHostId()).thenReturn(NICIRA_NVP_HOST_ID); - - HostVO niciraNvpHost = mock(HostVO.class); - when(niciraNvpHost.getId()).thenReturn(NICIRA_NVP_HOST_ID); - when(hostDao.findById(NICIRA_NVP_HOST_ID)).thenReturn(niciraNvpHost); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Shared); - - final DeployDestination dest = mock(DeployDestination.class); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext context = mock(ReservationContext.class); - when(context.getDomain()).thenReturn(dom); - when(context.getAccount()).thenReturn(acc); - - //SHARED NETWORKS CASE 2 - when(niciraNvpRouterMappingDao.existsMappingForNetworkId(NETWORK_ID)).thenReturn(false); - - VlanVO vlanVO = mock(VlanVO.class); - when(vlanVO.getVlanTag()).thenReturn("111"); - when(vlanDao.listVlansByNetworkId(NETWORK_ID)).thenReturn(Arrays.asList(new VlanVO[] {vlanVO})); - - when(niciraNvpHost.getDetail("l2gatewayserviceuuid")).thenReturn("bbbb-bbbb-bbbb"); - - final ConfigureSharedNetworkVlanIdAnswer answer = mock(ConfigureSharedNetworkVlanIdAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentManager.easySend(eq(NICIRA_NVP_HOST_ID), (Command)any())).thenReturn(answer); - - assertTrue(element.implement(network, offering, dest, context)); - } - - @Test(expected=CloudRuntimeException.class) - public void implementSharedNetworkNumericalVlanIdWithoutL2GatewayService() throws URISyntaxException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ - final Network network = mock(Network.class); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); - when(network.getId()).thenReturn(NETWORK_ID); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(network.getGuestType()).thenReturn(GuestType.Shared); - - when(networkModel.isProviderForNetwork(Provider.NiciraNvp, NETWORK_ID)).thenReturn(true); - when(ntwkSrvcDao.canProviderSupportServiceInNetwork(NETWORK_ID, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - when(device.getHostId()).thenReturn(NICIRA_NVP_HOST_ID); - - HostVO niciraNvpHost = mock(HostVO.class); - when(niciraNvpHost.getId()).thenReturn(NICIRA_NVP_HOST_ID); - when(hostDao.findById(NICIRA_NVP_HOST_ID)).thenReturn(niciraNvpHost); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Shared); - - final DeployDestination dest = mock(DeployDestination.class); - - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext context = mock(ReservationContext.class); - when(context.getDomain()).thenReturn(dom); - when(context.getAccount()).thenReturn(acc); - - //SHARED NETWORKS CASE 2 - when(niciraNvpRouterMappingDao.existsMappingForNetworkId(NETWORK_ID)).thenReturn(false); - - VlanVO vlanVO = mock(VlanVO.class); - when(vlanVO.getVlanTag()).thenReturn("111"); - when(vlanDao.listVlansByNetworkId(NETWORK_ID)).thenReturn(Arrays.asList(new VlanVO[] {vlanVO})); - - when(niciraNvpHost.getDetail("l2gatewayserviceuuid")).thenReturn(null); - - element.implement(network, offering, dest, context); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java deleted file mode 100644 index c6ad8a6d9070..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java +++ /dev/null @@ -1,478 +0,0 @@ -// -// 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.network.guru; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Collections; - -import org.junit.Before; -import org.junit.Test; - -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.CreateLogicalSwitchAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchAnswer; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.deploy.DeploymentPlan; -import com.cloud.domain.Domain; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.Network; -import com.cloud.network.Network.GuestType; -import com.cloud.network.Network.Service; -import com.cloud.network.Network.State; -import com.cloud.network.NetworkModel; -import com.cloud.network.NetworkProfile; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.NiciraNvpDeviceVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.NiciraNvpDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; -import com.cloud.user.Account; -import com.cloud.vm.ReservationContext; - -public class NiciraNvpGuestNetworkGuruTest { - private static final long NETWORK_ID = 42L; - PhysicalNetworkDao physnetdao = mock(PhysicalNetworkDao.class); - NiciraNvpDao nvpdao = mock(NiciraNvpDao.class); - DataCenterDao dcdao = mock(DataCenterDao.class); - NetworkOfferingServiceMapDao nosd = mock(NetworkOfferingServiceMapDao.class); - AgentManager agentmgr = mock(AgentManager.class); - NetworkOrchestrationService netmgr = mock(NetworkOrchestrationService.class); - NetworkModel netmodel = mock(NetworkModel.class); - - HostDao hostdao = mock(HostDao.class); - NetworkDao netdao = mock(NetworkDao.class); - NiciraNvpGuestNetworkGuru guru; - - @Before - public void setUp() { - guru = new NiciraNvpGuestNetworkGuru(); - ((GuestNetworkGuru)guru)._physicalNetworkDao = physnetdao; - guru.physicalNetworkDao = physnetdao; - guru.niciraNvpDao = nvpdao; - guru._dcDao = dcdao; - guru.ntwkOfferingSrvcDao = nosd; - ((GuestNetworkGuru)guru)._networkModel = netmodel; - guru.hostDao = hostdao; - guru.agentMgr = agentmgr; - guru.networkDao = netdao; - - final DataCenterVO dc = mock(DataCenterVO.class); - when(dc.getNetworkType()).thenReturn(NetworkType.Advanced); - when(dc.getGuestNetworkCidr()).thenReturn("10.1.1.1/24"); - - when(dcdao.findById((Long)any())).thenReturn(dc); - } - - @Test - public void testCanHandle() { - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); - - assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Supported: IsolationMethod == VXLAN - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VXLAN"})); - assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Not supported TrafficType != Guest - when(offering.getTrafficType()).thenReturn(TrafficType.Management); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - // Supported: GuestType Shared - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Shared); - assertTrue(guru.canHandle(offering, NetworkType.Advanced, physnet)); - - // Not supported: Basic networking - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - assertFalse(guru.canHandle(offering, NetworkType.Basic, physnet) == true); - - // Not supported: IsolationMethod != STT, VXLAN - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); - assertFalse(guru.canHandle(offering, NetworkType.Advanced, physnet) == true); - - } - - @Test - public void testDesign() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(true); - - when(netmodel.listNetworkOfferingServices(NETWORK_ID)).thenReturn(Arrays.asList(Service.Connectivity)); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork != null); - assertTrue(designednetwork.getBroadcastDomainType() == BroadcastDomainType.Lswitch); - } - - @Test - public void testDesignNoElementOnPhysicalNetwork() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections. emptyList()); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork == null); - } - - @Test - public void testDesignNoIsolationMethodSTT() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"VLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Collections. emptyList()); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork == null); - } - - @Test - public void testDesignNoConnectivityInOffering() { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - final DeploymentPlan plan = mock(DeploymentPlan.class); - final Network network = mock(Network.class); - final Account account = mock(Account.class); - - final Network designednetwork = guru.design(offering, plan, network, "", 1L, account); - assertTrue(designednetwork == null); - } - - @Test - public void testImplement() throws InsufficientVirtualNetworkCapacityException { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - mock(DeploymentPlan.class); - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - final HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - final Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork != null); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testImplementWithCidr() throws InsufficientVirtualNetworkCapacityException { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - mock(DeploymentPlan.class); - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getGateway()).thenReturn("10.1.1.1"); - when(network.getCidr()).thenReturn("10.1.1.0/24"); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - final HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - final Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork != null); - assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24")); - assertTrue(implementednetwork.getGateway().equals("10.1.1.1")); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testImplementURIException() throws InsufficientVirtualNetworkCapacityException { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - mock(DeploymentPlan.class); - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - final HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - //when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - final Network implementednetwork = guru.implement(network, offering, dest, res); - assertTrue(implementednetwork == null); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - } - - @Test - public void testShutdown() throws InsufficientVirtualNetworkCapacityException, URISyntaxException { - final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class); - when(physnetdao.findById((Long)any())).thenReturn(physnet); - when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] {"STT", "VXLAN"})); - when(physnet.getId()).thenReturn(NETWORK_ID); - - final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class); - when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] {device})); - when(device.getId()).thenReturn(1L); - - final NetworkOffering offering = mock(NetworkOffering.class); - when(offering.getId()).thenReturn(NETWORK_ID); - when(offering.getTrafficType()).thenReturn(TrafficType.Guest); - when(offering.getGuestType()).thenReturn(GuestType.Isolated); - - when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false); - - mock(DeploymentPlan.class); - - final NetworkVO network = mock(NetworkVO.class); - when(network.getName()).thenReturn("testnetwork"); - when(network.getState()).thenReturn(State.Implementing); - when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); - when(network.getBroadcastUri()).thenReturn(new URI("lswitch:aaaaa")); - when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID); - when(netdao.findById(NETWORK_ID)).thenReturn(network); - - final DeployDestination dest = mock(DeployDestination.class); - - final DataCenter dc = mock(DataCenter.class); - when(dest.getDataCenter()).thenReturn(dc); - - final HostVO niciraHost = mock(HostVO.class); - when(hostdao.findById(anyLong())).thenReturn(niciraHost); - when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa"); - when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt"); - when(niciraHost.getId()).thenReturn(NETWORK_ID); - - when(netmodel.findPhysicalNetworkId(anyLong(), (String)any(), (TrafficType)any())).thenReturn(NETWORK_ID); - final Domain dom = mock(Domain.class); - when(dom.getName()).thenReturn("domain"); - final Account acc = mock(Account.class); - when(acc.getAccountName()).thenReturn("accountname"); - final ReservationContext res = mock(ReservationContext.class); - when(res.getDomain()).thenReturn(dom); - when(res.getAccount()).thenReturn(acc); - - final DeleteLogicalSwitchAnswer answer = mock(DeleteLogicalSwitchAnswer.class); - when(answer.getResult()).thenReturn(true); - when(agentmgr.easySend(eq(NETWORK_ID), (Command)any())).thenReturn(answer); - - final NetworkProfile implementednetwork = mock(NetworkProfile.class); - when(implementednetwork.getId()).thenReturn(NETWORK_ID); - when(implementednetwork.getBroadcastUri()).thenReturn(new URI("lswitch:aaaa")); - when(offering.isSpecifyVlan()).thenReturn(false); - - guru.shutdown(implementednetwork, offering); - verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command)any()); - verify(implementednetwork, times(1)).setBroadcastUri(null); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java deleted file mode 100644 index b14694dc0987..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/ExecutionCounterTest.java +++ /dev/null @@ -1,102 +0,0 @@ -// -// 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.network.nicira; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.junit.Test; - -public class ExecutionCounterTest { - - @Test - public void testIncrementCounter() throws Exception { - final ExecutionCounter executionCounter = new ExecutionCounter(-1); - - executionCounter.incrementExecutionCounter().incrementExecutionCounter(); - - assertThat(executionCounter.getValue(), equalTo(2)); - } - - @Test - public void testHasNotYetReachedTheExecutuionLimit() throws Exception { - final ExecutionCounter executionCounter = new ExecutionCounter(2); - - executionCounter.incrementExecutionCounter(); - - assertThat(executionCounter.hasReachedExecutionLimit(), equalTo(false)); - } - - @Test - public void testHasAlreadyReachedTheExecutuionLimit() throws Exception { - final ExecutionCounter executionCounter = new ExecutionCounter(2); - - executionCounter.incrementExecutionCounter().incrementExecutionCounter(); - - assertThat(executionCounter.hasReachedExecutionLimit(), equalTo(true)); - } - - @Test - public void testConcurrentUpdatesToCounter() throws Exception { - final ExecutionCounter executionCounter = new ExecutionCounter(0); - final ExecutorService executorService = Executors.newFixedThreadPool(3); - final AtomicInteger counterTask1 = new AtomicInteger(-1); - final AtomicInteger counterTask2 = new AtomicInteger(-1); - final AtomicInteger counterTask3 = new AtomicInteger(-1); - - final Runnable task1 = new Runnable() { - @Override - public void run() { - executionCounter.incrementExecutionCounter().incrementExecutionCounter(); - executionCounter.incrementExecutionCounter().incrementExecutionCounter(); - counterTask1.set(executionCounter.getValue()); - } - }; - final Runnable task2 = new Runnable() { - @Override - public void run() { - executionCounter.incrementExecutionCounter().incrementExecutionCounter(); - counterTask2.set(executionCounter.getValue()); - } - }; - final Runnable task3 = new Runnable() { - @Override - public void run() { - counterTask3.set(executionCounter.getValue()); - } - }; - - executorService.execute(task1); - executorService.execute(task2); - executorService.execute(task3); - - executorService.shutdown(); - executorService.awaitTermination(5L, TimeUnit.SECONDS); - - assertThat(counterTask1.get(), equalTo(4)); - assertThat(counterTask2.get(), equalTo(2)); - assertThat(counterTask3.get(), equalTo(0)); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java deleted file mode 100644 index 199a6feedd7e..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleAdapterTest.java +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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.network.nicira; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; - -import org.junit.Test; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; - -public class NatRuleAdapterTest { - private final Gson gson = new GsonBuilder() - .registerTypeAdapter(NatRule.class, new NatRuleAdapter()) - .create(); - - @Test(expected = JsonParseException.class) - public void testNatRuleAdapterNoType() { - gson.fromJson("{}", NatRule.class); - } - - @Test(expected = JsonParseException.class) - public void testNatRuleAdapterWrongType() { - gson.fromJson("{type : \"WrongType\"}", NatRule.class); - } - - @Test() - public void testNatRuleAdapterWithSourceNatRule() { - final SourceNatRule sourceNatRule = (SourceNatRule) gson.fromJson("{type : \"SourceNatRule\"}", NatRule.class); - - assertThat(sourceNatRule, instanceOf(SourceNatRule.class)); - } - - @Test() - public void testNatRuleAdapterWithDestinationNatRule() { - final DestinationNatRule destinationNatRule = (DestinationNatRule) gson.fromJson("{type : \"DestinationNatRule\"}", NatRule.class); - - assertThat(destinationNatRule, instanceOf(DestinationNatRule.class)); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java deleted file mode 100644 index e4072bd82a9b..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NatRuleTest.java +++ /dev/null @@ -1,55 +0,0 @@ -// -// 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.network.nicira; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.google.gson.FieldNamingPolicy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class NatRuleTest { - - @Test - public void testNatRuleEncoding() { - final Gson gson = - new GsonBuilder().registerTypeAdapter(NatRule.class, new NatRuleAdapter()) - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) - .create(); - - final DestinationNatRule rn1 = new DestinationNatRule(); - rn1.setToDestinationIpAddress("10.10.10.10"); - rn1.setToDestinationPort(80); - final Match mr1 = new Match(); - mr1.setSourceIpAddresses("11.11.11.11/24"); - mr1.setEthertype("IPv4"); - mr1.setProtocol(6); - rn1.setMatch(mr1); - - final String jsonString = gson.toJson(rn1); - final NatRule dnr = gson.fromJson(jsonString, NatRule.class); - - assertTrue(dnr instanceof DestinationNatRule); - assertTrue(rn1.equals(dnr)); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java deleted file mode 100644 index 318b95a7f623..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiIT.java +++ /dev/null @@ -1,337 +0,0 @@ -// -// 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.network.nicira; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; - -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.rest.HttpClientHelper; - -public class NiciraNvpApiIT { - - protected NiciraNvpApi api; - - protected long timestamp = System.currentTimeMillis(); - - @Before - public void setup() throws Exception { - PropertiesUtil.loadFromFile(PropertiesUtil.findConfigFile("config.properties")); - final String host = System.getProperty("nvp.host"); - final String user = System.getProperty("nvp.admin.user"); - final String pass = System.getProperty("nvp.admin.pwd"); - api = NiciraNvpApi.create() - .host(host) - .username(user) - .password(pass) - .httpClient(HttpClientHelper.createHttpClient(5)) - .build(); - } - - @Test - public void testCRUDSecurityProfile() { - SecurityProfile sProfile = new SecurityProfile(); - sProfile.setDisplayName("SecProfile" + timestamp); - - final List egressRules = new ArrayList(); - sProfile.setLogicalPortEgressRules(egressRules); - egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 80, 88, 6)); - egressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "2a80:34ac::1", null, 90, 98, 6)); - - final List ingressRules = new ArrayList(); - sProfile.setLogicalPortIngressRules(ingressRules); - ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV4, "1.10.10.0", null, 50, 58, 6)); - ingressRules.add(new SecurityRule(SecurityRule.ETHERTYPE_IPV6, "280a:3ac4::1", null, 60, 68, 6)); - - final List tags = new ArrayList(); - sProfile.setTags(tags); - tags.add(new NiciraNvpTag("nvp", "MyTag1")); - tags.add(new NiciraNvpTag("nicira", "MyTag2")); - // In the creation we don't get to specify UUID, href or schema: they don't exist yet - - try { - sProfile = api.createSecurityProfile(sProfile); - - // We can now update the new entity - sProfile.setDisplayName("UpdatedSecProfile" + timestamp); - api.updateSecurityProfile(sProfile, sProfile.getUuid()); - - // Read them all - List profiles = api.findSecurityProfile(); - SecurityProfile scInList = null; - for (final SecurityProfile iProfile : profiles) { - if (iProfile.getUuid().equalsIgnoreCase(sProfile.getUuid())) { - scInList = iProfile; - } - } - assertEquals("Read a Security Profile different from the one just created and updated", sProfile, scInList); - - // Read them filtered by uuid (get one) - profiles = api.findSecurityProfile(sProfile.getUuid()); - assertEquals("Read a Security Profile different from the one just created and updated", sProfile, profiles.get(0)); - assertEquals("Read a Security Profile filtered by unique id (UUID) with more than one item", 1, profiles.size()); - - // We can now delete the new entity - api.deleteSecurityProfile(sProfile.getUuid()); - } catch (final NiciraNvpApiException e) { - e.printStackTrace(); - assertTrue("Errors in Security Profile CRUD", false); - } - } - - @Test - public void testCRUDAclReadAll() { - try { - Acl acl = setupAcl(); - - acl = api.createAcl(acl); - acl.setDisplayName("UpdatedAcl" + timestamp); - api.updateAcl(acl, acl.getUuid()); - - List acls = api.findAcl(); - Acl scInList = null; - for (final Acl iAcl : acls) { - if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) { - scInList = iAcl; - } - } - assertEquals("Read a ACL different from the one just created and updated", acl, scInList); - - api.deleteAcl(acl.getUuid()); - } catch (final NiciraNvpApiException e) { - e.printStackTrace(); - fail("Errors in ACL CRUD"); - } - } - - @Test - public void testCRUDAclReadOne() { - try { - Acl acl = setupAcl(); - - acl = api.createAcl(acl); - acl.setDisplayName("UpdatedAcl" + timestamp); - api.updateAcl(acl, acl.getUuid()); - - List acls = api.findAcl(acl.getUuid()); - assertEquals("Read a ACL different from the one just created and updated", acl, acls.get(0)); - assertEquals("Read a ACL filtered by unique id (UUID) with more than one item", 1, acls.size()); - - api.deleteAcl(acl.getUuid()); - } catch (final NiciraNvpApiException e) { - e.printStackTrace(); - fail("Errors in ACL CRUD"); - } - } - - @Test - public void testCRUDLogicalSwitch() throws Exception { - LogicalSwitch logicalSwitch = new LogicalSwitch(); - logicalSwitch.setDisplayName("LogicalSwitch" + timestamp); - logicalSwitch.setPortIsolationEnabled(true); - logicalSwitch.setReplicationMode("service"); - logicalSwitch.setTags(new ArrayList()); - logicalSwitch.getTags().add(new NiciraNvpTag("anto", "hugo")); - - // In the creation we don't get to specify UUID, href or schema: they don't exist yet - - logicalSwitch = api.createLogicalSwitch(logicalSwitch); - - // We can now update the new entity - logicalSwitch.setDisplayName("UpdatedLogicalSwitch" + timestamp); - api.updateLogicalSwitch(logicalSwitch, logicalSwitch.getUuid()); - - // Read them all - List logicalSwitches = api.findLogicalSwitch(); - for (final LogicalSwitch iLogicalSwitch : logicalSwitches) { - if (iLogicalSwitch.getUuid().equalsIgnoreCase(logicalSwitch.getUuid())) { - assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, iLogicalSwitch); - } - } - - // Read them filtered by uuid (get one) - logicalSwitches = api.findLogicalSwitch(logicalSwitch.getUuid()); - assertEquals("Read a LogicalSwitch different from the one just created and updated", logicalSwitch, logicalSwitches.get(0)); - assertEquals("Read a LogicalSwitch filtered by unique id (UUID) with more than one item", 1, logicalSwitches.size()); - - // Before deleting the test LogicalSwitch, test its ports - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", "OwnerName")); - - LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort("LSwitchPort" + timestamp, tags, true); - logicalSwitchPort = api.createLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort); - - logicalSwitchPort.setDisplayName("UpdatedLSwitchPort" + timestamp); - api.updateLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort); - - final List logicalSwitchePorts = api.findLogicalSwitchPortsByUuid(logicalSwitch.getUuid(), logicalSwitchPort.getUuid()); - for (final LogicalSwitchPort iLSwitchPort : logicalSwitchePorts) { - if (iLSwitchPort.getUuid().equalsIgnoreCase(logicalSwitchPort.getUuid())) { - assertEquals("Read a LogicalSwitchPort different from the one just created and updated", logicalSwitchPort, iLSwitchPort); - } - } - - // And finally test attachments - final String attachmentUuid = UUID.randomUUID().toString(); - final VifAttachment vifAttachment = new VifAttachment(attachmentUuid); - api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), vifAttachment); - - assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected", - api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()), logicalSwitchPort.getUuid()); - - api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid()); - - // We can now delete the new entity - api.deleteLogicalSwitch(logicalSwitch.getUuid()); - } - - @Test - public void testCRUDLogicalRouter() { - LogicalRouter logicalRouter = new LogicalRouter(); - logicalRouter.setDisplayName("LogicalRouter" + timestamp); - logicalRouter.setDistributed(true); - logicalRouter.setNatSynchronizationEnabled(true); - logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE); - final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig( - new RouterNextHop("192.168.10.20")); - logicalRouter.setRoutingConfig(routingConfig); - - // In the creation we don't get to specify UUID, href or schema: they don't exist yet - - try { - logicalRouter = api.createLogicalRouter(logicalRouter); - - // We can now update the new entity - logicalRouter.setDisplayName("UpdatedLogicalSwitch" + timestamp); - api.updateLogicalRouter(logicalRouter, logicalRouter.getUuid()); - - // Read them all - List logicalRouters = api.findLogicalRouter(); - LogicalRouter lsInList = null; - for (final LogicalRouter iLogicalRouter : logicalRouters) { - if (iLogicalRouter.getUuid().equalsIgnoreCase(logicalRouter.getUuid())) { - lsInList = iLogicalRouter; - } - } - assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, lsInList); - - // Read them filtered by uuid (get one) - logicalRouters = api.findLogicalRouter(logicalRouter.getUuid()); - assertEquals("Read a LogicalRouter different from the one just created and updated", logicalRouter, logicalRouters.get(0)); - assertEquals("Read a LogicalRouter filtered by unique id (UUID) with more than one item", 1, logicalRouters.size()); - - assertEquals(logicalRouters.get(0), api.findOneLogicalRouterByUuid(logicalRouter.getUuid())); - - // Before deleting the test LogicalRouter, test its ports - final List tags = new ArrayList(); - tags.add(new NiciraNvpTag("cs_account", "OwnerName")); - - LogicalRouterPort logicalRouterPort = new LogicalRouterPort(); - logicalRouterPort.setDisplayName("LRouterPort" + timestamp); - logicalRouterPort.setTags(tags); - logicalRouterPort.setAdminStatusEnabled(true); - logicalRouterPort.setPortno(1024); - logicalRouterPort.setMacAddress("00:00:00:00:00:00"); - - final List ipAddresses = new ArrayList(); - // Add some ips to this list - logicalRouterPort.setIpAddresses(ipAddresses); - logicalRouterPort = api.createLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort); - - logicalRouterPort.setDisplayName("UpdatedLRouterPort" + timestamp); - api.updateLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort); - - final List logicalRouterePorts = api.findLogicalRouterPortsByUuid(logicalRouter.getUuid(), logicalRouterPort.getUuid()); - for (final LogicalRouterPort iLRouterPort : logicalRouterePorts) { - if (iLRouterPort.getUuid().equalsIgnoreCase(logicalRouterPort.getUuid())) { - assertEquals("Read a LogicalRouterPort different from the one just created and updated", logicalRouterPort, iLRouterPort); - } - } - - UUID.randomUUID().toString(); - - // Test CRUD for Nat Rules - SourceNatRule snr = new SourceNatRule(); - snr.setToSourceIpAddressMin("192.168.10.10"); - snr.setToSourceIpAddressMax("192.168.10.20"); - snr.setOrder(200); - final Match match = new Match(); - match.setSourceIpAddresses("192.168.150.150"); - snr.setMatch(match); - snr = (SourceNatRule) api.createLogicalRouterNatRule(logicalRouter.getUuid(), snr); - snr.setToSourceIpAddressMax("192.168.10.30"); - api.updateLogicalRouterNatRule(logicalRouter.getUuid(), snr); - - api.findNatRulesByLogicalRouterUuid(logicalRouter.getUuid()); - api.deleteLogicalRouterNatRule(logicalRouter.getUuid(), snr.getUuid()); - - api.deleteLogicalRouterPort(logicalRouter.getUuid(), logicalRouterPort.getUuid()); - - // We can now delete the new entity - api.deleteLogicalRouter(logicalRouter.getUuid()); - } catch (final NiciraNvpApiException e) { - e.printStackTrace(); - assertTrue("Errors in LogicalRouter CRUD", false); - } - } - - @Test - public void testGetControlClusterStatus() throws NiciraNvpApiException { - final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus(); - final String clusterStatus = controlClusterStatus.getClusterStatus(); - final boolean correctStatus = clusterStatus.equalsIgnoreCase("stable") || - clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"); - assertTrue("Not recognizable cluster status", correctStatus); - } - - private Acl setupAcl() { - Acl acl = new Acl(); - acl.setDisplayName("Acl" + timestamp); - - // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type - // Note that if the protocol is 1 (ICMP) then you cannot put ports - final List egressRules = new ArrayList<>(); - acl.setLogicalPortEgressRules(egressRules); - egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); - egressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); - - final List ingressRules = new ArrayList<>(); - acl.setLogicalPortIngressRules(ingressRules); - ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 1, "allow", null, null, "1.10.10.0", "1.10.10.1", null, null, null, null, 0, 0, 5)); - ingressRules.add(new AclRule(AclRule.ETHERTYPE_IPV4, 6, "allow", null, null, "1.10.10.6", "1.10.10.7", 80, 80, 80, 80, 1, null, null)); - - final List tags = new ArrayList<>(); - acl.setTags(tags); - tags.add(new NiciraNvpTag("nvp", "MyTag1")); - tags.add(new NiciraNvpTag("nicira", "MyTag2")); - // In the creation we don't get to specify UUID, href or schema: they don't exist yet - - return acl; - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java deleted file mode 100644 index ed3eccaaafc1..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraNvpApiTest.java +++ /dev/null @@ -1,198 +0,0 @@ -// -// 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.network.nicira; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.hasSize; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.List; - -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.message.BasicStatusLine; -import org.hamcrest.Matchers; -import org.junit.Test; - -import com.cloud.utils.rest.HttpClientHelper; -import com.cloud.utils.rest.HttpUriRequestMethodMatcher; -import com.cloud.utils.rest.HttpUriRequestPathMatcher; -import com.cloud.utils.rest.HttpUriRequestQueryMatcher; - -public class NiciraNvpApiTest { - private static final StatusLine HTTP_200_REPSONSE = new BasicStatusLine(new ProtocolVersion("HTTPS", 1, 1), HttpStatus.SC_OK, "OK"); - private static final StatusLine HTTP_201_REPSONSE = new BasicStatusLine(new ProtocolVersion("HTTPS", 1, 1), HttpStatus.SC_CREATED, "Created"); - - protected static final String UUID = "aaaa"; - protected static final String UUID2 = "bbbb"; - protected static final String UUID_SEC_PROFILE_URI = NiciraConstants.SEC_PROFILE_URI_PREFIX + "/aaaa"; - protected static final String SCHEMA = "myTestSchema"; - protected static final String SCHEMA2 = "myTestSchema2"; - protected static final String HREF = "myTestHref"; - protected static final String HREF2 = "myTestHref2"; - protected static final String SEC_PROFILE_JSON_RESPONSE = - "{\"uuid\" : \"aaaa\"," - + "\"display_name\" : \"myTestName\"," - + "\"href\" : \"myTestHref\"," - + "\"schema\" : \"myTestSchema\"}"; - - protected static final String SEC_PROFILE_LIST_JSON_RESPONSE = "{\"results\" : [{\"uuid\" : \"aaaa\"," - + "\"display_name\" : \"myTestName\"," - + "\"href\" : \"myTestHref\"," - + "\"schema\" : \"myTestSchema\"}," - + "{ \"uuid\" : \"bbbb\"," - + "\"display_name\" : \"myTestName2\"," - + "\"href\" : \"myTestHref2\"," - + "\"schema\" : \"myTestSchema2\"}]," - + "\"result_count\": 2}"; - - private static NiciraNvpApi buildApi(final CloseableHttpClient httpClient) { - return NiciraNvpApi.create() - .host("localhost") - .username("admin") - .password("adminpassword") - .httpClient(httpClient) - .build(); - } - - @Test - @SuppressWarnings("unchecked") - public void testFindSecurityProfile() throws Exception { - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - when(response.getStatusLine()).thenReturn(HTTP_200_REPSONSE); - when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_LIST_JSON_RESPONSE)); - final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); - doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); - final NiciraNvpApi api = buildApi(httpClient); - - final List actualProfiles = api.findSecurityProfile(); - - assertThat("Wrong number of results", actualProfiles, hasSize(2)); - assertThat("Wrong Uuid in the newly created SecurityProfile", actualProfiles, Matchers. contains( - hasProperty("uuid", equalTo(UUID)), - hasProperty("uuid", equalTo(UUID2)))); - assertThat("Wrong HREF in the newly created SecurityProfile", actualProfiles, Matchers. contains( - hasProperty("href", equalTo(HREF)), - hasProperty("href", equalTo(HREF2)))); - assertThat("Wrong Schema in the newly created SecurityProfile", actualProfiles, Matchers. contains( - hasProperty("schema", equalTo(SCHEMA)), - hasProperty("schema", equalTo(SCHEMA2)))); - verify(response, times(1)).close(); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQuery("fields=*"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); - } - - @Test - @SuppressWarnings("unchecked") - public void testFindSecurityProfileByUuid() throws Exception { - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - when(response.getStatusLine()).thenReturn(HTTP_200_REPSONSE); - when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_LIST_JSON_RESPONSE)); - final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); - doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); - final NiciraNvpApi api = buildApi(httpClient); - - final List actualProfiles = api.findSecurityProfile(UUID); - - assertThat("Wrong number of results", actualProfiles, hasSize(2)); - assertThat("Wrong Uuid in the newly created SecurityProfile", actualProfiles, Matchers. contains( - hasProperty("uuid", equalTo(UUID)), - hasProperty("uuid", equalTo(UUID2)))); - assertThat("Wrong HREF in the newly created SecurityProfile", actualProfiles, Matchers. contains( - hasProperty("href", equalTo(HREF)), - hasProperty("href", equalTo(HREF2)))); - assertThat("Wrong Schema in the newly created SecurityProfile", actualProfiles, Matchers. contains( - hasProperty("schema", equalTo(SCHEMA)), - hasProperty("schema", equalTo(SCHEMA2)))); - verify(response, times(1)).close(); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("GET"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("uuid=" + UUID), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("fields=*"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); - } - - @Test - public void testCreateSecurityProfile() throws Exception { - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); - when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); - final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); - doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); - final NiciraNvpApi api = buildApi(httpClient); - - final SecurityProfile actualSecProfile = api.createSecurityProfile(new SecurityProfile()); - - assertThat("Wrong Uuid in the newly created SecurityProfile", actualSecProfile, hasProperty("uuid", equalTo(UUID))); - assertThat("Wrong Href in the newly created SecurityProfile", actualSecProfile, hasProperty("href", equalTo(HREF))); - assertThat("Wrong Schema in the newly created SecurityProfile", actualSecProfile, hasProperty("schema", equalTo(SCHEMA))); - verify(response, times(1)).close(); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX), any(HttpClientContext.class)); - } - - @Test - public void testUpdateSecurityProfile() throws Exception { - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); - when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); - final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); - doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); - final NiciraNvpApi api = buildApi(httpClient); - - api.updateSecurityProfile(new SecurityProfile(), UUID); - - verify(response, times(1)).close(); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("PUT"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX + "/" + UUID), any(HttpClientContext.class)); - } - - @Test - public void testDeleteSecurityProfile() throws Exception { - final CloseableHttpResponse response = mock(CloseableHttpResponse.class); - when(response.getStatusLine()).thenReturn(HTTP_201_REPSONSE); - when(response.getEntity()).thenReturn(new StringEntity(SEC_PROFILE_JSON_RESPONSE)); - final CloseableHttpClient httpClient = spy(HttpClientHelper.createHttpClient(2)); - doReturn(response).when(httpClient).execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class)); - final NiciraNvpApi api = buildApi(httpClient); - - api.deleteSecurityProfile(UUID); - - verify(response, times(1)).close(); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("DELETE"), any(HttpClientContext.class)); - verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPathMatcher.aPath(NiciraConstants.SEC_PROFILE_URI_PREFIX + "/" + UUID), any(HttpClientContext.class)); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java deleted file mode 100644 index bae11c7bfa2a..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraRestClientTest.java +++ /dev/null @@ -1,212 +0,0 @@ -// -// 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.network.nicira; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.isEmptyOrNullString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.http.HttpHost; -import org.apache.http.ProtocolVersion; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.message.BasicStatusLine; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; - -import com.cloud.utils.rest.CloudstackRESTException; -import com.cloud.utils.rest.HttpMethods; -import com.cloud.utils.rest.HttpRequestMatcher; -import com.cloud.utils.rest.HttpUriRequestBuilder; - -@RunWith(MockitoJUnitRunner.class) -public class NiciraRestClientTest { - - private static final int HTTPS_PORT = 443; - - private static final String HTTPS = "HTTPS"; - private static final String LOGIN_PATH = "/login"; - private static final String LOCALHOST = "localhost"; - private static final String ADMIN = "admin"; - private static final String ADMIN_PASSWORD = "adminpassword"; - - private static final HttpHost HTTP_HOST = new HttpHost(LOCALHOST, HTTPS_PORT, HTTPS); - - private static final StatusLine HTTP_200_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 200, "OK"); - private static final StatusLine HTTP_401_STATUSLINE = new BasicStatusLine(new ProtocolVersion(HTTPS, 1, 1), 401, "Unauthorized"); - - private static final Map loginParameters = new LinkedHashMap(); - private static HttpUriRequest request; - private static HttpUriRequest loginRequest; - private final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); - private final CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class); - private HttpClientContext httpClientContext; - private NiciraRestClient client; - - @BeforeClass - public static void setupClass() { - loginParameters.put("username", ADMIN); - loginParameters.put("password", ADMIN_PASSWORD); - request = HttpUriRequestBuilder.create() - .method(HttpMethods.GET) - .path("/path") - .build(); - loginRequest = HttpUriRequestBuilder.create() - .method(HttpMethods.POST) - .methodParameters(loginParameters) - .path(LOGIN_PATH) - .build(); - } - - @Before - public void setup() { - httpClientContext = HttpClientContext.create(); - client = spy(NiciraRestClient.create() - .client(httpClient) - .clientContext(httpClientContext) - .hostname(LOCALHOST) - .username(ADMIN) - .password(ADMIN_PASSWORD) - .loginUrl(LOGIN_PATH) - .executionLimit(5) - .build()); - } - - @Test - public void testExecuteSuccessAtFirstAttempt() throws Exception { - when(mockResponse.getStatusLine()).thenReturn(HTTP_200_STATUSLINE); - when(httpClient.execute(eq(HTTP_HOST), eq(request), eq(httpClientContext))).thenReturn(mockResponse); - - final CloseableHttpResponse response = client.execute(request); - - assertThat(response, notNullValue()); - assertThat(response, sameInstance(mockResponse)); - verify(client).execute(request, 0); - } - - @Test - public void testExecuteUnauthorizedThenSuccess() throws Exception { - when(mockResponse.getStatusLine()) - .thenReturn(HTTP_401_STATUSLINE) - .thenReturn(HTTP_200_STATUSLINE) - .thenReturn(HTTP_200_STATUSLINE); - when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext))) - .thenReturn(mockResponse) - .thenReturn(mockResponse); - when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext))) - .thenReturn(mockResponse); - - final CloseableHttpResponse response = client.execute(request); - - assertThat(response, notNullValue()); - assertThat(response, sameInstance(mockResponse)); - verify(client).execute((HttpUriRequest)HttpRequestMatcher.eq(request), eq(0)); - verify(client).execute((HttpUriRequest)HttpRequestMatcher.eq(request), eq(200)); - verify(client).execute((HttpUriRequest)HttpRequestMatcher.eq(loginRequest), eq(401)); - } - - @Test - public void testExecuteTwoConsecutiveUnauthorizedExecutions() throws Exception { - when(mockResponse.getStatusLine()) - .thenReturn(HTTP_401_STATUSLINE) - .thenReturn(HTTP_401_STATUSLINE); - when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext))) - .thenReturn(mockResponse); - when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext))) - .thenReturn(mockResponse); - final NiciraRestClient client = spy(NiciraRestClient.create() - .client(httpClient) - .clientContext(httpClientContext) - .hostname(LOCALHOST) - .username(ADMIN) - .password(ADMIN_PASSWORD) - .loginUrl(LOGIN_PATH) - .executionLimit(2) - .build()); - - try { - client.execute(request); - fail("Expected CloudstackRESTException exception"); - } catch (final CloudstackRESTException e) { - assertThat(e.getMessage(), not(isEmptyOrNullString())); - verify(client).execute((HttpUriRequest)HttpRequestMatcher.eq(request), eq(0)); - verify(client).execute((HttpUriRequest)HttpRequestMatcher.eq(loginRequest), eq(401)); - } - } - - @Test - public void testExecuteLiveLockWhenControllerAllowsLoginAndFollowsWithUnauthorizedButDoesNotRediect() throws Exception { - when(mockResponse.getStatusLine()) - .thenReturn(HTTP_401_STATUSLINE) - .thenReturn(HTTP_200_STATUSLINE) - .thenReturn(HTTP_401_STATUSLINE) - .thenReturn(HTTP_200_STATUSLINE) - .thenReturn(HTTP_401_STATUSLINE) - .thenReturn(HTTP_200_STATUSLINE) - .thenReturn(HTTP_401_STATUSLINE) - .thenReturn(HTTP_200_STATUSLINE) - .thenReturn(HTTP_401_STATUSLINE); - when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(request), eq(httpClientContext))) - .thenReturn(mockResponse) - .thenReturn(mockResponse) - .thenReturn(mockResponse) - .thenReturn(mockResponse) - .thenReturn(mockResponse); - when(httpClient.execute(eq(HTTP_HOST), HttpRequestMatcher.eq(loginRequest), eq(httpClientContext))) - .thenReturn(mockResponse) - .thenReturn(mockResponse) - .thenReturn(mockResponse) - .thenReturn(mockResponse); - final NiciraRestClient client = spy(NiciraRestClient.create() - .client(httpClient) - .clientContext(httpClientContext) - .hostname(LOCALHOST) - .username(ADMIN) - .password(ADMIN_PASSWORD) - .loginUrl(LOGIN_PATH) - .executionLimit(2) - .build()); - - try { - client.execute(request); - fail("Execution count should have been maxed out"); - } catch (final CloudstackRESTException e) { - assertThat(e.getMessage(), containsString("Reached max executions limit of ")); - } - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java deleted file mode 100644 index 6b3ffc3bbddd..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/NiciraTagTest.java +++ /dev/null @@ -1,58 +0,0 @@ -// -// 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.network.nicira; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class NiciraTagTest { - @Test - public void testCreateTag() { - final NiciraNvpTag tag = new NiciraNvpTag("scope", "tag"); - assertEquals("scope part set", "scope", tag.getScope()); - assertEquals("tag part set", "tag", tag.getTag()); - } - - @Test - public void testCreateLongTag() { - final NiciraNvpTag tag = new NiciraNvpTag("scope", "verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); - assertEquals("scope part set", "scope", tag.getScope()); - assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag()); - } - - @Test - public void testSetTag() { - final NiciraNvpTag tag = new NiciraNvpTag(); - tag.setScope("scope"); - tag.setTag("tag"); - assertEquals("scope part set", "scope", tag.getScope()); - assertEquals("tag part set", "tag", tag.getTag()); - } - - @Test - public void testSetLongTag() { - final NiciraNvpTag tag = new NiciraNvpTag(); - tag.setScope("scope"); - tag.setTag("verylongtagthatshouldattheminimumexceedthefortycharacterlenght"); - assertEquals("scope part set", "scope", tag.getScope()); - assertEquals("tag part set", "verylongtagthatshouldattheminimumexceedt", tag.getTag()); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java deleted file mode 100644 index 44269b235449..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/nicira/RoutingConfigAdapterTest.java +++ /dev/null @@ -1,57 +0,0 @@ -// -// 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.network.nicira; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.notNullValue; - -import org.junit.Test; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; - -public class RoutingConfigAdapterTest { - private final Gson gson = new GsonBuilder() - .registerTypeAdapter(RoutingConfig.class, new RoutingConfigAdapter()) - .create(); - - @Test(expected = JsonParseException.class) - public void testRoutingConfigAdapterNoType() { - gson.fromJson("{}", RoutingConfig.class); - } - - @Test(expected = JsonParseException.class) - public void testRoutingConfigAdapterWrongType() { - gson.fromJson("{type : \"WrongType\"}", RoutingConfig.class); - } - - @Test() - public void testRoutingConfigAdapter() throws Exception { - final String jsonString = "{type : \"SingleDefaultRouteImplicitRoutingConfig\"}"; - - final SingleDefaultRouteImplicitRoutingConfig object = gson.fromJson(jsonString, SingleDefaultRouteImplicitRoutingConfig.class); - - assertThat(object, notNullValue()); - assertThat(object, instanceOf(SingleDefaultRouteImplicitRoutingConfig.class)); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java deleted file mode 100644 index a28cb5fd5eac..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java +++ /dev/null @@ -1,250 +0,0 @@ -// -// 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.network.resource; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; -import com.cloud.agent.api.CreateLogicalSwitchCommand; -import com.cloud.agent.api.DeleteLogicalRouterCommand; -import com.cloud.agent.api.DeleteLogicalSwitchCommand; -import com.cloud.agent.api.DeleteLogicalSwitchPortCommand; -import com.cloud.agent.api.MaintainCommand; -import com.cloud.agent.api.ReadyCommand; -import com.cloud.agent.api.UpdateLogicalSwitchPortCommand; -import com.cloud.network.nicira.LogicalRouterPort; -import com.cloud.network.nicira.LogicalSwitch; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.VifAttachment; - -public class NiciraNvpRequestWrapperTest { - - @Mock - private final NiciraNvpResource niciraNvpResource = Mockito.mock(NiciraNvpResource.class); - - @Test - public void testReadyCommandWrapper() { - final ReadyCommand command = new ReadyCommand(); - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testMaintainCommandWrapper() { - final MaintainCommand command = new MaintainCommand(); - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testCreateLogicalSwitchCommandWrapper() { - final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); - final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class); - final LogicalSwitch logicalSwitch = Mockito.mock(LogicalSwitch.class); - - final String transportUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String transportType = "stt"; - final String name = "logicalswitch"; - final String ownerName = "owner"; - - final CreateLogicalSwitchCommand command = new CreateLogicalSwitchCommand(transportUuid, transportType, name, ownerName); - - final String truncated = "lswitch-" + command.getName(); - - when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities); - when(niciraNvpUtilities.createLogicalSwitch()).thenReturn(logicalSwitch); - when(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN)).thenReturn(truncated); - when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); - - try { - when(niciraNvpApi.createLogicalSwitch(logicalSwitch)).thenReturn(logicalSwitch); - when(logicalSwitch.getUuid()).thenReturn(transportUuid); - } catch (final NiciraNvpApiException e) { - fail(e.getMessage()); - } - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testDeleteLogicalSwitchCommandWrapper() { - final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); - - final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - - final DeleteLogicalSwitchCommand command = new DeleteLogicalSwitchCommand(logicalSwitchUuid); - - when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); - - try { - doNothing().when(niciraNvpApi).deleteLogicalSwitch(command.getLogicalSwitchUuid()); - } catch (final NiciraNvpApiException e) { - fail(e.getMessage()); - } - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testConfigurePublicIpsOnLogicalRouterCommand() { - final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); - final LogicalRouterPort port1 = Mockito.mock(LogicalRouterPort.class); - - final List listPorts = new ArrayList(); - listPorts.add(port1); - - final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String l3GatewayServiceUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final List publicCidrs = new ArrayList(); - publicCidrs.add("10.1.1.0/24"); - - final ConfigurePublicIpsOnLogicalRouterCommand command = new ConfigurePublicIpsOnLogicalRouterCommand(logicalRouterUuid, l3GatewayServiceUuid, publicCidrs); - - when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); - - try { - when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(listPorts); - doNothing().when(niciraNvpApi).updateLogicalRouterPort(command.getLogicalRouterUuid(), port1); - } catch (final NiciraNvpApiException e) { - fail(e.getMessage()); - } - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testDeleteLogicalSwitchPortCommand() { - final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); - - final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - - final DeleteLogicalSwitchPortCommand command = new DeleteLogicalSwitchPortCommand(logicalSwitchUuid, logicalSwitchPortUuid); - - when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); - - try { - doNothing().when(niciraNvpApi).deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid()); - } catch (final NiciraNvpApiException e) { - fail(e.getMessage()); - } - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testDeleteLogicalRouterCommand() { - final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); - - final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - - final DeleteLogicalRouterCommand command = new DeleteLogicalRouterCommand(logicalRouterUuid); - - when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); - - try { - doNothing().when(niciraNvpApi).deleteLogicalRouter(command.getLogicalRouterUuid()); - } catch (final NiciraNvpApiException e) { - fail(e.getMessage()); - } - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } - - @Test - public void testUpdateLogicalSwitchPortCommand() { - final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class); - final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class); - final VifAttachment vifAttachment = Mockito.mock(VifAttachment.class); - - final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String attachmentUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345"; - final String ownerName = "admin"; - final String nicName = "eth0"; - - final UpdateLogicalSwitchPortCommand command = new UpdateLogicalSwitchPortCommand(logicalSwitchPortUuid, logicalSwitchUuid, attachmentUuid, ownerName, nicName); - - when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities); - when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi); - - try { - when(niciraNvpUtilities.createVifAttachment(attachmentUuid)).thenReturn(vifAttachment); - doNothing().when(niciraNvpApi).updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment); - } catch (final NiciraNvpApiException e) { - fail(e.getMessage()); - } - - final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance(); - assertNotNull(wrapper); - - final Answer answer = wrapper.execute(command, niciraNvpResource); - - assertTrue(answer.getResult()); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java deleted file mode 100644 index 417a8468a562..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/NiciraNvpResourceTest.java +++ /dev/null @@ -1,825 +0,0 @@ -// -// 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.network.resource; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.naming.ConfigurationException; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatcher; - -import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand; -import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer; -import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand; -import com.cloud.agent.api.CreateLogicalRouterAnswer; -import com.cloud.agent.api.CreateLogicalRouterCommand; -import com.cloud.agent.api.CreateLogicalSwitchAnswer; -import com.cloud.agent.api.CreateLogicalSwitchCommand; -import com.cloud.agent.api.CreateLogicalSwitchPortAnswer; -import com.cloud.agent.api.CreateLogicalSwitchPortCommand; -import com.cloud.agent.api.DeleteLogicalRouterAnswer; -import com.cloud.agent.api.DeleteLogicalRouterCommand; -import com.cloud.agent.api.DeleteLogicalSwitchAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchCommand; -import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer; -import com.cloud.agent.api.DeleteLogicalSwitchPortCommand; -import com.cloud.agent.api.FindLogicalSwitchPortAnswer; -import com.cloud.agent.api.FindLogicalSwitchPortCommand; -import com.cloud.agent.api.PingCommand; -import com.cloud.agent.api.StartupCommand; -import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer; -import com.cloud.agent.api.UpdateLogicalSwitchPortCommand; -import com.cloud.agent.api.to.PortForwardingRuleTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.host.Host; -import com.cloud.network.nicira.Attachment; -import com.cloud.network.nicira.ControlClusterStatus; -import com.cloud.network.nicira.DestinationNatRule; -import com.cloud.network.nicira.LogicalRouter; -import com.cloud.network.nicira.LogicalRouterPort; -import com.cloud.network.nicira.LogicalSwitch; -import com.cloud.network.nicira.LogicalSwitchPort; -import com.cloud.network.nicira.NatRule; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.nicira.SourceNatRule; -import com.cloud.network.utils.CommandRetryUtility; - -public class NiciraNvpResourceTest { - NiciraNvpApi nvpApi = mock(NiciraNvpApi.class); - NiciraNvpResource resource; - Map parameters; - - private CommandRetryUtility retryUtility; - - @Before - public void setUp() { - resource = new NiciraNvpResource() { - @Override - protected NiciraNvpApi createNiciraNvpApi(final String host, final String username, final String password) { - return nvpApi; - } - }; - - parameters = new HashMap(); - parameters.put("name", "nvptestdevice"); - parameters.put("ip", "127.0.0.1"); - parameters.put("adminuser", "adminuser"); - parameters.put("guid", "aaaaa-bbbbb-ccccc"); - parameters.put("zoneId", "blublub"); - parameters.put("adminpass", "adminpass"); - - retryUtility = CommandRetryUtility.getInstance(); - retryUtility.setServerResource(resource); - } - - @Test(expected = ConfigurationException.class) - public void resourceConfigureFailure() throws ConfigurationException { - resource.configure("NiciraNvpResource", Collections. emptyMap()); - } - - @Test - public void testInitialization() throws ConfigurationException { - resource.configure("NiciraNvpResource", parameters); - - final StartupCommand[] sc = resource.initialize(); - assertTrue(sc.length == 1); - assertTrue("Incorrect startup command GUID", "aaaaa-bbbbb-ccccc".equals(sc[0].getGuid())); - assertTrue("Incorrect NVP device name", "nvptestdevice".equals(sc[0].getName())); - assertTrue("Incorrect Data Center", "blublub".equals(sc[0].getDataCenter())); - } - - @Test - public void testPingCommandStatusOk() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getClusterStatus()).thenReturn("stable"); - when(nvpApi.getControlClusterStatus()).thenReturn(ccs); - - final PingCommand ping = resource.getCurrentStatus(42); - assertTrue(ping != null); - assertTrue(ping.getHostId() == 42); - assertTrue(ping.getHostType() == Host.Type.L2Networking); - } - - @Test - public void testPingCommandStatusFail() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getClusterStatus()).thenReturn("unstable"); - when(nvpApi.getControlClusterStatus()).thenReturn(ccs); - - final PingCommand ping = resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testPingCommandStatusApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final ControlClusterStatus ccs = mock(ControlClusterStatus.class); - when(ccs.getClusterStatus()).thenReturn("unstable"); - when(nvpApi.getControlClusterStatus()).thenThrow(new NiciraNvpApiException()); - - final PingCommand ping = resource.getCurrentStatus(42); - assertTrue(ping == null); - } - - @Test - public void testRetries() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalSwitch ls = mock(LogicalSwitch.class); - when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()).thenThrow(new NiciraNvpApiException()).thenReturn(ls); - - final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner"); - final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc); - assertTrue(clsa.getResult()); - } - - @Test - public void testCreateLogicalSwitch() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalSwitch ls = mock(LogicalSwitch.class); - when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenReturn(ls); - - final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner"); - final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc); - assertTrue(clsa.getResult()); - assertTrue("cccc".equals(clsa.getLogicalSwitchUuid())); - } - - @Test - public void testCreateLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalSwitch ls = mock(LogicalSwitch.class); - when(ls.getUuid()).thenReturn("cccc").thenReturn("cccc"); - when(nvpApi.createLogicalSwitch((LogicalSwitch) any())).thenThrow(new NiciraNvpApiException()); - - final CreateLogicalSwitchCommand clsc = new CreateLogicalSwitchCommand((String) parameters.get("guid"), "stt", "loigicalswitch", "owner"); - final CreateLogicalSwitchAnswer clsa = (CreateLogicalSwitchAnswer) resource.executeRequest(clsc); - assertFalse(clsa.getResult()); - } - - @Test - public void testDeleteLogicalSwitch() throws ConfigurationException { - resource.configure("NiciraNvpResource", parameters); - - final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) resource.executeRequest(dlsc); - assertTrue(dlsa.getResult()); - } - - @Test - public void testDeleteLogicalSwitchApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitch((String) any()); - - final DeleteLogicalSwitchCommand dlsc = new DeleteLogicalSwitchCommand("cccc"); - final DeleteLogicalSwitchAnswer dlsa = (DeleteLogicalSwitchAnswer) resource.executeRequest(dlsc); - assertFalse(dlsa.getResult()); - } - - @Test - public void testCreateLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lsp.getUuid()).thenReturn("eeee"); - when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); - - final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc); - assertTrue(clspa.getResult()); - assertTrue("eeee".equals(clspa.getLogicalSwitchPortUuid())); - - } - - @Test - public void testCreateLogicalSwitchPortApiExceptionInCreate() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lsp.getUuid()).thenReturn("eeee"); - when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenThrow(new NiciraNvpApiException()); - - final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc); - assertFalse(clspa.getResult()); - } - - @Test - public void testCreateLogicalSwitchPortApiExceptionInModify() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lsp.getUuid()).thenReturn("eeee"); - when(nvpApi.createLogicalSwitchPort(eq("cccc"), (LogicalSwitchPort) any())).thenReturn(lsp); - doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); - - final CreateLogicalSwitchPortCommand clspc = new CreateLogicalSwitchPortCommand("cccc", "dddd", "owner", "nicname"); - final CreateLogicalSwitchPortAnswer clspa = (CreateLogicalSwitchPortAnswer) resource.executeRequest(clspc); - assertFalse(clspa.getResult()); - verify(nvpApi, atLeastOnce()).deleteLogicalSwitchPort((String) any(), (String) any()); - } - - @Test - public void testDeleteLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalSwitchPort((String) any(), (String) any()); - final DeleteLogicalSwitchPortAnswer dlspa = (DeleteLogicalSwitchPortAnswer) resource.executeRequest(new DeleteLogicalSwitchPortCommand("aaaa", "bbbb")); - assertFalse(dlspa.getResult()); - } - - @Test - public void testUpdateLogicalSwitchPortException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String) any(), (String) any(), (Attachment) any()); - final UpdateLogicalSwitchPortAnswer dlspa = - (UpdateLogicalSwitchPortAnswer) resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname")); - assertFalse(dlspa.getResult()); - } - - @Test - public void testFindLogicalSwitchPort() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final List lspl = Arrays.asList(new LogicalSwitchPort()); - when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - - final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); - assertTrue(flspa.getResult()); - } - - @Test - public void testFindLogicalSwitchPortNotFound() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - @SuppressWarnings("unchecked") - final List lspl = Collections.EMPTY_LIST; - when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenReturn(lspl); - - final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); - assertFalse(flspa.getResult()); - } - - @Test - public void testFindLogicalSwitchPortApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - when(nvpApi.findLogicalSwitchPortsByUuid("aaaa", "bbbb")).thenThrow(new NiciraNvpApiException()); - - final FindLogicalSwitchPortAnswer flspa = (FindLogicalSwitchPortAnswer) resource.executeRequest(new FindLogicalSwitchPortCommand("aaaa", "bbbb")); - assertFalse(flspa.getResult()); - } - - @Test - public void testCreateLogicalRouter() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalRouter lrc = mock(LogicalRouter.class); - final LogicalRouterPort lrp = mock(LogicalRouterPort.class); - final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lrc.getUuid()).thenReturn("ccccc"); - when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); - when(lsp.getUuid()).thenReturn("fffff"); - when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc); - when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenReturn(lrp); - when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort) any())).thenReturn(lsp); - final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); - - assertTrue(clra.getResult()); - assertTrue("ccccc".equals(clra.getLogicalRouterUuid())); - verify(nvpApi, atLeast(1)).createLogicalRouterNatRule((String) any(), (NatRule) any()); - } - - @Test - public void testCreateLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenThrow(new NiciraNvpApiException()); - final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); - - assertFalse(clra.getResult()); - } - - @Test - public void testCreateLogicalRouterApiExceptionRollbackRouter() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalRouter lrc = mock(LogicalRouter.class); - when(lrc.getUuid()).thenReturn("ccccc"); - when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc); - when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenThrow(new NiciraNvpApiException()); - final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); - - assertFalse(clra.getResult()); - verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); - } - - @Test - public void testCreateLogicalRouterApiExceptionRollbackRouterAndSwitchPort() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final LogicalRouter lrc = mock(LogicalRouter.class); - final LogicalRouterPort lrp = mock(LogicalRouterPort.class); - final LogicalSwitchPort lsp = mock(LogicalSwitchPort.class); - when(lrc.getUuid()).thenReturn("ccccc"); - when(lrp.getUuid()).thenReturn("ddddd").thenReturn("eeeee"); - when(lsp.getUuid()).thenReturn("fffff"); - when(nvpApi.createLogicalRouter((LogicalRouter) any())).thenReturn(lrc); - when(nvpApi.createLogicalRouterPort(eq("ccccc"), (LogicalRouterPort) any())).thenReturn(lrp); - when(nvpApi.createLogicalSwitchPort(eq("bbbbb"), (LogicalSwitchPort) any())).thenReturn(lsp); - when(nvpApi.createLogicalRouterNatRule((String) any(), (NatRule) any())).thenThrow(new NiciraNvpApiException()); - final CreateLogicalRouterCommand clrc = new CreateLogicalRouterCommand("aaaaa", 50, "bbbbb", "lrouter", "publiccidr", "nexthop", "internalcidr", "owner"); - final CreateLogicalRouterAnswer clra = (CreateLogicalRouterAnswer) resource.executeRequest(clrc); - - assertFalse(clra.getResult()); - verify(nvpApi, atLeast(1)).deleteLogicalRouter(eq("ccccc")); - verify(nvpApi, atLeast(1)).deleteLogicalSwitchPort(eq("bbbbb"), eq("fffff")); - } - - @Test - public void testDeleteLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - doThrow(new NiciraNvpApiException()).when(nvpApi).deleteLogicalRouter(eq("aaaaa")); - final DeleteLogicalRouterAnswer dlspa = (DeleteLogicalRouterAnswer) resource.executeRequest(new DeleteLogicalRouterCommand("aaaaa")); - assertFalse(dlspa.getResult()); - } - - @Test - public void testConfigurePublicIpsOnLogicalRouterApiException() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); - @SuppressWarnings("unchecked") - final List list = Collections.EMPTY_LIST; - - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); - when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list); - doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String) any(), (LogicalRouterPort) any()); - - final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) resource.executeRequest(cmd); - assertFalse(answer.getResult()); - - } - - @Test - public void testConfigurePublicIpsOnLogicalRouterRetry() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - - final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class); - - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb"); - when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenThrow(new NiciraNvpApiException("retry 1")).thenThrow(new NiciraNvpApiException("retry 2")); - - final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) resource.executeRequest(cmd); - assertFalse(answer.getResult()); - - } - - @Test - public void testConfigureStaticNatRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api find call - @SuppressWarnings("unchecked") - final List storedRules = Collections.EMPTY_LIST; - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - // Mock the api create calls - final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final NatRule argument) { - final NatRule rule = argument; - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } - })); - } - - @Test - public void testConfigureStaticNatRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - // Mock the api find call - final List storedRules = Arrays.asList(rulepair); - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final NatRule argument) { - final NatRule rule = argument; - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } - })); - } - - @Test - public void testConfigureStaticNatRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, true, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - final UUID rule0Uuid = UUID.randomUUID(); - final UUID rule1Uuid = UUID.randomUUID(); - rulepair[0].setUuid(rule0Uuid); - rulepair[1].setUuid(rule1Uuid); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - // Mock the api find call - final List storedRules = Arrays.asList(rulepair); - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final UUID uuid) { - if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { - return true; - } - return false; - } - })); - } - - @Test - public void testConfigureStaticNatRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigureStaticNatRulesOnLogicalRouterCommand cmd = mock(ConfigureStaticNatRulesOnLogicalRouterCommand.class); - final StaticNatRuleTO rule = new StaticNatRuleTO(1, "11.11.11.11", null, null, "10.10.10.10", null, null, null, false, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - final NatRule[] rulepair = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); - - // Mock the api find call - @SuppressWarnings("unchecked") - final List storedRules = Collections.EMPTY_LIST; - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - final ConfigureStaticNatRulesOnLogicalRouterAnswer a = (ConfigureStaticNatRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertFalse(a.getResult()); - verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); - } - - @Test - public void testConfigurePortForwardingRulesOnLogicalRouter() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api find call - @SuppressWarnings("unchecked") - final List storedRules = Collections.EMPTY_LIST; - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final NatRule rule) { - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } - })); - } - - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterExistingRules() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, true); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - // Mock the api find call - final List storedRules = Arrays.asList(rulepair); - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final NatRule rule) { - if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { - return true; - } - if (rule.getType().equals("SourceNatRule") && ((SourceNatRule) rule).getToSourceIpAddressMin().equals("11.11.11.11")) { - return true; - } - return false; - } - })); - } - - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterRemoveRules() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", true, true); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); - final UUID rule0Uuid = UUID.randomUUID(); - final UUID rule1Uuid = UUID.randomUUID(); - rulepair[0].setUuid(rule0Uuid); - rulepair[1].setUuid(rule1Uuid); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - // Mock the api find call - final List storedRules = Arrays.asList(rulepair); - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertTrue(a.getResult()); - verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final UUID uuid) { - if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { - return true; - } - return false; - } - })); - } - - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterRollback() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 80, "10.10.10.10", 8080, 8080, "tcp", false, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenThrow(new NiciraNvpApiException()); - - // Mock the api find call - @SuppressWarnings("unchecked") - final List storedRules = Collections.EMPTY_LIST; - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - assertFalse(a.getResult()); - verify(nvpApi, atLeastOnce()).deleteLogicalRouterNatRule(eq("aaaaa"), eq(rulepair[0].getUuid())); - } - - @Test - public void testConfigurePortForwardingRulesOnLogicalRouterPortRange() throws ConfigurationException, NiciraNvpApiException { - resource.configure("NiciraNvpResource", parameters); - /* - * StaticNat Outside IP: 11.11.11.11 Inside IP: 10.10.10.10 - */ - - // Mock the command - final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = mock(ConfigurePortForwardingRulesOnLogicalRouterCommand.class); - final PortForwardingRuleTO rule = new PortForwardingRuleTO(1, "11.11.11.11", 80, 85, "10.10.10.10", 80, 85, "tcp", false, false); - final List rules = new ArrayList(); - rules.add(rule); - when(cmd.getRules()).thenReturn(rules); - when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa"); - - // Mock the api find call - @SuppressWarnings("unchecked") - final List storedRules = Collections.EMPTY_LIST; - when(nvpApi.findNatRulesByLogicalRouterUuid("aaaaa")).thenReturn(storedRules); - - // Mock the api create calls - final NatRule[] rulepair = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 80, 85 }, "11.11.11.11", new int[] { 80, 85 }, "tcp"); - rulepair[0].setUuid(UUID.randomUUID()); - rulepair[1].setUuid(UUID.randomUUID()); - when(nvpApi.createLogicalRouterNatRule(eq("aaaaa"), (NatRule) any())).thenReturn(rulepair[0]).thenReturn(rulepair[1]); - - final ConfigurePortForwardingRulesOnLogicalRouterAnswer a = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) resource.executeRequest(cmd); - - // The expected result is false, Nicira does not support port ranges in DNAT - assertFalse(a.getResult()); - - } - - @Test - public void testGenerateStaticNatRulePair() { - final NatRule[] rules = resource.generateStaticNatRulePair("10.10.10.10", "11.11.11.11"); - assertTrue("DestinationNatRule".equals(rules[0].getType())); - assertTrue("SourceNatRule".equals(rules[1].getType())); - - final DestinationNatRule dnr = (DestinationNatRule) rules[0]; - assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); - assertTrue(dnr.getToDestinationPort() == null); - assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); - - final SourceNatRule snr = (SourceNatRule) rules[1]; - assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); - assertTrue(snr.getToSourcePort() == null); - assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); - } - - @Test - public void testGeneratePortForwardingRulePair() { - final NatRule[] rules = resource.generatePortForwardingRulePair("10.10.10.10", new int[] { 8080, 8080 }, "11.11.11.11", new int[] { 80, 80 }, "tcp"); - assertTrue("DestinationNatRule".equals(rules[0].getType())); - assertTrue("SourceNatRule".equals(rules[1].getType())); - - final DestinationNatRule dnr = (DestinationNatRule) rules[0]; - assertTrue(dnr.getToDestinationIpAddress().equals("10.10.10.10")); - assertTrue(dnr.getToDestinationPort() == 8080); - assertTrue(dnr.getMatch().getDestinationIpAddresses().equals("11.11.11.11")); - assertTrue(dnr.getMatch().getDestinationPort() == 80); - assertTrue(dnr.getMatch().getEthertype().equals("IPv4") && dnr.getMatch().getProtocol() == 6); - - final SourceNatRule snr = (SourceNatRule) rules[1]; - assertTrue(snr.getToSourceIpAddressMin().equals("11.11.11.11") && snr.getToSourceIpAddressMax().equals("11.11.11.11")); - assertTrue(snr.getToSourcePort() == 80); - assertTrue(snr.getMatch().getSourceIpAddresses().equals("10.10.10.10")); - assertTrue(snr.getMatch().getSourcePort() == 8080); - assertTrue(snr.getMatch().getEthertype().equals("IPv4") && rules[1].getMatch().getProtocol() == 6); - } -} diff --git a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapperTest.java b/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapperTest.java deleted file mode 100644 index b0a988270a5f..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/java/com/cloud/network/resource/wrapper/NiciraCheckHealthCommandWrapperTest.java +++ /dev/null @@ -1,80 +0,0 @@ -// -// 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.network.resource.wrapper; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CheckHealthCommand; -import com.cloud.network.nicira.ControlClusterStatus; -import com.cloud.network.nicira.NiciraNvpApi; -import com.cloud.network.nicira.NiciraNvpApiException; -import com.cloud.network.resource.NiciraNvpResource; - -public class NiciraCheckHealthCommandWrapperTest { - - private final NiciraNvpResource niciraResource = mock(NiciraNvpResource.class); - private final NiciraNvpApi niciraApi = mock(NiciraNvpApi.class); - - @Before - public void setup() { - when(niciraResource.getNiciraNvpApi()).thenReturn(niciraApi); - } - - @Test - public void tetsExecuteWhenClusterIsNotStable() throws Exception { - when(niciraApi.getControlClusterStatus()).thenReturn(new ControlClusterStatus()); - - final NiciraCheckHealthCommandWrapper commandWrapper = new NiciraCheckHealthCommandWrapper(); - final Answer answer = commandWrapper.execute(new CheckHealthCommand(), niciraResource); - - assertThat(answer.getResult(), equalTo(false)); - } - - @SuppressWarnings("unchecked") - @Test - public void tetsExecuteWhenApiThrowsException() throws Exception { - when(niciraApi.getControlClusterStatus()).thenThrow(NiciraNvpApiException.class); - - final NiciraCheckHealthCommandWrapper commandWrapper = new NiciraCheckHealthCommandWrapper(); - final Answer answer = commandWrapper.execute(new CheckHealthCommand(), niciraResource); - - assertThat(answer.getResult(), equalTo(false)); - } - - @Test - public void tetsExecuteWhenClusterIsStable() throws Exception { - final ControlClusterStatus statusValue = mock(ControlClusterStatus.class); - when(statusValue.getClusterStatus()).thenReturn("stable"); - when(niciraApi.getControlClusterStatus()).thenReturn(statusValue); - - final NiciraCheckHealthCommandWrapper commandWrapper = new NiciraCheckHealthCommandWrapper(); - final Answer answer = commandWrapper.execute(new CheckHealthCommand(), niciraResource); - - assertThat(answer.getResult(), equalTo(true)); - } - -} diff --git a/plugins/network-elements/nicira-nvp/src/test/resources/config.properties b/plugins/network-elements/nicira-nvp/src/test/resources/config.properties deleted file mode 100644 index 04cf76b805eb..000000000000 --- a/plugins/network-elements/nicira-nvp/src/test/resources/config.properties +++ /dev/null @@ -1,22 +0,0 @@ -# -# 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. -# - -nvp.host=localhost -nvp.admin.user=admin -nvp.admin.pwd=adminpassword diff --git a/plugins/network-elements/stratosphere-ssp/pom.xml b/plugins/network-elements/stratosphere-ssp/pom.xml deleted file mode 100644 index 0288c8a5dd79..000000000000 --- a/plugins/network-elements/stratosphere-ssp/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - 4.0.0 - cloud-plugin-network-ssp - Apache CloudStack Plugin - Stratosphere SSP - http://www.stratosphere.co.jp/ - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/AddSspCmd.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/AddSspCmd.java deleted file mode 100644 index 1e26fc1d18d8..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/AddSspCmd.java +++ /dev/null @@ -1,136 +0,0 @@ -// 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 org.apache.cloudstack.api.commands; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.SspResponse; -import org.apache.cloudstack.api.response.ZoneResponse; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.network.element.SspService; - -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; - -@APICommand(name = "addStratosphereSsp", responseObject = SspResponse.class, description = "Adds stratosphere ssp server", - requestHasSensitiveInfo = true, responseHasSensitiveInfo = false) -public class AddSspCmd extends BaseCmd { - @Inject - SspService _service; - @Inject - DataCenterDao _dcDao; - - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "The zone ID") - private Long zoneId; - - @Parameter(name = ApiConstants.URL, type = CommandType.STRING, required = true, description = "Stratosphere ssp server URL") - private String url; - - @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = false, description = "Stratosphere ssp API username") - private String username; - - @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = false, description = "Stratosphere ssp API password") - private String password; - - @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Stratosphere ssp API name") - private String name; // required because HostVO name field defined as NOT NULL. - - @Parameter(name = "tenantuuid", type = CommandType.STRING, required = false, description = "Stratosphere ssp tenant UUID") - private String tenantUuid; // required in creating ssp tenant_network - - @Override - public String getCommandName() { - return getClass().getAnnotation(APICommand.class).name(); - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException, - NetworkRuleConflictException { - logger.trace("execute"); - Host host = _service.addSspHost(this); - SspResponse response = new SspResponse(); - response.setResponseName(getCommandName()); - response.setObjectName("ssphost"); - response.setUrl(this.getUrl()); - response.setZoneId(_dcDao.findById(getZoneId()).getUuid()); - response.setHostId(host.getUuid()); - this.setResponseObject(response); - } - - public Long getZoneId() { - return zoneId; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTenantUuid() { - return tenantUuid; - } - - public void setTenantUuid(String tenantUuid) { - this.tenantUuid = tenantUuid; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/DeleteSspCmd.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/DeleteSspCmd.java deleted file mode 100644 index b567a2cacb5c..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/commands/DeleteSspCmd.java +++ /dev/null @@ -1,72 +0,0 @@ -// 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 org.apache.cloudstack.api.commands; - -import javax.inject.Inject; - - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.HostResponse; -import org.apache.cloudstack.api.response.SuccessResponse; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.network.element.SspService; - -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; - -@APICommand(name = "deleteStratosphereSsp", responseObject = SuccessResponse.class, description = "Removes stratosphere ssp server", - requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class DeleteSspCmd extends BaseCmd { - @Inject - SspService _service; - - @Parameter(name = ApiConstants.HOST_ID, type = CommandType.UUID, entityType = HostResponse.class, required = true, description = "The host ID of ssp server") - private Long hostId; - - @Override - public String getCommandName() { - return getClass().getAnnotation(APICommand.class).name(); - } - - @Override - public long getEntityOwnerId() { - return CallContext.current().getCallingAccount().getId(); - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException, - NetworkRuleConflictException { - logger.trace("execute"); - SuccessResponse resp = new SuccessResponse(); - resp.setSuccess(_service.deleteSspHost(this)); - this.setResponseObject(resp); - } - - public Long getHostId() { - return hostId; - } - - public void setHostId(Long hostId) { - this.hostId = hostId; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/response/SspResponse.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/response/SspResponse.java deleted file mode 100644 index 338f7ee112dc..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/api/response/SspResponse.java +++ /dev/null @@ -1,77 +0,0 @@ -// 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 org.apache.cloudstack.api.response; - -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; -import org.apache.cloudstack.api.EntityReference; - -import com.cloud.host.HostVO; -import com.cloud.serializer.Param; - -@EntityReference(value = HostVO.class) -public class SspResponse extends BaseResponse { - @SerializedName(ApiConstants.HOST_ID) - @Param(description = "Server ID of the stratosphere ssp server") - private String hostId; - - @SerializedName(ApiConstants.ZONE_ID) - @Param(description = "Zone which this ssp controls") - private String zoneId; - - @SerializedName(ApiConstants.URL) - @Param(description = "URL of ssp endpoint") - private String url; - - @SerializedName(ApiConstants.NAME) - @Param(description = "Name") - private String name; - - public String getHostId() { - return hostId; - } - - public void setHostId(String hostId) { - this.hostId = hostId; - } - - public String getZoneId() { - return zoneId; - } - - public void setZoneId(String zoneId) { - this.zoneId = zoneId; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDao.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDao.java deleted file mode 100644 index 4927da1c9d97..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDao.java +++ /dev/null @@ -1,33 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import com.cloud.utils.db.GenericDao; - -public interface SspCredentialDao extends GenericDao { - /** - * Find an ssp credential for a specific cloudstack zone. - * - * For now, credential is a pair of username and password. - * We might want to fetch different pairs for each cloudstack users - * in future work. - * - * @param zoneId zone Id - * @return credential object - */ - public SspCredentialVO findByZone(long zoneId); -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDaoImpl.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDaoImpl.java deleted file mode 100644 index aea77166f929..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialDaoImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - - -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -public class SspCredentialDaoImpl extends GenericDaoBase implements SspCredentialDao { - private final SearchBuilder PnetSearch; - - public SspCredentialDaoImpl() { - PnetSearch = createSearchBuilder(); - PnetSearch.and("dataCenterId", PnetSearch.entity().getZoneId(), Op.EQ); - PnetSearch.done(); - } - - @Override - public SspCredentialVO findByZone(long zoneId) { - SearchCriteria sc = PnetSearch.create(); - sc.setParameters("dataCenterId", zoneId); - return findOneBy(sc); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialVO.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialVO.java deleted file mode 100644 index 92836f5af671..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspCredentialVO.java +++ /dev/null @@ -1,70 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -import com.cloud.utils.db.Encrypt; - -@Entity -@Table(name = "external_stratosphere_ssp_credentials") -public class SspCredentialVO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "data_center_id") - private long zoneId; // Actually, this is zoneId - - // XXX: We might want to restrict access to this by cloudstack privileges. - @Column(name = "username") - private String username; - - @Encrypt - @Column(name = "password") - private String password; - - public long getZoneId() { - return zoneId; - } - - public void setZoneId(long zoneId) { - this.zoneId = zoneId; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDao.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDao.java deleted file mode 100644 index 7bccdaa309a9..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDao.java +++ /dev/null @@ -1,34 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import com.cloud.utils.db.GenericDao; - -public interface SspTenantDao extends GenericDao { - /** - * Find an ssp tenant uuid for a specific cloudstack zone. - * - * The ssp tenant uuid will be used in ssp tenant_network creation. - * For now, we map ssp tenant to cloudstack zone. Instead, we might - * want to map ssp tenant to cloudstack domain, or ssp tenant to - * cloudstack project in future. - * - * @param zoneId zone id - * @return tenant uuid string - */ - public String findUuidByZone(long zoneId); -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDaoImpl.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDaoImpl.java deleted file mode 100644 index b90cf13485d1..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantDaoImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - - -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; - -public class SspTenantDaoImpl extends GenericDaoBase implements SspTenantDao { - - private final SearchBuilder zoneSearch; - - public SspTenantDaoImpl() { - zoneSearch = createSearchBuilder(); - zoneSearch.and("zoneId", zoneSearch.entity().getZoneId(), Op.EQ); - zoneSearch.done(); - } - - @Override - public String findUuidByZone(long zoneId) { - SearchCriteria sc = zoneSearch.create(); - sc.setParameters("zoneId", zoneId); - SspTenantVO ret = findOneBy(sc); - if (ret != null) { - return ret.getUuid(); - } - return null; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantVO.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantVO.java deleted file mode 100644 index 51bb6859ef0d..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspTenantVO.java +++ /dev/null @@ -1,55 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "external_stratosphere_ssp_tenants") -public class SspTenantVO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "zone_id") - private long zoneId; - - @Column(name = "uuid") - private String uuid; - - public long getZoneId() { - return zoneId; - } - - public void setZoneId(long zoneId) { - this.zoneId = zoneId; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDao.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDao.java deleted file mode 100644 index 63c947a9a931..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDao.java +++ /dev/null @@ -1,40 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import java.util.List; - -import com.cloud.network.Network; -import com.cloud.utils.db.GenericDao; -import com.cloud.vm.NicProfile; - -/** - * Mapping for SSP UUID and cloudstack entities - */ -public interface SspUuidDao extends GenericDao { - public String findUuidByNetwork(Network network); - - public String findUuidByNicProfile(NicProfile nicProfile); - - public Long findNetworkIdByUuid(String uuid); - - public Long findNicProfileIdByUuid(String uuid); - - public int removeUuid(String uuid); - - public List listUUidVoByNicProfile(NicProfile nicProfile); -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDaoImpl.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDaoImpl.java deleted file mode 100644 index dccc1d7ffa90..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidDaoImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import java.util.List; - - - -import com.cloud.network.Network; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.vm.NicProfile; - -public class SspUuidDaoImpl extends GenericDaoBase implements SspUuidDao { - - - protected final SearchBuilder native2uuid; - protected final SearchBuilder uuid2native; - protected final SearchBuilder uuidfetch; - - public SspUuidDaoImpl() { - native2uuid = createSearchBuilder(); - native2uuid.and("obj_class", native2uuid.entity().getObjClass(), Op.EQ); - native2uuid.and("obj_id", native2uuid.entity().getObjId(), Op.EQ); - native2uuid.done(); - - uuid2native = createSearchBuilder(); - uuid2native.and("obj_class", uuid2native.entity().getObjClass(), Op.EQ); - uuid2native.and("uuid", uuid2native.entity().getUuid(), Op.EQ); - uuid2native.done(); - - uuidfetch = createSearchBuilder(); - uuidfetch.and("uuid", uuidfetch.entity().getUuid(), Op.EQ); - uuidfetch.done(); - } - - @Override - public String findUuidByNetwork(Network network) { - SearchCriteria cs = native2uuid.create(); - cs.setParameters("obj_class", SspUuidVO.objClassNetwork); - cs.setParameters("obj_id", network.getId()); - SspUuidVO vo = findOneBy(cs); - if (vo != null) { - return vo.getUuid(); - } - return null; - } - - @Override - public String findUuidByNicProfile(NicProfile nicProfile) { - SearchCriteria cs = native2uuid.create(); - cs.setParameters("obj_class", SspUuidVO.objClassNicProfile); - cs.setParameters("obj_id", nicProfile.getId()); - SspUuidVO vo = findOneBy(cs); - if (vo != null) { - return vo.getUuid(); - } - return null; - } - - @Override - public List listUUidVoByNicProfile(NicProfile nicProfile) { - SearchCriteria cs = native2uuid.create(); - cs.setParameters("obj_class", SspUuidVO.objClassNicProfile); - cs.setParameters("obj_id", nicProfile.getId()); - return listBy(cs); - } - - @Override - public Long findNetworkIdByUuid(String uuid) { - return findByUuid(SspUuidVO.objClassNetwork, uuid); - } - - @Override - public Long findNicProfileIdByUuid(String uuid) { - return findByUuid(SspUuidVO.objClassNicProfile, uuid); - } - - private Long findByUuid(String clazz, String uuid) { - SearchCriteria cs = uuid2native.create(); - cs.setParameters("obj_class", clazz); - cs.setParameters("uuid", uuid); - SspUuidVO vo = findOneBy(cs); - if (vo != null) { - return vo.getObjId(); - } - return null; - } - - @Override - public int removeUuid(String uuid) { - SearchCriteria cs = uuidfetch.create(); - cs.setParameters("uuid", uuid); - return this.remove(cs); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidVO.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidVO.java deleted file mode 100644 index b81ae58a1ed2..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/dao/SspUuidVO.java +++ /dev/null @@ -1,80 +0,0 @@ -// 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 org.apache.cloudstack.network.dao; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "external_stratosphere_ssp_uuids") -public class SspUuidVO { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "uuid") - private String uuid; - - @Column(name = "obj_class") - private String objClass; - - @Column(name = "obj_id") - private long objId; - - static public final String objClassNetwork = "net"; - static public final String objClassNicProfile = "nic"; - - @Column(name = "reservation_id") - private String reservationId; - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getObjClass() { - return objClass; - } - - public void setObjClass(String objClass) { - this.objClass = objClass; - } - - public long getObjId() { - return objId; - } - - public void setObjId(long objId) { - this.objId = objId; - } - - public String getReservationId() { - return reservationId; - } - - public void setReservationId(String reservationId) { - this.reservationId = reservationId; - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspClient.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspClient.java deleted file mode 100644 index c60813badf62..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspClient.java +++ /dev/null @@ -1,199 +0,0 @@ -// 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 org.apache.cloudstack.network.element; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; - -import org.apache.http.HttpStatus; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.HttpClient; -import org.apache.http.client.HttpResponseException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicResponseHandler; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.google.gson.Gson; -import com.google.gson.annotations.SerializedName; - -/** - * Stratosphere sdn platform api client - */ -public class SspClient { - protected Logger logger = LogManager.getLogger(getClass()); - private static final HttpClient s_client = new DefaultHttpClient( - new PoolingClientConnectionManager()); - static { - s_client.getParams() - .setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY) - .setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); - } - - private final String apiUrl; - private final String username; - private final String password; - - public SspClient(String apiUrl, String username, String password) { - super(); - this.apiUrl = apiUrl; - this.username = username; - this.password = password; - } - - protected HttpClient getHttpClient() { // for mock test - return s_client; - } - - private String executeMethod(HttpRequestBase req, String path) { - try { - URI base = new URI(apiUrl); - req.setURI(new URI(base.getScheme(), base.getUserInfo(), base.getHost(), - base.getPort(), path, null, null)); - } catch (URISyntaxException e) { - logger.error("invalid API URL " + apiUrl + " path " + path, e); - return null; - } - try { - String content = null; - try { - content = getHttpClient().execute(req, new BasicResponseHandler()); - logger.info("ssp api call: " + req); - } catch (HttpResponseException e) { - logger.info("ssp api call failed: " + req, e); - if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED && login()) { - req.reset(); - content = getHttpClient().execute(req, new BasicResponseHandler()); - logger.info("ssp api retry call: " + req); - } - } - return content; - } catch (ClientProtocolException e) { // includes HttpResponseException - logger.error("ssp api call failed: " + req, e); - } catch (IOException e) { - logger.error("ssp api call failed: " + req, e); - } - return null; - } - - public boolean login() { - HttpPost method = new HttpPost(); - try { - method.setEntity(new UrlEncodedFormEntity(Arrays.asList( - new BasicNameValuePair("username", username), - new BasicNameValuePair("password", password)))); - } catch (UnsupportedEncodingException e) { - logger.error("invalid username or password", e); - return false; - } - if (executeMethod(method, "/ws.v1/login") != null) { - return true; - } - return false; - } - - public class TenantNetwork { - public String uuid; - public String name; - @SerializedName("tenant_uuid") - public String tenantUuid; - } - - public TenantNetwork createTenantNetwork(String tenantUuid, String networkName) { - TenantNetwork req = new TenantNetwork(); - req.name = networkName; - req.tenantUuid = tenantUuid; - - HttpPost method = new HttpPost(); - method.setEntity(new StringEntity(new Gson().toJson(req), ContentType.APPLICATION_JSON)); - return new Gson().fromJson( - executeMethod(method, "/ssp.v1/tenant-networks"), - TenantNetwork.class); - } - - public boolean deleteTenantNetwork(String tenantNetworkUuid) { - HttpDelete method = new HttpDelete(); - if (executeMethod(method, "/ssp.v1/tenant-networks/" + tenantNetworkUuid) != null) { - return true; - } - return false; - } - - public class TenantPort { - public String uuid; - public String name; - @SerializedName("network_uuid") - public String networkUuid; - @SerializedName("attachment_type") - public String attachmentType; - @SerializedName("attachment_ip_address") - public String hypervisorIpAddress; - @SerializedName("vlan_id") - public Integer vlanId; - } - - public TenantPort createTenantPort(String tenantNetworkUuid) { - TenantPort req = new TenantPort(); - req.networkUuid = tenantNetworkUuid; - req.attachmentType = "NoAttachment"; - - HttpPost method = new HttpPost(); - method.setEntity(new StringEntity(new Gson().toJson(req), ContentType.APPLICATION_JSON)); - return new Gson().fromJson( - executeMethod(method, "/ssp.v1/tenant-ports"), - TenantPort.class); - } - - public boolean deleteTenantPort(String tenantPortUuid) { - HttpDelete method = new HttpDelete(); - if (executeMethod(method, "/ssp.v1/tenant-ports/" + tenantPortUuid) != null) { - return true; - } - return false; - } - - public TenantPort updateTenantVifBinding(String portUuid, String hypervisorIpAddress) { - TenantPort req = new TenantPort(); - if (hypervisorIpAddress != null) { - req.attachmentType = "VifAttachment"; - req.hypervisorIpAddress = hypervisorIpAddress; - } else { - req.attachmentType = "NoAttachment"; - } - - HttpPut method = new HttpPut(); - method.setEntity(new StringEntity(new Gson().toJson(req), ContentType.APPLICATION_JSON)); - return new Gson().fromJson( - executeMethod(method, "/ssp.v1/tenant-ports/" + portUuid), - TenantPort.class); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspElement.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspElement.java deleted file mode 100644 index bfe9de2c837f..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspElement.java +++ /dev/null @@ -1,588 +0,0 @@ -// 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 org.apache.cloudstack.network.element; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - - -import org.apache.cloudstack.api.commands.AddSspCmd; -import org.apache.cloudstack.api.commands.DeleteSspCmd; -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.network.dao.SspCredentialDao; -import org.apache.cloudstack.network.dao.SspCredentialVO; -import org.apache.cloudstack.network.dao.SspTenantDao; -import org.apache.cloudstack.network.dao.SspTenantVO; -import org.apache.cloudstack.network.dao.SspUuidDao; -import org.apache.cloudstack.network.dao.SspUuidVO; - -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkMigrationResponder; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.BroadcastDomainType; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PhysicalNetworkServiceProvider.State; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.element.ConnectivityProvider; -import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ResourceManager; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.NicProfile; -import com.cloud.vm.NicVO; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.NicDao; - -/** - * Stratosphere sdn platform network element - * - * This class will be called per network setup operations. - * This class also have ssp specific methods. - * - * Current implementation use HostVO for storage of api endpoint information, - * but note this is not necessary. The other way is create our own database - * table for that information. - */ -public class SspElement extends AdapterBase implements ConnectivityProvider, SspManager, SspService, NetworkMigrationResponder { - public static final String s_SSP_NAME = "StratosphereSsp"; - private static final Provider s_ssp_provider = new Provider(s_SSP_NAME, false); - - @Inject - NetworkServiceMapDao _ntwkSrvcDao; - @Inject - NetworkModel _networkModel; - @Inject - NetworkOrchestrationService _networkMgr; - @Inject - ResourceManager _resourceMgr; - @Inject - PhysicalNetworkDao _physicalNetworkDao; - @Inject - PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; - @Inject - SspCredentialDao _sspCredentialDao; - @Inject - SspTenantDao _sspTenantDao; - @Inject - SspUuidDao _sspUuidDao; - @Inject - DataCenterDao _dcDao; - @Inject - HostDao _hostDao; - @Inject - ConfigurationDao _configDao; - @Inject - NicDao _nicDao = null; - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - return super.configure(name, params); - } - - @Override - public Map> getCapabilities() { - Map> capabilities = new HashMap>(); - capabilities.put(Service.Connectivity, new HashMap()); // XXX: We might need some more category here. - return capabilities; - } - - @Override - public Provider getProvider() { - return s_ssp_provider; - } - - private List fetchSspClients(Long physicalNetworkId, Long dataCenterId, boolean enabledOnly) { - ArrayList clients = new ArrayList(); - - boolean provider_found = false; - PhysicalNetworkServiceProviderVO provider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetworkId, s_SSP_NAME); - if (enabledOnly) { - if (provider != null && provider.getState() == State.Enabled) { - provider_found = true; - } - } else { - provider_found = true; - } - - if (physicalNetworkId != null && provider_found) { - SspCredentialVO credential = _sspCredentialDao.findByZone(dataCenterId); - List hosts = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.L2Networking, dataCenterId); - for (HostVO host : hosts) { - assert (credential != null); - _hostDao.loadDetails(host); - if ("v1Api".equals(host.getDetail("sspHost"))) { - clients.add(new SspClient(host.getDetail("url"), credential.getUsername(), credential.getPassword())); - } - } - } - if (clients.size() == 0) { - String global_apiUrl = _configDao.getValueAndInitIfNotExist("ssp.url", "Network", null); - String global_username = _configDao.getValueAndInitIfNotExist("ssp.username", "Network", null); - String global_password = _configDao.getValueAndInitIfNotExist("ssp.password", "Network", null); - if (global_apiUrl != null && global_username != null && global_password != null) { - clients.add(new SspClient(global_apiUrl, global_username, global_password)); - } - } - return clients; - } - - /* (non-Javadoc) - * @see org.apache.cloudstack.network.element.NetworkElement#isReady(com.cloud.network.PhysicalNetworkServiceProvider) - */ - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(provider.getPhysicalNetworkId()); - assert (physicalNetwork != null); - if (fetchSspClients(physicalNetwork.getId(), physicalNetwork.getDataCenterId(), false).size() > 0) { - return true; - } - logger.warn("Ssp api endpoint not found. " + physicalNetwork.toString()); - return false; - } - - /* (non-Javadoc) - * If this element is ready, then it can be enabled. - * @see org.apache.cloudstack.network.element.SspManager#isEnabled(com.cloud.network.PhysicalNetwork) - */ - @Override - public boolean canHandle(PhysicalNetwork physicalNetwork) { - if (physicalNetwork != null) { - if (fetchSspClients(physicalNetwork.getId(), physicalNetwork.getDataCenterId(), true).size() > 0) { - return true; - } - logger.warn("enabled Ssp api endpoint not found. " + physicalNetwork.toString()); - } else { - logger.warn("PhysicalNetwork is NULL."); - } - return false; - } - - private boolean canHandle(Network network) { - if (canHandle(_physicalNetworkDao.findById(network.getPhysicalNetworkId()))) { - if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), Service.Connectivity, getProvider())) { - logger.info("SSP is implicitly active for " + network); - } - return true; - } - return false; - } - - @Override - public Host addSspHost(AddSspCmd cmd) { - SspClient client = new SspClient(cmd.getUrl(), cmd.getUsername(), cmd.getPassword()); - if (!client.login()) { - throw new CloudRuntimeException("Ssp login failed."); - } - - long zoneId = cmd.getZoneId(); - SspCredentialVO credential = _sspCredentialDao.findByZone(zoneId); - if (credential == null) { - if (cmd.getUsername() == null || cmd.getPassword() == null) { - throw new InvalidParameterValueException("Initial credential required for zone: " + zoneId); - } - credential = new SspCredentialVO(); - credential.setZoneId(zoneId); - credential.setUsername(cmd.getUsername()); - credential.setPassword(cmd.getPassword()); - _sspCredentialDao.persist(credential); - } else { - if (cmd.getUsername() != null || cmd.getPassword() != null) { - logger.warn("Tenant credential already configured for zone:" + zoneId); - } - } - - String tenantUuid = _sspTenantDao.findUuidByZone(zoneId); - if (tenantUuid == null) { - if (cmd.getTenantUuid() == null) { - throw new InvalidParameterValueException("Initial tenant uuid required for zone: " + zoneId); - } - SspTenantVO tenant = new SspTenantVO(); - tenant.setZoneId(zoneId); - tenant.setUuid(cmd.getTenantUuid()); - _sspTenantDao.persist(tenant); - } else { - if (cmd.getTenantUuid() != null) { - logger.warn("Tenant uuid already configured for zone:" + zoneId); - } - } - - String normalizedUrl = null; - String hostname = null; - try { - URL url = new URL(cmd.getUrl()); - normalizedUrl = url.toString(); - hostname = url.getHost(); - } catch (MalformedURLException e1) { - throw new CloudRuntimeException("Invalid url " + cmd.getUrl()); - } - - List hosts = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.L2Networking, zoneId); - for (HostVO host : hosts) { - assert (credential != null); - _hostDao.loadDetails(host); - if ("v1Api".equals(host.getDetail("sspHost"))) { - if (normalizedUrl.equals(host.getDetail("url"))) { - logger.warn("Ssp host already registered " + normalizedUrl); - return host; - } - } - } - // SspHost HostVO will be created per zone and url. - HostVO host = new HostVO(UUID.randomUUID().toString()); - host.setDataCenterId(zoneId); - host.setType(Host.Type.L2Networking); - host.setPrivateIpAddress(hostname); // db schema not null. It may be a name, not IP address. - // host.setPrivateMacAddress(""); // db schema nullable - // host.setPrivateNetmask(""); // db schema nullable - host.setVersion("1"); // strange db schema not null - host.setName(cmd.getName()); - - host.setDetails(new HashMap()); - host.setDetail("sspHost", "v1Api"); - host.setDetail("url", normalizedUrl); - return _hostDao.persist(host); - } - - @Override - public boolean deleteSspHost(DeleteSspCmd cmd) { - logger.info("deleteStratosphereSsp"); - return _hostDao.remove(cmd.getHostId()); - } - - @Override - public boolean createNetwork(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) { - if (_sspUuidDao.findUuidByNetwork(network) != null) { - logger.info("Network already has ssp TenantNetwork uuid :" + network.toString()); - return true; - } - if (!canHandle(network)) { - return false; - } - - String tenantUuid = _sspTenantDao.findUuidByZone(network.getDataCenterId()); - if (tenantUuid == null) { - tenantUuid = _configDao.getValueAndInitIfNotExist("ssp.tenant", "Network", null); - } - - boolean processed = false; - for (SspClient client : fetchSspClients(network.getPhysicalNetworkId(), network.getDataCenterId(), true)) { - SspClient.TenantNetwork sspNet = client.createTenantNetwork(tenantUuid, network.getName()); - if (sspNet != null) { - SspUuidVO uuid = new SspUuidVO(); - uuid.setUuid(sspNet.uuid); - uuid.setObjClass(SspUuidVO.objClassNetwork); - uuid.setObjId(network.getId()); - _sspUuidDao.persist(uuid); - return true; - } - processed = true; - } - if (processed) { - logger.error("Could not allocate an uuid for network " + network.toString()); - return false; - } else { - logger.error("Skipping #createNetwork() for " + network.toString()); - return true; - } - } - - @Override - public boolean deleteNetwork(Network network) { - String tenantNetworkUuid = _sspUuidDao.findUuidByNetwork(network); - if (tenantNetworkUuid != null) { - boolean processed = false; - for (SspClient client : fetchSspClients(network.getPhysicalNetworkId(), network.getDataCenterId(), true)) { - if (client.deleteTenantNetwork(tenantNetworkUuid)) { - _sspUuidDao.removeUuid(tenantNetworkUuid); - processed = true; - break; - } - } - if (!processed) { - logger.error("Ssp api tenant network deletion failed " + network.toString()); - } - } else { - logger.debug("Silently skipping #deleteNetwork() for " + network.toString()); - } - return true; - } - - // we use context.reservationId for dedup of guru & element operations. - @Override - public boolean createNicEnv(Network network, NicProfile nic, DeployDestination dest, ReservationContext context) { - String tenantNetworkUuid = _sspUuidDao.findUuidByNetwork(network); - if (tenantNetworkUuid == null) { - logger.debug("Skipping #createNicEnv() for nic on " + network.toString()); - return true; - } - - String reservationId = context.getReservationId(); - List tenantPortUuidVos = _sspUuidDao.listUUidVoByNicProfile(nic); - for (SspUuidVO tenantPortUuidVo : tenantPortUuidVos) { - if (reservationId.equals(tenantPortUuidVo.getReservationId())) { - logger.info("Skipping because reservation found " + reservationId); - return true; - } - } - - String tenantPortUuid = null; - for (SspClient client : fetchSspClients(network.getPhysicalNetworkId(), network.getDataCenterId(), true)) { - SspClient.TenantPort sspPort = client.createTenantPort(tenantNetworkUuid); - if (sspPort != null) { - tenantPortUuid = sspPort.uuid; - nic.setReservationId(reservationId); - - SspUuidVO uuid = new SspUuidVO(); - uuid.setUuid(tenantPortUuid); - uuid.setObjClass(SspUuidVO.objClassNicProfile); - uuid.setObjId(nic.getId()); - uuid.setReservationId(reservationId); - _sspUuidDao.persist(uuid); - break; - } - } - if (tenantPortUuid == null) { - logger.debug("#createNicEnv() failed for nic on " + network.toString()); - return false; - } - - for (SspClient client : fetchSspClients(network.getPhysicalNetworkId(), network.getDataCenterId(), true)) { - SspClient.TenantPort sspPort = client.updateTenantVifBinding(tenantPortUuid, dest.getHost().getPrivateIpAddress()); - if (sspPort != null) { - if (sspPort.vlanId != null) { - nic.setBroadcastType(BroadcastDomainType.Vlan); - nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(String.valueOf(sspPort.vlanId))); - } - return true; - } - } - logger.error("Updating vif failed " + nic.toString()); - return false; - } - - @Override - public boolean deleteNicEnv(Network network, NicProfile nic, ReservationContext context) { - if (context == null) { - logger.error("ReservationContext was null for " + nic + " " + network); - return false; - } - String reservationId = context.getReservationId(); - - SspUuidVO deleteTarget = null; - SspUuidVO remainingTarget = null; - List tenantPortUuidVos = _sspUuidDao.listUUidVoByNicProfile(nic); - for (SspUuidVO tenantPortUuidVo : tenantPortUuidVos) { - if (reservationId.equals(tenantPortUuidVo.getReservationId())) { - deleteTarget = tenantPortUuidVo; - } else { - remainingTarget = tenantPortUuidVo; - } - } - - if (deleteTarget != null) { // delete the target ssp uuid (tenant-port) - String tenantPortUuid = deleteTarget.getUuid(); - boolean processed = false; - for (SspClient client : fetchSspClients(network.getPhysicalNetworkId(), network.getDataCenterId(), true)) { - SspClient.TenantPort sspPort = client.updateTenantVifBinding(tenantPortUuid, null); - if (sspPort != null) { - processed = true; - break; - } - } - if (!processed) { - logger.warn("Ssp api nic detach failed " + nic.toString()); - } - processed = false; - for (SspClient client : fetchSspClients(network.getPhysicalNetworkId(), network.getDataCenterId(), true)) { - if (client.deleteTenantPort(tenantPortUuid)) { - _sspUuidDao.removeUuid(tenantPortUuid); - processed = true; - break; - } - } - if (!processed) { - logger.warn("Ssp api tenant port deletion failed " + nic.toString()); - } - _sspUuidDao.removeUuid(tenantPortUuid); - } - if (remainingTarget != null) { - NicVO nicVo = _nicDao.findById(nic.getId()); - nicVo.setReservationId(remainingTarget.getReservationId()); - _nicDao.persist(nicVo); // persist the new reservationId - } - return true; - } - - /* (non-Javadoc) - * Implements a network using ssp element. - * - * This method will be called right after NetworkGuru#implement(). - * see also {@link #shutdown(Network, ReservationContext, boolean)} - * @see org.apache.cloudstack.network.element.NetworkElement#implement(com.cloud.network.Network, com.cloud.offering.NetworkOffering, com.cloud.deploy.DeployDestination, com.cloud.vm.ReservationContext) - */ - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - logger.info("implement"); - return createNetwork(network, offering, dest, context); - } - - /* (non-Javadoc) - * Shutdown the network implementation - * - * This method will be called right BEFORE NetworkGuru#shutdown(). - * The entities was acquired by {@link #implement(Network, NetworkOffering, DeployDestination, ReservationContext)} - * @see org.apache.cloudstack.network.element.NetworkElement#shutdown(com.cloud.network.Network, com.cloud.vm.ReservationContext, boolean) - */ - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - logger.trace("shutdown"); - return deleteNetwork(network); - } - - /* (non-Javadoc) - * Prepares a network environment for a VM nic. - * - * This method will be called right after NetworkGuru#reserve(). - * The entities will be released by {@link #release(Network, NicProfile, VirtualMachineProfile, ReservationContext)} - * @see org.apache.cloudstack.network.element.NetworkElement#prepare(com.cloud.network.Network, com.cloud.vm.NicProfile, com.cloud.vm.VirtualMachineProfile, com.cloud.deploy.DeployDestination, com.cloud.vm.ReservationContext) - */ - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - logger.trace("prepare"); - return createNicEnv(network, nic, dest, context); - } - - /* (non-Javadoc) - * Release the network environment that was prepared for a VM nic. - * - * This method will be called right AFTER NetworkGuru#release(). - * The entities was acquired in {@link #prepare(Network, NicProfile, VirtualMachineProfile, DeployDestination, ReservationContext)} - * @see org.apache.cloudstack.network.element.NetworkElement#release(com.cloud.network.Network, com.cloud.vm.NicProfile, com.cloud.vm.VirtualMachineProfile, com.cloud.vm.ReservationContext) - */ - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - logger.trace("release"); - return deleteNicEnv(network, nic, context); - } - - /* (non-Javadoc) - * Destroy a network implementation. - * - * This method will be called right BEFORE NetworkGuru#trash() in "Expunge" phase. - * @see org.apache.cloudstack.network.element.NetworkElement#destroy(com.cloud.network.Network) - */ - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - logger.trace("destroy"); - // nothing to do here. - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - logger.trace("shutdownProviderInstances"); - return true; - } - - @Override - public boolean canEnableIndividualServices() { - logger.trace("canEnableIndividualServices"); - return true; // because there is only Connectivity - } - - @Override - public boolean verifyServicesCombination(Set services) { - logger.trace("verifyServicesCombination " + services.toString()); - return true; - } - - @Override - public boolean prepareMigration(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) { - try { - prepare(network, nic, vm, dest, context); - } catch (ConcurrentOperationException e) { - logger.error("prepareForMigration failed.", e); - return false; - } catch (ResourceUnavailableException e) { - logger.error("prepareForMigration failed.", e); - return false; - } catch (InsufficientCapacityException e) { - logger.error("prepareForMigration failed.", e); - return false; - } - return true; - } - - @Override - public void rollbackMigration(NicProfile nic, Network network, VirtualMachineProfile vm, ReservationContext src, ReservationContext dst) { - try { - release(network, nic, vm, dst); - } catch (ConcurrentOperationException e) { - logger.error("rollbackMigration failed.", e); - } catch (ResourceUnavailableException e) { - logger.error("rollbackMigration failed.", e); - } - } - - @Override - public void commitMigration(NicProfile nic, Network network, VirtualMachineProfile vm, ReservationContext src, ReservationContext dst) { - try { - release(network, nic, vm, src); - } catch (ConcurrentOperationException e) { - logger.error("commitMigration failed.", e); - } catch (ResourceUnavailableException e) { - logger.error("commitMigration failed.", e); - } - } - - @Override - public List> getCommands() { - return Arrays.> asList(AddSspCmd.class, DeleteSspCmd.class); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspManager.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspManager.java deleted file mode 100644 index 4bcaff238bd4..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspManager.java +++ /dev/null @@ -1,70 +0,0 @@ -// 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 org.apache.cloudstack.network.element; - -import com.cloud.deploy.DeployDestination; -import com.cloud.network.Network; -import com.cloud.network.PhysicalNetwork; -import com.cloud.offering.NetworkOffering; -import com.cloud.utils.component.Manager; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; - -public interface SspManager extends Manager { - /** - * Checks Ssp is activated or not - * @param physicalNetwork - * @return true if physicalNetworkProvider is configured - */ - public boolean canHandle(PhysicalNetwork physicalNetwork); - - /** - * Tell ssp to create a network - * @param network - * @param offering - * @param dest - * @param context - * @return - */ - public boolean createNetwork(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context); - - /** - * Tell ssp to delete a network - * @param network - * @return - */ - public boolean deleteNetwork(Network network); - - /** - * Create a nic entry in ssp - * @param network - * @param nic - * @param dest - * @param context - * @return true on success - */ - public boolean createNicEnv(Network network, NicProfile nic, DeployDestination dest, ReservationContext context); - - /** - * Delete a nic entry from ssp - * @param network - * @param nic - * @param context - * @return - */ - public boolean deleteNicEnv(Network network, NicProfile nic, ReservationContext context); -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspService.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspService.java deleted file mode 100644 index 3330045e1186..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/element/SspService.java +++ /dev/null @@ -1,47 +0,0 @@ -// 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 org.apache.cloudstack.network.element; - -import org.apache.cloudstack.api.commands.AddSspCmd; -import org.apache.cloudstack.api.commands.DeleteSspCmd; - -import com.cloud.host.Host; -import com.cloud.utils.component.PluggableService; - -/** - * Stratosphere sdn platform plugin service. - */ -public interface SspService extends PluggableService { - /** - * Add an ssp api endpoint information as an host - * - * Adds a api endpoint information in database and - * make it usable. - * @param cmd - * @return - */ - public Host addSspHost(AddSspCmd cmd); - - /** - * Delete an ssp api endpoint information - * - * Deletes the information from database. - * @param cmd - * @return - */ - public boolean deleteSspHost(DeleteSspCmd cmd); -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/guru/SspGuestNetworkGuru.java b/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/guru/SspGuestNetworkGuru.java deleted file mode 100644 index 894c258939e2..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/java/org/apache/cloudstack/network/guru/SspGuestNetworkGuru.java +++ /dev/null @@ -1,152 +0,0 @@ -// 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 org.apache.cloudstack.network.guru; - -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientVirtualNetworkCapacityException; -import com.cloud.network.Network; -import com.cloud.network.NetworkMigrationResponder; -import com.cloud.network.NetworkProfile; -import com.cloud.network.PhysicalNetwork; -import com.cloud.network.PhysicalNetwork.IsolationMethod; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.guru.GuestNetworkGuru; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingServiceMapDao; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.ReservationContextImpl; -import com.cloud.vm.VirtualMachineProfile; -import org.apache.cloudstack.network.element.SspElement; -import org.apache.cloudstack.network.element.SspManager; - -import javax.inject.Inject; - -/** - * Stratosphere SDN Platform NetworkGuru - */ -public class SspGuestNetworkGuru extends GuestNetworkGuru implements NetworkMigrationResponder { - - @Inject - SspManager _sspMgr; - @Inject - NetworkDao _networkDao; - @Inject - NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; - - public SspGuestNetworkGuru() { - super(); - _isolationMethods = new IsolationMethod[] {new IsolationMethod("SSP")}; - } - - @Override - protected boolean canHandle(NetworkOffering offering, NetworkType networkType, PhysicalNetwork physicalNetwork) { - logger.trace("canHandle"); - - String setting = null; - if (physicalNetwork != null && physicalNetwork.getIsolationMethods().contains("SSP")) { - // Be careful, PhysicalNetwork#getIsolationMethods() returns List, not List - setting = "physicalnetwork setting"; - } else if (_ntwkOfferingSrvcDao.isProviderForNetworkOffering(offering.getId(), Network.Provider.getProvider(SspElement.s_SSP_NAME))) { - setting = "network offering setting"; - } - if (setting != null) { - if (networkType != NetworkType.Advanced) { - logger.info("SSP enebled by " + setting + " but not active because networkType was " + networkType); - } else if (!isMyTrafficType(offering.getTrafficType())) { - logger.info("SSP enabled by " + setting + " but not active because traffic type not Guest"); - } else if (offering.getGuestType() != Network.GuestType.Isolated) { - logger.info("SSP works for network isolatation."); - } else if (!_sspMgr.canHandle(physicalNetwork)) { - logger.info("SSP manager not ready"); - } else { - return true; - } - } else { - logger.debug("SSP not configured to be active"); - } - return false; - } - - /* (non-Javadoc) - * FYI: What is done in parent class is allocateVnet(vlan). - * Effective return object members are: cidr, broadcastUri, gateway, mode, physicalNetworkId - * The other members will be silently ignored. - * This method is called at DeployVMCmd#execute (running phase) - NetworkManagerImpl#prepare - * @see org.apache.cloudstack.network.guru.GuestNetworkGuru#implement(com.cloud.network.Network, com.cloud.offering.NetworkOffering, com.cloud.deploy.DeployDestination, com.cloud.vm.ReservationContext) - */ - @Override - public Network implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException { - logger.trace("implement " + network.toString()); - super.implement(network, offering, dest, context); - _sspMgr.createNetwork(network, offering, dest, context); - return network; - } - - @Override - public void shutdown(NetworkProfile profile, NetworkOffering offering) { - logger.trace("shutdown " + profile.toString()); - _sspMgr.deleteNetwork(profile); - super.shutdown(profile, offering); - } - - @Override - public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException { - super.reserve(nic, network, vm, dest, context); - _sspMgr.createNicEnv(network, nic, dest, context); - } - - @Override - public boolean release(NicProfile nic, VirtualMachineProfile vm, String reservationId) { - Network network = _networkDao.findById(nic.getNetworkId()); - _sspMgr.deleteNicEnv(network, nic, new ReservationContextImpl(reservationId, null, null)); - return super.release(nic, vm, reservationId); - } - - @Override - public void updateNicProfile(NicProfile profile, Network network) { - super.updateNicProfile(profile, network); - } - - @Override - public boolean prepareMigration(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) { - try { - reserve(nic, network, vm, dest, context); - } catch (InsufficientVirtualNetworkCapacityException e) { - logger.error("prepareForMigration failed", e); - return false; - } catch (InsufficientAddressCapacityException e) { - logger.error("prepareForMigration failed", e); - return false; - } - return true; - } - - @Override - public void rollbackMigration(NicProfile nic, Network network, VirtualMachineProfile vm, ReservationContext src, ReservationContext dst) { - release(nic, vm, dst.getReservationId()); - } - - @Override - public void commitMigration(NicProfile nic, Network network, VirtualMachineProfile vm, ReservationContext src, ReservationContext dst) { - release(nic, vm, src.getReservationId()); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/module.properties b/plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/module.properties deleted file mode 100644 index b4d6e1d4db7f..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=ssp -parent=network diff --git a/plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml b/plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml deleted file mode 100644 index cd373e16cc35..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/main/resources/META-INF/cloudstack/ssp/spring-ssp-context.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - diff --git a/plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspClientTest.java b/plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspClientTest.java deleted file mode 100644 index a6b723ccda1d..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspClientTest.java +++ /dev/null @@ -1,82 +0,0 @@ -// 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 org.apache.cloudstack.network.element; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.doReturn; -import java.util.UUID; - -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.BasicResponseHandler; -import org.junit.Test; - -public class SspClientTest { - String uuid = UUID.randomUUID().toString(); - - String apiUrl = "http://a.example.jp/"; - String username = "foo"; - String password = "bar"; - - @Test - public void loginTest() throws Exception { - SspClient sspClient = spy(new SspClient(apiUrl, username, password)); - - HttpClient client = mock(HttpClient.class); - doReturn(client).when(sspClient).getHttpClient(); - when(client.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class))).thenReturn(""); - - assertTrue(sspClient.login()); - assertTrue(sspClient.login()); - assertTrue(sspClient.login()); - } - - @Test - public void createNetworkTest() throws Exception { - String networkName = "example network 1"; - String tenant_net_uuid = UUID.randomUUID().toString(); - SspClient sspClient = spy(new SspClient(apiUrl, username, password)); - - HttpClient client = mock(HttpClient.class); - doReturn(client).when(sspClient).getHttpClient(); - String body = "{\"uuid\":\"" + tenant_net_uuid + "\",\"name\":\"" + networkName - + "\",\"tenant_uuid\":\"" + uuid + "\"}"; - when(client.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class))).thenReturn(body); - - SspClient.TenantNetwork tnet = sspClient.createTenantNetwork(uuid, networkName); - assertEquals(tnet.name, networkName); - assertEquals(tnet.uuid, tenant_net_uuid); - assertEquals(tnet.tenantUuid, uuid); - } - - @Test - public void deleteNetworkTest() throws Exception { - String tenant_net_uuid = UUID.randomUUID().toString(); - SspClient sspClient = spy(new SspClient(apiUrl, username, password)); - - HttpClient client = mock(HttpClient.class); - doReturn(client).when(sspClient).getHttpClient(); - when(client.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class))).thenReturn(""); - - sspClient.deleteTenantNetwork(tenant_net_uuid); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspElementTest.java b/plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspElementTest.java deleted file mode 100644 index d0aaffada7f0..000000000000 --- a/plugins/network-elements/stratosphere-ssp/src/test/java/org/apache/cloudstack/network/element/SspElementTest.java +++ /dev/null @@ -1,154 +0,0 @@ -// 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 org.apache.cloudstack.network.element; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.HashMap; - -import org.junit.Before; -import org.junit.Test; - -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.network.dao.SspCredentialDao; -import org.apache.cloudstack.network.dao.SspCredentialVO; -import org.apache.cloudstack.network.dao.SspTenantDao; -import org.apache.cloudstack.network.dao.SspUuidDao; - -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.network.Network; -import com.cloud.network.NetworkModel; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.dao.PhysicalNetworkDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.dao.PhysicalNetworkVO; -import com.cloud.resource.ResourceManager; -import com.cloud.vm.dao.NicDao; - -public class SspElementTest { - SspElement _element = new SspElement(); - - @Before - public void setUp() { - _element._configDao = mock(ConfigurationDao.class); - _element._dcDao = mock(DataCenterDao.class); - _element._hostDao = mock(HostDao.class); - _element._networkMgr = mock(NetworkOrchestrationService.class); - _element._networkModel = mock(NetworkModel.class); - _element._nicDao = mock(NicDao.class); - _element._physicalNetworkDao = mock(PhysicalNetworkDao.class); - _element._physicalNetworkServiceProviderDao = mock(PhysicalNetworkServiceProviderDao.class); - _element._resourceMgr = mock(ResourceManager.class); - _element._ntwkSrvcDao = mock(NetworkServiceMapDao.class); - - _element._sspCredentialDao = mock(SspCredentialDao.class); - _element._sspTenantDao = mock(SspTenantDao.class); - _element._sspUuidDao = mock(SspUuidDao.class); - } - - Long dataCenterId = new Long(21); - Long physicalNetworkId = new Long(22); - Long networkId = new Long(23); - PhysicalNetworkVO psvo = mock(PhysicalNetworkVO.class); - PhysicalNetworkServiceProviderVO nspvo = mock(PhysicalNetworkServiceProviderVO.class); - SspCredentialVO credential = mock(SspCredentialVO.class); - HostVO host = mock(HostVO.class); - - public void fullyConfigured() { - // when physicalNetworkServiceProvider is configured - when(psvo.getId()).thenReturn(physicalNetworkId); - when(psvo.getDataCenterId()).thenReturn(dataCenterId); - - when(_element._physicalNetworkDao.findById(physicalNetworkId)).thenReturn(psvo); - - when(nspvo.getState()).thenReturn(PhysicalNetworkServiceProvider.State.Enabled); - when(nspvo.getPhysicalNetworkId()).thenReturn(physicalNetworkId); - - when(_element._physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetworkId, "StratosphereSsp")).thenReturn(nspvo); - - // and zone api server, credentail is configured - when(credential.getUsername()).thenReturn("foo"); - when(credential.getPassword()).thenReturn("bar"); - - when(_element._sspCredentialDao.findByZone(dataCenterId.longValue())).thenReturn(credential); - - HashMap details = new HashMap(); - details.put("sspHost", "v1Api"); - details.put("url", "http://a.example.jp/"); - - when(host.getDataCenterId()).thenReturn(dataCenterId); - when(host.getDetails()).thenReturn(details); - when(host.getDetail("sspHost")).thenReturn(details.get("sspHost")); - when(host.getDetail("url")).thenReturn(details.get("url")); - - when(_element._resourceMgr.listAllHostsInOneZoneByType(Host.Type.L2Networking, dataCenterId)).thenReturn(Arrays. asList(host)); - - when(_element._ntwkSrvcDao.canProviderSupportServiceInNetwork(networkId, Network.Service.Connectivity, _element.getProvider())).thenReturn(true); - } - - @Test - public void isReadyTest() { - fullyConfigured(); - - // isReady is called in changing the networkserviceprovider state to Enabled. - when(nspvo.getState()).thenReturn(PhysicalNetworkServiceProvider.State.Disabled); - - // ssp is ready - assertTrue(_element.isReady(nspvo)); - - // If you don't call addstratospheressp api, ssp won't be ready - when(_element._sspCredentialDao.findByZone(dataCenterId.longValue())).thenReturn(null); - when(_element._resourceMgr.listAllHostsInOneZoneByType(Host.Type.L2Networking, dataCenterId)).thenReturn(Arrays. asList()); - assertFalse(_element.isReady(nspvo)); - } - - @Test - public void canHandleTest() { - fullyConfigured(); - - // ssp is active - assertTrue(_element.canHandle(psvo)); - - // You can disable ssp temporary by truning the state disabled - when(nspvo.getState()).thenReturn(PhysicalNetworkServiceProvider.State.Disabled); - assertFalse(_element.canHandle(psvo)); - - // If you don't want ssp for a specific physicalnetwork, you don't need to - // setup physicalNetworkProvider. - when(_element._physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetworkId, "StratosphereSsp")).thenReturn(null); - assertFalse(_element.canHandle(psvo)); - - // restore... - when(nspvo.getState()).thenReturn(PhysicalNetworkServiceProvider.State.Enabled); - when(_element._physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetworkId, "StratosphereSsp")).thenReturn(nspvo); - - // If you don't call addstratospheressp api, ssp won't be active - when(_element._sspCredentialDao.findByZone(dataCenterId.longValue())).thenReturn(null); - when(_element._resourceMgr.listAllHostsInOneZoneByType(Host.Type.L2Networking, dataCenterId)).thenReturn(Arrays. asList()); - assertFalse(_element.canHandle(psvo)); - } -} diff --git a/plugins/network-elements/stratosphere-ssp/sspmock/sspmock.py b/plugins/network-elements/stratosphere-ssp/sspmock/sspmock.py deleted file mode 100644 index 492e32545fef..000000000000 --- a/plugins/network-elements/stratosphere-ssp/sspmock/sspmock.py +++ /dev/null @@ -1,99 +0,0 @@ -# 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. - -import json -import uuid -from flask import Flask,request,make_response -from beaker.middleware import SessionMiddleware -app = Flask(__name__) - -tenant_networks = [] -tenant_ports = [] - -@app.route("/ws.v1/login", methods=["POST",]) -def login(): - assert "username" in request.form - assert "password" in request.form - request.environ["beaker.session"]["login"] = True - res = make_response("", 200) - res.headers["content-type"] = "application/json" - return res - -@app.route("/ssp.v1/tenant-networks", methods=["POST",]) -def create_tenant_network(): - if "login" not in request.environ["beaker.session"]: - return make_response("", 401) - obj = request.json - obj["uuid"] = str(uuid.uuid1()) - tenant_networks.append(obj) - res = make_response(json.dumps(obj), 201) - res.headers["content-type"] = "application/json" - return res - -@app.route("/ssp.v1/tenant-networks/", methods=["DELETE",]) -def delete_tenant_network(tenant_net_uuid): - if "login" not in request.environ["beaker.session"]: - return make_response("", 401) - for net in tenant_networks: - if net["uuid"] == tenant_net_uuid: - tenant_networks.remove(net) - return make_response("", 204) - return make_response("", 404) - -@app.route("/ssp.v1/tenant-ports", methods=["POST",]) -def create_tenant_port(): - if "login" not in request.environ["beaker.session"]: - return make_response("", 401) - obj = request.json - obj["uuid"] = str(uuid.uuid1()) - tenant_ports.append(obj) - res = make_response(json.dumps(obj), 201) - res.headers["content-type"] = "application/json" - return res - -@app.route("/ssp.v1/tenant-ports/", methods=["DELETE",]) -def delete_tenant_port(tenant_port_uuid): - if "login" not in request.environ["beaker.session"]: - return make_response("", 401) - for port in tenant_ports: - if port["uuid"] == tenant_port_uuid: - tenant_ports.remove(port) - return make_response("", 204) - return make_response("", 404) - -@app.route("/ssp.v1/tenant-ports/", methods=["PUT",]) -def update_tenant_port(tenant_port_uuid): - if "login" not in request.environ["beaker.session"]: - return make_response("", 401) - for port in tenant_ports: - if port["uuid"] == tenant_port_uuid: - obj = request.json - obj["uuid"] = tenant_port_uuid - obj["vlan_id"] = 100 - tenant_ports.remove(port) - tenant_ports.append(obj) - res = make_response(json.dumps(obj), 200) - res.headers["content-type"] = "application/json" - return res - return make_response("", 404) - -if __name__=="__main__": - app.wsgi_app = SessionMiddleware(app.wsgi_app, { - "session.auto":True, - "session.type":"cookie", - "session.validate_key":"hoge"}) - app.run(host="0.0.0.0", port=9080, debug=True) diff --git a/plugins/pom.xml b/plugins/pom.xml index 3262404032fa..513622890820 100755 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -58,7 +58,6 @@ api/discovery api/rate-limit - api/solidfire-intg-test backup/dummy backup/networker @@ -88,7 +87,6 @@ hypervisors/external hypervisors/hyperv hypervisors/kvm - hypervisors/ucs hypervisors/xenserver integrations/cloudian @@ -97,18 +95,13 @@ metrics - network-elements/bigswitch network-elements/dns-notifier network-elements/elastic-loadbalancer - network-elements/globodns network-elements/internal-loadbalancer network-elements/netscaler - network-elements/nicira-nvp network-elements/opendaylight network-elements/ovs network-elements/palo-alto - network-elements/stratosphere-ssp - network-elements/brocade-vcs network-elements/vxlan outofbandmanagement-drivers/ipmitool @@ -122,13 +115,9 @@ storage/image/s3 storage/image/sample storage/image/swift - storage/volume/cloudbyte - storage/volume/datera storage/volume/default - storage/volume/nexenta storage/volume/sample storage/volume/ontap - storage/volume/solidfire storage/volume/scaleio storage/volume/linstor storage/volume/storpool @@ -144,10 +133,8 @@ storage-allocators/random user-authenticators/ldap - user-authenticators/md5 user-authenticators/oauth2 user-authenticators/pbkdf2 - user-authenticators/plain-text user-authenticators/saml2 user-authenticators/sha256salted @@ -230,10 +217,8 @@ api/vmware-sioc backup/veeam hypervisors/vmware - network-elements/cisco-vnmc network-elements/nsx network-elements/netris - network-elements/juniper-contrail network-elements/tungsten diff --git a/plugins/storage/volume/cloudbyte/pom.xml b/plugins/storage/volume/cloudbyte/pom.xml deleted file mode 100644 index 453a03ee155d..000000000000 --- a/plugins/storage/volume/cloudbyte/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - cloud-plugin-storage-volume-cloudbyte - Apache CloudStack Plugin - Storage Volume CloudByte Provider - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../../pom.xml - - - - org.apache.cloudstack - cloud-plugin-storage-volume-default - ${project.version} - - - org.apache.cloudstack - cloud-engine-storage-volume - ${project.version} - - - com.mysql - mysql-connector-j - provided - - - com.google.code.gson - gson - - - org.glassfish.jersey.core - jersey-client - ${cs.jersey-client.version} - - - - - - maven-surefire-plugin - - - integration-test - - test - - - - - - - diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/driver/ElastistorPrimaryDataStoreDriver.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/driver/ElastistorPrimaryDataStoreDriver.java deleted file mode 100644 index 9dc0229f7828..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/driver/ElastistorPrimaryDataStoreDriver.java +++ /dev/null @@ -1,437 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.driver; - -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; -import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreCapabilities; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.command.CreateObjectAnswer; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.FileSystem; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.cloudstack.storage.volume.VolumeObject; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.host.Host; -import com.cloud.storage.DiskOfferingVO; -import com.cloud.storage.ResizeVolumePayload; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.VolumeDetailVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.DiskOfferingDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeDetailsDao; -import com.cloud.user.AccountManager; -import com.cloud.utils.Pair; -import com.cloud.utils.exception.CloudRuntimeException; - -/** - * The implementation class for ElastistorPrimaryDataStoreDriver. - * This directs the public interface methods to use CloudByte's Elastistor based - * volumes. - */ -public class ElastistorPrimaryDataStoreDriver extends CloudStackPrimaryDataStoreDriverImpl implements PrimaryDataStoreDriver { - - - @Inject - AccountManager _accountMgr; - @Inject - DiskOfferingDao _diskOfferingDao; - @Inject - private VolumeDao _volumeDao; - @Inject - private PrimaryDataStoreDao _storagePoolDao; - @Inject - StorageManager storageMgr; - @Inject - VolumeDetailsDao _volumeDetailsDao; - - @Override - public DataTO getTO(DataObject data) { - return null; - } - - @Override - public DataStoreTO getStoreTO(DataStore store) { - return null; - } - - @Override - public void createAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { - - String iqn = null; - String errMsg = null; - - CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errMsg == null, errMsg)); - - if (dataObject.getType() == DataObjectType.VOLUME) { - - VolumeInfo volumeInfo = (VolumeInfo) dataObject; - - long storagePoolId = dataStore.getId(); - String volumeName = volumeInfo.getName(); - Long Iops = volumeInfo.getMaxIops(); - // quota size of the cloudbyte volume will be increased with the given HypervisorSnapshotReserve - Long quotaSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, _storagePoolDao.findById(storagePoolId)); - - StoragePoolVO storagePool = _storagePoolDao.findById(dataStore.getId()); - VolumeVO volume = _volumeDao.findById(volumeInfo.getId()); - - // if the primary storage is not managed (thick provisioned) - // then no need to create volume at elastistor, - // calling super(default) that creates a vdi(disk) only. - if (!(storagePool.isManaged())) { - super.createAsync(dataStore, dataObject, callback); - - // update the volume property - volume.setPoolType(storagePool.getPoolType()); - _volumeDao.update(volume.getId(), volume); - - return; - } - - DiskOfferingVO diskOffering = _diskOfferingDao.findById(volumeInfo.getDiskOfferingId()); - - long capacityIops = storagePool.getCapacityIops(); - capacityIops = capacityIops - Iops; - - if (capacityIops < 0) { - throw new CloudRuntimeException(String.format("IOPS not available. [pool:%s] [availiops:%d] [requirediops:%d]", storagePool, capacityIops, Iops)); - } - - String protocoltype = null; - StoragePoolVO dataStoreVO = _storagePoolDao.findById(storagePoolId); - String desc = diskOffering.getDisplayText(); - - if (desc.toLowerCase().contains("iscsi")) { - protocoltype = "iscsi"; - } else if (dataStoreVO.getPoolType().equals(StoragePoolType.NetworkFilesystem) || dataStoreVO.getPoolType().equals(StoragePoolType.Filesystem)) { - protocoltype = "nfs"; - } else { - protocoltype = "iscsi"; - } - - FileSystem esvolume = null; - try { - esvolume = ElastistorUtil.createElastistorVolume(volumeName, dataStoreVO.getUuid(), quotaSize, Iops, protocoltype, volumeName); - } catch (Throwable e) { - logger.error(e.toString(), e); - result.setResult(e.toString()); - callback.complete(result); - throw new CloudRuntimeException(e.getMessage()); - } - - if (esvolume.getNfsenabled().equalsIgnoreCase("true")) { - volume.set_iScsiName(esvolume.getPath()); - volume.setPoolType(StoragePoolType.NetworkFilesystem); - } else { - iqn = esvolume.getIqn(); - String modifiediqn = "/" + iqn + "/0"; - volume.set_iScsiName(modifiediqn); - volume.setPoolType(StoragePoolType.IscsiLUN); - } - - volume.setFolder(String.valueOf(esvolume.getUuid())); - volume.setPoolId(storagePoolId); - volume.setUuid(esvolume.getUuid()); - volume.setPath(null); - - _volumeDao.update(volume.getId(), volume); - - long capacityBytes = storagePool.getCapacityBytes(); - long usedBytes = storagePool.getUsedBytes(); - - Long inbytes = volume.getSize(); - - usedBytes += inbytes; - - storagePool.setCapacityIops(capacityIops); - storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); - - _storagePoolDao.update(storagePoolId, storagePool); - logger.info("Elastistor volume creation complete."); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to createAsync"; - logger.error(errMsg); - } - - result.setResult(errMsg); - - callback.complete(result); - } - - @Override - public void deleteAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { - - String errMsg = null; - - StoragePoolVO storagePool = _storagePoolDao.findById(dataStore.getId()); - - // if the primary storage is not managed(thick provisioned) then no need - // to delete volume at elastistor, just - // call the super(default) to delete a vdi(disk) only. - - if (!(storagePool.isManaged())) { - super.deleteAsync(dataStore, dataObject, callback); - return; - } - - if (dataObject.getType() == DataObjectType.VOLUME) { - VolumeInfo volumeInfo = (VolumeInfo) dataObject; - - long storagePoolId = dataStore.getId(); - boolean result = false; - try { - result = ElastistorUtil.deleteElastistorVolume(volumeInfo.getUuid()); - } catch (Throwable e) { - e.printStackTrace(); - CommandResult result2 = new CommandResult(); - result2.setResult(e.toString()); - callback.complete(result2); - } - - if (result) { - long usedBytes = storagePool.getUsedBytes(); - long capacityIops = storagePool.getCapacityIops(); - - usedBytes -= volumeInfo.getSize(); - capacityIops += volumeInfo.getMaxIops(); - - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - storagePool.setCapacityIops(capacityIops < 0 ? 0 : capacityIops); - - _storagePoolDao.update(storagePoolId, storagePool); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to deleteAsync"; - } - - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to deleteAsync"; - } - - CommandResult result = new CommandResult(); - - result.setResult(errMsg); - - callback.complete(result); - } - - @Override - public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public void copyAsync(DataObject srcData, DataObject destData, Host destHost, AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean canCopy(DataObject srcData, DataObject destData) { - return false; - } - - @Override - public void resize(DataObject data, AsyncCompletionCallback callback) { - - logger.debug("Resize elastistor volume started"); - Boolean status = false; - VolumeObject vol = (VolumeObject) data; - StoragePool pool = (StoragePool) data.getDataStore(); - - ResizeVolumePayload resizeParameter = (ResizeVolumePayload) vol.getpayload(); - - CreateCmdResult result = new CreateCmdResult(null, null); - - StoragePoolVO poolVO = _storagePoolDao.findById(pool.getId()); - - if (!(poolVO.isManaged())) { - super.resize(data, callback); - return; - } - - try { - - status = ElastistorUtil.updateElastistorVolumeSize(vol.getUuid(), resizeParameter.newSize); - - } catch (Throwable e) { - logger.error("Resize elastistor volume failed, please contact elastistor admin.", e); - result.setResult(e.toString()); - callback.complete(result); - } - - if (status) { - // now updating the cloudstack storagepool usedbytes and volume - Long usedBytes = poolVO.getUsedBytes(); - Long currentVolumeSize = vol.getSize(); - Long newUsedBytes; - - if (currentVolumeSize < resizeParameter.newSize) { - newUsedBytes = usedBytes + (resizeParameter.newSize - currentVolumeSize); - poolVO.setUsedBytes(newUsedBytes); - } else { - newUsedBytes = usedBytes - (currentVolumeSize - resizeParameter.newSize); - poolVO.setUsedBytes(newUsedBytes); - } - - _storagePoolDao.update(pool.getId(), poolVO); - - vol.getVolume().setSize(resizeParameter.newSize); - vol.update(); - callback.complete(result); - } else { - callback.complete(result); - } - - } - - @Override - public void handleQualityOfServiceForVolumeMigration(VolumeInfo volumeInfo, QualityOfServiceState qualityOfServiceState) {} - - //this method will utilize the volume details table to add third party volume properties - public void updateVolumeDetails(VolumeVO volume, FileSystem esvolume) { - - VolumeDetailVO compression = new VolumeDetailVO(volume.getId(), "compression", esvolume.getCompression(), false); - _volumeDetailsDao.persist(compression); - VolumeDetailVO deduplication = new VolumeDetailVO(volume.getId(), "deduplication", esvolume.getDeduplication(), false); - _volumeDetailsDao.persist(deduplication); - VolumeDetailVO sync = new VolumeDetailVO(volume.getId(), "sync", esvolume.getSync(), false); - _volumeDetailsDao.persist(sync); - VolumeDetailVO graceallowed = new VolumeDetailVO(volume.getId(), "graceallowed", esvolume.getGraceallowed(), false); - _volumeDetailsDao.persist(graceallowed); - - } - - @Override - public long getDataObjectSizeIncludingHypervisorSnapshotReserve(DataObject dataObject, StoragePool pool) { - VolumeInfo volume = (VolumeInfo)dataObject; - long volumeSize = volume.getSize(); - Integer hypervisorSnapshotReserve = volume.getHypervisorSnapshotReserve(); - - if (hypervisorSnapshotReserve != null) { - if (hypervisorSnapshotReserve < 25) { - hypervisorSnapshotReserve = 25; - } - - volumeSize += volumeSize * (hypervisorSnapshotReserve / 100f); - } - - return volumeSize; - } - - @Override - public ChapInfo getChapInfo(DataObject dataObject) { - return null; - } - - @Override - public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) { - CreateCmdResult result = null; - try { - logger.info("Taking elastistor volume Snapshot"); - SnapshotObjectTO snapshotTO = (SnapshotObjectTO)snapshot.getTO(); - - String volumeid = snapshotTO.getVolume().getUuid(); - String snapshotname = snapshotTO.getName(); - - Answer answer = ElastistorUtil.createElastistorVolumeSnapshot(volumeid, snapshotname); - - if(answer.getResult() == false){ - logger.info("elastistor volume snapshot failed"); - throw new CloudRuntimeException("elastistor volume snapshot failed"); - }else{ - logger.info("elastistor volume snapshot succesfull"); - - snapshotTO.setPath(answer.getDetails()); - - CreateObjectAnswer createObjectAnswer = new CreateObjectAnswer(snapshotTO); - - result = new CreateCmdResult(null, createObjectAnswer); - - result.setResult(null); - } - } - catch (Throwable e) { - logger.debug("Failed to take snapshot: " + e.getMessage()); - result = new CreateCmdResult(null, null); - result.setResult(e.toString()); - } - callback.complete(result); - } - - @Override - public void revertSnapshot(SnapshotInfo snapshot, SnapshotInfo snapshotOnPrimaryStore, AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public Map getCapabilities() { - Map mapCapabilities = new HashMap(); - - mapCapabilities.put(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString(), Boolean.TRUE.toString()); - - return mapCapabilities; - } - - @Override - public boolean canProvideStorageStats() { - return false; - } - - @Override - public Pair getStorageStats(StoragePool storagePool) { - return null; - } - - @Override - public boolean canProvideVolumeStats() { - return false; - } - - @Override - public Pair getVolumeStats(StoragePool storagePool, String volumeId) { - return null; - } - - @Override - public boolean canHostAccessStoragePool(Host host, StoragePool pool) { - return true; - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java deleted file mode 100644 index 7f3a36d65384..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java +++ /dev/null @@ -1,601 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.lifecycle; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import javax.inject.Inject; - -import com.cloud.host.Host; -import com.cloud.storage.dao.StoragePoolAndAccessGroupMapDao; -import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.FileSystem; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.Tsm; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.UpdateTsmCmdResponse; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.UpdateTsmStorageCmdResponse; -import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateStoragePoolCommand; -import com.cloud.agent.api.DeleteStoragePoolCommand; -import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.capacity.CapacityManager; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceManager; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolAutomation; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.exception.CloudRuntimeException; - -public class ElastistorPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { - @Inject - HostDao _hostDao; - @Inject - StoragePoolHostDao _storagePoolHostDao; - @Inject - protected ResourceManager _resourceMgr; - @Inject - PrimaryDataStoreDao primaryDataStoreDao; - @Inject - AgentManager agentMgr; - @Inject - StorageManager storageMgr; - @Inject - PrimaryDataStoreHelper dataStoreHelper; - @Inject - PrimaryDataStoreDao _storagePoolDao; - @Inject - PrimaryDataStoreHelper _dataStoreHelper; - @Inject - StoragePoolAutomation _storagePoolAutomation; - @Inject - StoragePoolDetailsDao _storagePoolDetailsDao; - @Inject - DataCenterDao _zoneDao; - @Inject - CapacityManager _capacityMgr; - @Inject - private StoragePoolAndAccessGroupMapDao storagePoolAndAccessGroupMapDao; - - @Override - public DataStore initialize(Map dsInfos) { - - String url = (String) dsInfos.get("url"); - Long zoneId = (Long) dsInfos.get("zoneId"); - Long podId = (Long) dsInfos.get("podId"); - Long clusterId = (Long) dsInfos.get("clusterId"); - String storagePoolName = (String) dsInfos.get("name"); - String providerName = (String) dsInfos.get("providerName"); - Long capacityBytes = (Long) dsInfos.get("capacityBytes"); - Long capacityIops = (Long) dsInfos.get("capacityIops"); - String tags = (String) dsInfos.get("tags"); - Boolean isTagARule = (Boolean) dsInfos.get("isTagARule"); - boolean managed = (Boolean) dsInfos.get("managed"); - Map details = (Map) dsInfos.get("details"); - String domainName = details.get("domainname"); - - String storageIp; - int storagePort = 0; - StoragePoolType storagetype = null; - String accesspath = null; - String protocoltype = null; - String mountpoint = null; - - if (!managed) { - storageIp = getStorageIp(url); - storagePort = getDefaultStoragePort(url); - storagetype = getStorageType(url); - accesspath = getAccessPath(url); - protocoltype = getProtocolType(url); - String[] mp = accesspath.split("/"); - mountpoint = mp[1]; - - } else if (details.get("hypervisortype") == "KVM") { - storageIp = url; - storagePort = 3260; - storagetype = StoragePoolType.Iscsi; - accesspath = storageIp + ":/" + storagePoolName; - }else{ - storageIp = url; - storagePort = 2049; - storagetype = StoragePoolType.NetworkFilesystem; - accesspath = storageIp + ":/" + storagePoolName; - } - /** - * if the elastistor params which are required for plugin configuration - * are not injected through spring-storage-volume-cloudbyte-context.xml, - * it can be set from details map. - */ - if (details.get("esaccountid") != null) - ElastistorUtil.setElastistorAccountId(details.get("esaccountid")); - if (details.get("esdefaultgateway") != null) - ElastistorUtil.setElastistorGateway(details.get("esdefaultgateway")); - if (details.get("estntinterface") != null) - ElastistorUtil.setElastistorInterface(details.get("estntinterface")); - if (details.get("espoolid") != null) - ElastistorUtil.setElastistorPoolId(details.get("espoolid")); - if (details.get("essubnet") != null) - ElastistorUtil.setElastistorSubnet(details.get("essubnet")); - - logger.info("Elastistor details was set successfully."); - - if (capacityBytes == null || capacityBytes <= 0) { - throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0."); - } - - if (capacityIops == null || capacityIops <= 0) { - throw new IllegalArgumentException("'capacityIops' must be present and greater than 0."); - } - - if (domainName == null) { - domainName = "ROOT"; - logger.debug("setting the domain to ROOT"); - } - - // elastistor does not allow same name and ip pools. - List storagePoolVO = _storagePoolDao.listAll(); - for (StoragePoolVO poolVO : storagePoolVO) { - if (storagePoolName.equals(poolVO.getName())) { - throw new IllegalArgumentException("Storage pool with this name already exists in elastistor, please specify a unique name. [name:" + storagePoolName + "]"); - } - if (storageIp.equals(poolVO.getHostAddress())) { - throw new IllegalArgumentException("Storage pool with this ip already exists in elastistor, please specify a unique ip. [ip:" + storageIp + "]"); - } - } - - PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); - - parameters.setHost(storageIp); - parameters.setPort(storagePort); - parameters.setPath(accesspath); - parameters.setType(storagetype); - parameters.setZoneId(zoneId); - parameters.setPodId(podId); - parameters.setName(storagePoolName); - parameters.setProviderName(providerName); - parameters.setManaged(managed); - parameters.setCapacityBytes(capacityBytes); - parameters.setUsedBytes(0); - parameters.setCapacityIops(capacityIops); - parameters.setHypervisorType(HypervisorType.Any); - parameters.setTags(tags); - parameters.setIsTagARule(isTagARule); - parameters.setDetails(details); - parameters.setClusterId(clusterId); - - Tsm tsm = null; - if (managed) { - // creates the TSM in elastistor - tsm = createElastistorTSM(storagePoolName, storageIp, capacityBytes, capacityIops, domainName); - } else { - // creates the TSM & Volume in elastistor - tsm = createElastistorTSM(storagePoolName, storageIp, capacityBytes, capacityIops, domainName); - - parameters = createElastistorVolume(parameters, tsm, storagePoolName, capacityBytes, capacityIops, protocoltype, mountpoint); - } - - // setting tsm's uuid as storagepool's uuid - parameters.setUuid(tsm.getUuid()); - - return _dataStoreHelper.createPrimaryDataStore(parameters); - } - - private Tsm createElastistorTSM(String storagePoolName, String storageIp, Long capacityBytes, Long capacityIops, String domainName) { - - logger.info("Creation of elastistor TSM started."); - - Tsm tsm; - String elastistorAccountId; - try { - // to create a tsm , account id is required, so getting the account id for the given cloudstack domain - elastistorAccountId = ElastistorUtil.getElastistorAccountId(domainName); - - // create the tsm for the given account id - tsm = ElastistorUtil.createElastistorTsm(storagePoolName, storageIp, capacityBytes, capacityIops, elastistorAccountId); - } catch (Throwable e) { - logger.error("Failed to create TSM in elastistor.", e); - throw new CloudRuntimeException("Failed to create TSM in elastistor. " + e.getMessage()); - } - - logger.info("Creation of elastistor TSM completed successfully."); - - return tsm; - } - - private PrimaryDataStoreParameters createElastistorVolume(PrimaryDataStoreParameters parameters, Tsm tsm, String storagePoolName, Long capacityBytes, Long capacityIops, String protocoltype, - String mountpoint) { - - try { - - logger.info("Creation of elastistor volume started."); - - FileSystem volume = ElastistorUtil.createElastistorVolume(storagePoolName, tsm.getUuid(), capacityBytes, capacityIops, protocoltype, mountpoint); - - if (protocoltype.contentEquals("iscsi")) { - String accesspath = "/" + volume.getIqn() + "/0"; - parameters.setPath(accesspath); - } - logger.info("Creation of elastistor volume completed successfully."); - - return parameters; - } catch (Throwable e) { - logger.error("Failed to create volume in elastistor.", e); - throw new CloudRuntimeException("Failed to create volume in elastistor. " + e.getMessage()); - } - - } - - private String getAccessPath(String url) { - StringTokenizer st = new StringTokenizer(url, "/"); - int count = 0; - while (st.hasMoreElements()) { - if (count == 2) { - String s = "/"; - return s.concat(st.nextElement().toString()); - } - st.nextElement(); - count++; - } - return null; - } - - private StoragePoolType getStorageType(String url) { - - StringTokenizer st = new StringTokenizer(url, ":"); - - while (st.hasMoreElements()) { - String accessprotocol = st.nextElement().toString(); - - if (accessprotocol.contentEquals("nfs")) { - return StoragePoolType.NetworkFilesystem; - } else if (accessprotocol.contentEquals("iscsi")) { - return StoragePoolType.IscsiLUN; - } - - else - - break; - - } - return null; - } - - private String getProtocolType(String url) { - StringTokenizer st = new StringTokenizer(url, ":"); - - while (st.hasMoreElements()) { - String accessprotocol = st.nextElement().toString(); - - if (accessprotocol.contentEquals("nfs")) { - return "nfs"; - } else if (accessprotocol.contentEquals("iscsi")) { - return "iscsi"; - } else - break; - } - return null; - } - - // this method parses the url and gets the default storage port based on - // access protocol - private int getDefaultStoragePort(String url) { - - StringTokenizer st = new StringTokenizer(url, ":"); - - while (st.hasMoreElements()) { - - String accessprotocol = st.nextElement().toString(); - - if (accessprotocol.contentEquals("nfs")) { - return 2049; - } else if (accessprotocol.contentEquals("iscsi")) { - return 3260; - } else - break; - - } - return -1; - - } - - // parses the url and returns the storage volume ip - private String getStorageIp(String url) { - - StringTokenizer st = new StringTokenizer(url, "/"); - int count = 0; - - while (st.hasMoreElements()) { - if (count == 1) - return st.nextElement().toString(); - - st.nextElement(); - count++; - } - return null; - } - - @Override - public boolean attachCluster(DataStore store, ClusterScope scope) { - - dataStoreHelper.attachCluster(store); - - StoragePoolVO dataStoreVO = _storagePoolDao.findById(store.getId()); - - PrimaryDataStoreInfo primarystore = (PrimaryDataStoreInfo) store; - List hostsToConnect = _resourceMgr.getEligibleUpHostsInClusterForStorageConnection(primarystore); - logger.debug(String.format("Attaching the pool to each of the hosts %s in the cluster: %s", hostsToConnect, primarystore.getClusterId())); - - if (!dataStoreVO.isManaged()) { - boolean success = false; - for (HostVO h : hostsToConnect) { - success = createStoragePool(h, primarystore); - if (success) { - break; - } - } - } - - logger.debug("In createPool Adding the pool to each of the hosts"); - List poolHosts = new ArrayList(); - for (HostVO h : hostsToConnect) { - try { - storageMgr.connectHostToSharedPool(h, primarystore.getId()); - poolHosts.add(h); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + h + " and " + primarystore, e); - } - - if (poolHosts.isEmpty()) { - logger.warn("No host can access storage pool " + primarystore + " on cluster " + primarystore.getClusterId()); - primaryDataStoreDao.expunge(primarystore.getId()); - throw new CloudRuntimeException("Failed to access storage pool"); - } - } - - return true; - } - - private boolean createStoragePool(Host host, StoragePool pool) { - logger.debug(String.format("creating pool %s on host %s", pool, host)); - if (pool.getPoolType() != StoragePoolType.NetworkFilesystem && pool.getPoolType() != StoragePoolType.Filesystem && pool.getPoolType() != StoragePoolType.IscsiLUN - && pool.getPoolType() != StoragePoolType.Iscsi && pool.getPoolType() != StoragePoolType.VMFS && pool.getPoolType() != StoragePoolType.SharedMountPoint - && pool.getPoolType() != StoragePoolType.PreSetup && pool.getPoolType() != StoragePoolType.OCFS2 && pool.getPoolType() != StoragePoolType.RBD - && pool.getPoolType() != StoragePoolType.CLVM) { - logger.warn(" Doesn't support storage pool type " + pool.getPoolType()); - return false; - } - CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, pool); - final Answer answer = agentMgr.easySend(host.getId(), cmd); - if (answer != null && answer.getResult()) { - return true; - } else { - primaryDataStoreDao.expunge(pool.getId()); - String msg = ""; - if (answer != null) { - msg = String.format("Can not create storage pool through host %s due to %s", host, answer.getDetails()); - logger.warn(msg); - } else { - msg = String.format("Can not create storage pool through host %s due to CreateStoragePoolCommand returns null", host); - logger.warn(msg); - } - throw new CloudRuntimeException(msg); - } - } - - @Override - public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { - _dataStoreHelper.attachHost(store, scope, existingInfo); - return true; - } - - @Override - public boolean attachZone(DataStore dataStore, ZoneScope scope, HypervisorType hypervisorType) { - List hostsToConnect = _resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, scope.getScopeId(), hypervisorType); - - logger.debug(String.format("In createPool. Attaching the pool to each of the hosts in %s.", hostsToConnect)); - List poolHosts = new ArrayList(); - for (HostVO host : hostsToConnect) { - try { - storageMgr.connectHostToSharedPool(host, dataStore.getId()); - poolHosts.add(host); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); - } - } - if (poolHosts.isEmpty()) { - logger.warn("No host can access storage pool " + dataStore + " in this zone."); - primaryDataStoreDao.expunge(dataStore.getId()); - throw new CloudRuntimeException("Failed to create storage pool as it is not accessible to hosts."); - } - dataStoreHelper.attachZone(dataStore, hypervisorType); - return true; - } - - @Override - public boolean maintain(DataStore store) { - _storagePoolAutomation.maintain(store); - _dataStoreHelper.maintain(store); - return true; - } - - @Override - public boolean cancelMaintain(DataStore store) { - _dataStoreHelper.cancelMaintain(store); - _storagePoolAutomation.cancelMaintain(store); - return true; - } - - @Override - public void enableStoragePool(DataStore dataStore) { - _dataStoreHelper.enable(dataStore); - } - - @Override - public void disableStoragePool(DataStore dataStore) { - _dataStoreHelper.disable(dataStore); - } - - @SuppressWarnings("finally") - @Override - public boolean deleteDataStore(DataStore store) { - List hostPoolRecords = _storagePoolHostDao.listByPoolId(store.getId()); - StoragePool pool = (StoragePool) store; - - // find the hypervisor where the storage is attached to. - HypervisorType hType = null; - if (hostPoolRecords.size() > 0) { - hType = getHypervisorType(hostPoolRecords.get(0).getHostId()); - } - - StoragePoolVO storagePoolVO = _storagePoolDao.findById(store.getId()); - - if (!(storagePoolVO.isManaged())) { - // Remove the SR associated with the Xenserver - for (StoragePoolHostVO host : hostPoolRecords) { - DeleteStoragePoolCommand deleteCmd = new DeleteStoragePoolCommand(pool); - final Answer answer = agentMgr.easySend(host.getHostId(), deleteCmd); - - if (answer != null && answer.getResult()) { - // if host is KVM hypervisor then send deleteStoragepoolcmd - // to all the kvm hosts. - if (HypervisorType.KVM != hType) { - break; - } - } else { - if (answer != null) { - logger.error("Failed to delete storage pool: " + answer.getResult()); - } - } - } - } - // delete the Elastistor volume at backend - deleteElastistorVolume(pool, storagePoolVO.isManaged()); - - return _dataStoreHelper.deletePrimaryDataStore(store); - } - - private void deleteElastistorVolume(StoragePool pool, boolean managed) { - - String poolid = pool.getUuid(); - boolean status; - - try { - status = ElastistorUtil.deleteElastistorTsm(poolid, managed); - } catch (Throwable e) { - throw new CloudRuntimeException("Failed to delete primary storage on elastistor" + e); - } - - if (status == true) { - logger.info("deletion of elastistor primary storage complete"); - } else { - logger.error("deletion of elastistor volume failed"); - } - - } - - private HypervisorType getHypervisorType(long hostId) { - HostVO host = _hostDao.findById(hostId); - if (host != null) - return host.getHypervisorType(); - return HypervisorType.None; - } - - @Override - public boolean migrateToObjectStore(DataStore store) { - return false; - } - - @Override - public void updateStoragePool(StoragePool storagePool, Map details) { - String capacityBytes = details.get(PrimaryDataStoreLifeCycle.CAPACITY_BYTES); - String capacityIops = details.get(PrimaryDataStoreLifeCycle.CAPACITY_IOPS); - - StoragePoolVO storagePoolVO = _storagePoolDao.findById(storagePool.getId()); - - try { - if(capacityBytes != null){ - long usedBytes = _capacityMgr.getUsedBytes(storagePoolVO); - - if (Long.parseLong(capacityBytes) < usedBytes) { - throw new CloudRuntimeException("Cannot reduce the number of bytes for this storage pool as it would lead to an insufficient number of bytes"); - } - - UpdateTsmStorageCmdResponse updateTsmStorageCmdResponse = ElastistorUtil.updateElastistorTsmStorage(capacityBytes,storagePool.getUuid()); - - if(updateTsmStorageCmdResponse.getStorage().getId() != null){ - // update the cloudstack db - _storagePoolDao.updateCapacityBytes(storagePool.getId(), Long.parseLong(capacityBytes)); - - logger.info("elastistor TSM storage successfully updated"); - }else{ - throw new CloudRuntimeException("Failed to update the storage of Elastistor TSM" + updateTsmStorageCmdResponse.toString()); - } - } - - if(capacityIops != null){ - - long usedIops = _capacityMgr.getUsedIops(storagePoolVO); - long capacity = Long.parseLong(capacityIops); - - if (capacity < usedIops) { - throw new CloudRuntimeException("Cannot reduce the number of IOPS for this storage pool as it would lead to an insufficient number of IOPS"); - } - - UpdateTsmCmdResponse updateTsmCmdResponse = ElastistorUtil.updateElastistorTsmIOPS(capacityIops,storagePool.getUuid()); - - if(updateTsmCmdResponse.getTsm(0).getUuid() != null){ - // update the cloudstack db - _storagePoolDao.updateCapacityIops(storagePool.getId(), capacity); - - logger.info("elastistor TSM IOPS successfully updated"); - - }else{ - throw new CloudRuntimeException("Failed to update the IOPS of Elastistor TSM" + updateTsmCmdResponse.toString()); - } - } - - } catch (Throwable e) { - throw new CloudRuntimeException("Failed to update the storage pool" + e); - } - - - } - -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorHostListener.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorHostListener.java deleted file mode 100644 index 3946acc35d9c..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorHostListener.java +++ /dev/null @@ -1,149 +0,0 @@ -// -// 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. -// - -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ModifyStoragePoolAnswer; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.alert.AlertManager; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.exception.CloudRuntimeException; - -public class ElastistorHostListener implements HypervisorHostListener { - protected Logger logger = LogManager.getLogger(getClass()); - @Inject - AgentManager agentMgr; - @Inject - DataStoreManager dataStoreMgr; - @Inject - AlertManager alertMgr; - @Inject - StoragePoolHostDao storagePoolHostDao; - @Inject - PrimaryDataStoreDao primaryStoreDao; - @Inject - PrimaryDataStoreDao storagePoolDao; - @Inject - HostDao _hostDao; - - @Override - public boolean hostAdded(long hostId) { - return true; - } - - @Override - public boolean hostConnect(long hostId, long poolId) { - StoragePool pool = (StoragePool) this.dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary); - - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(poolId, hostId); - HostVO host = _hostDao.findById(hostId); - - if (storagePoolHost == null) { - storagePoolHost = new StoragePoolHostVO(poolId, hostId, ""); - - storagePoolHostDao.persist(storagePoolHost); - } - - StoragePoolVO poolVO = storagePoolDao.findById(pool.getId()); - - if(poolVO.isManaged() && (host.getHypervisorType() != HypervisorType.KVM)){ - return true; - } - - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool); - final Answer answer = agentMgr.easySend(hostId, cmd); - - if (answer == null) { - throw new CloudRuntimeException(String.format("Unable to get an answer to the modify storage pool command for pool %s", poolVO)); - } - - if (!answer.getResult()) { - String msg = String.format("Unable to attach storage pool %s to the host %s", poolVO, host); - - alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST,pool.getDataCenterId(), pool.getPodId(), msg, msg); - - throw new CloudRuntimeException(String.format("Unable to establish connection from storage head to storage pool %s due to %s", poolVO, answer.getDetails())); - } - - assert (answer instanceof ModifyStoragePoolAnswer) : String.format("Well, now why won't you actually return the ModifyStoragePoolAnswer when it's ModifyStoragePoolCommand? Pool=%sHost=%s", poolVO, host); - - logger.info(String.format("Connection established between pool %s and host %s", pool, host)); - return true; - } - - @Override - public boolean hostDisconnected(long hostId, long poolId) { - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(poolId, hostId); - - if (storagePoolHost != null) { - storagePoolHostDao.deleteStoragePoolHostDetails(hostId, poolId); - } - return false; - } - - @Override - public boolean hostAboutToBeRemoved(long hostId) { - return true; - } - - @Override - public boolean hostRemoved(long hostId, long clusterId) { - return true; - } - - @Override - public boolean hostEnabled(long hostId) { - return true; - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorPrimaryDataStoreProvider.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorPrimaryDataStoreProvider.java deleted file mode 100644 index a6b1848da559..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/provider/ElastistorPrimaryDataStoreProvider.java +++ /dev/null @@ -1,143 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.framework.config.impl.ConfigurationVO; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.driver.ElastistorPrimaryDataStoreDriver; -import org.apache.cloudstack.storage.datastore.lifecycle.ElastistorPrimaryDataStoreLifeCycle; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil; - -import com.cloud.agent.AgentManager; -import com.cloud.alert.AlertManager; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.component.ComponentContext; - -/** - * This is the starting point of the elastistor storage plugin. This bean will - * be detected by Spring container & initialized. This will be one of the - * providers available via {@link DataStoreProviderManagerImpl} object. - */ -@Component -public class ElastistorPrimaryDataStoreProvider implements PrimaryDataStoreProvider { - - protected Logger logger = LogManager.getLogger(getClass()); - - // these classes will be injected by spring - private ElastistorPrimaryDataStoreLifeCycle lifecycle; - private PrimaryDataStoreDriver driver; - private HypervisorHostListener listener; - - - @Inject - AgentManager agentMgr; - @Inject - DataStoreManager dataStoreMgr; - @Inject - AlertManager alertMgr; - @Inject - StoragePoolHostDao storagePoolHostDao; - @Inject - PrimaryDataStoreDao primaryStoreDao; - @Inject - ConfigurationDao configurationDao; - - @Override - public String getName() { - return ElastistorUtil.ES_PROVIDER_NAME; - } - - @Override - public DataStoreLifeCycle getDataStoreLifeCycle() { - return lifecycle; - } - - @Override - public PrimaryDataStoreDriver getDataStoreDriver() { - return driver; - } - - @Override - public HypervisorHostListener getHostListener() { - return listener; - } - - @Override - public boolean configure(Map params) { - - logger.info("Will configure elastistor's lifecycle, driver, listener & global configurations."); - - lifecycle = ComponentContext.inject(ElastistorPrimaryDataStoreLifeCycle.class); - driver = ComponentContext.inject(ElastistorPrimaryDataStoreDriver.class); - listener = ComponentContext.inject(ElastistorHostListener.class); - - // insert new cloudbyte global config to the configuration table - setCloudbyteGlobalConfiguration(); - - // set the injected configuration object in elastistor util class too!!! - ElastistorUtil.setConfigurationDao(configurationDao); - - logger.info("Successfully configured elastistor's lifecycle, driver, listener & global configurations."); - - return true; - } - - @Override - public Set getTypes() { - Set types = new HashSet(); - - types.add(DataStoreProviderType.PRIMARY); - - return types; - } - - private void setCloudbyteGlobalConfiguration() { - - if (configurationDao.findByName("cloudbyte.management.ip") == null) { - ConfigurationVO managementIP = new ConfigurationVO("Advanced", "DEFAULT", "management-server", - "cloudbyte.management.ip", null, "configure the cloudbyte elasticenter management IP"); - - configurationDao.persist(managementIP); - } - - if (configurationDao.findByName("cloudbyte.management.apikey") == null) { - ConfigurationVO managementApiKey = new ConfigurationVO("Advanced", "DEFAULT", "management-server", - "cloudbyte.management.apikey", null, "configure the cloudbyte elasticenter management API KEY"); - - configurationDao.persist(managementApiKey); - } - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorUtil.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorUtil.java deleted file mode 100644 index 603908e024ca..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorUtil.java +++ /dev/null @@ -1,2608 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import com.cloud.agent.api.Answer; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.utils.Pair; -import com.cloud.utils.exception.CloudRuntimeException; -import com.google.gson.Gson; -import com.google.gson.annotations.SerializedName; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.utils.security.SSLUtils; -import org.apache.cloudstack.utils.security.SecureSSLSocketFactory; -import org.apache.http.auth.InvalidCredentialsException; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientResponse; - -import javax.naming.ServiceUnavailableException; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriBuilder; -import java.net.ConnectException; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class ElastistorUtil { - - protected static Logger LOGGER = LogManager.getLogger(ElastistorUtil.class); - - private static ConfigurationDao configurationDao; - - public static ConfigurationDao getConfigurationDao() { - return configurationDao; - } - - public static void setConfigurationDao(ConfigurationDao configurationDao) { - ElastistorUtil.configurationDao = configurationDao; - } - - /** - * Elastistor REST API Param Keys. These should match exactly with the - * elastistor API commands' params. - */ - public static final String REST_PARAM_COMMAND = "command"; - public static final String REST_PARAM_APIKEY = "apikey"; - public static final String REST_PARAM_KEYWORD = "keyword"; - public static final String REST_PARAM_ID = "id"; - public static final String REST_PARAM_QUOTA_SIZE = "quotasize"; - public static final String REST_PARAM_READONLY = "readonly"; - public static final String REST_PARAM_RESPONSE = "response"; - public static final String REST_PARAM_POOLID = "poolid"; - public static final String REST_PARAM_ACCOUNTID = "accountid"; - public static final String REST_PARAM_GATEWAY = "router"; - public static final String REST_PARAM_SUBNET = "subnet"; - public static final String REST_PARAM_INTERFACE = "tntinterface"; - public static final String REST_PARAM_IPADDRESS = "ipaddress"; - public static final String REST_PARAM_JOBID = "jobId"; - public static final String REST_PARAM_FORECEDELETE = "forcedelete"; - public static final String REST_PARAM_TSM_THROUGHPUT = "totalthroughput"; - public static final String REST_PARAM_NAME = "name"; - public static final String REST_PARAM_NOOFCOPIES = "noofcopies"; - public static final String REST_PARAM_RECORDSIZE = "recordsize"; - public static final String REST_PARAM_TOTALIOPS = "totaliops"; - public static final String REST_PARAM_LATENCY = "latency"; - public static final String REST_PARAM_BLOCKSIZE = "blocksize"; - public static final String REST_PARAM_GRACEALLOWED = "graceallowed"; - public static final String REST_PARAM_IOPS = "iops"; - public static final String REST_PARAM_THROUGHPUT = "throughput"; - public static final String REST_PARAM_MEMLIMIT = "memlimit"; - public static final String REST_PARAM_NETWORKSPEED = "networkspeed"; - public static final String REST_PARAM_TSMID = "tsmid"; - public static final String REST_PARAM_DATASETID = "datasetid"; - public static final String REST_PARAM_QOSGROUPID = "qosgroupid"; - public static final String REST_PARAM_DEDUPLICATION = "deduplication"; - public static final String REST_PARAM_COMPRESSION = "compression"; - public static final String REST_PARAM_SYNC = "sync"; - public static final String REST_PARAM_MOUNTPOINT = "mountpoint"; - public static final String REST_PARAM_CASESENSITIVITY = "casesensitivity"; - public static final String REST_PARAM_UNICODE = "unicode"; - public static final String REST_PARAM_PROTOCOLTYPE = "protocoltype"; - public static final String REST_PARAM_AUTHNETWORK = "authnetwork"; - public static final String REST_PARAM_MAPUSERSTOROOT = "mapuserstoroot"; - public static final String REST_PARAM_STORAGEID = "storageid"; - public static final String REST_PARAM_TPCONTROL = "tpcontrol"; - public static final String REST_PARAM_IOPSCONTROL = "iopscontrol"; - - /** - * Constants related to elastistor which are persisted in cloudstack - * databases as keys. - */ - public static final String ES_SUBNET = "essubnet"; - public static final String ES_INTERFACE = "estntinterface"; - public static final String ES_GATEWAY = "esdefaultgateway"; - public static final String ES_PROVIDER_NAME = "CloudByte"; - public static final String ES_ACCOUNT_ID = "esAccountId"; - public static final String ES_POOL_ID = "esPoolId"; - public static final String ES_ACCOUNT_NAME = "esAccountName"; - public static final String ES_STORAGE_IP = "esStorageIp"; - public static final String ES_STORAGE_PORT = "esStoragePort"; - public static final String ES_STORAGE_TYPE = "esStorageType"; - public static final String ES_MANAGEMENT_IP = "esMgmtIp"; - public static final String ES_MANAGEMENT_PORT = "esMgmtPort"; - public static final String ES_API_KEY = "esApiKey"; - public static final String ES_VOLUME_ID = "esVolumeId"; - public static final String ES_VOLUME_GROUP_ID = "esVolumeGroupId"; - public static final String ES_FILE_SYSTEM_ID = "esFilesystemId"; - - /** - * Values from configuration that are required for every invocation of - * ElastiCenter API. These might in turn be saved as DB updates along with - * above keys. - */ - public static String s_esIPVAL = ""; - public static String s_esAPIKEYVAL = ""; - public static String s_esACCOUNTIDVAL = ""; - public static String s_esPOOLIDVAL = ""; - public static String s_esSUBNETVAL = ""; - public static String s_esINTERFACEVAL = ""; - public static String s_esGATEWAYVAL = ""; - - /** - * hardcoded constants for elastistor api calls. - */ - private static final String ES_NOOFCOPIES_VAL = "1"; - private static final String ES_BLOCKSIZE_VAL = "4K"; - private static final String ES_LATENCY_VAL = "15"; - private static final String ES_GRACEALLOWED_VAL = "false"; - private static final String ES_MEMLIMIT_VAL = "0"; - private static final String ES_NETWORKSPEED_VAL = "0"; - private static final String ES_DEDUPLICATION_VAL = "off"; - private static final String ES_COMPRESSION_VAL = "off"; - private static final String ES_CASESENSITIVITY_VAL = "sensitive"; - private static final String ES_READONLY_VAL = "off"; - private static final String ES_UNICODE_VAL = "off"; - private static final String ES_AUTHNETWORK_VAL = "all"; - private static final String ES_MAPUSERSTOROOT_VAL = "yes"; - private static final String ES_SYNC_VAL = "always"; - private static final String ES_TPCONTROL_VAL = "false"; - private static final String ES_IOPSCONTROL_VAL = "true"; - - /** - * Private constructor s.t. its never instantiated. - */ - private ElastistorUtil() { - - } - - /** - * This intializes a new jersey restclient for http call with elasticenter - */ - public static ElastiCenterClient getElastistorRestClient() { - ElastiCenterClient restclient = null; - try { - String ip = getConfigurationDao().getValue("cloudbyte.management.ip"); - String apikey = getConfigurationDao().getValue("cloudbyte.management.apikey"); - - if (ip == null) { - throw new CloudRuntimeException("set the value of cloudbyte.management.ip in global settings"); - } - if (apikey == null) { - throw new CloudRuntimeException("set the value of cloudbyte.management.apikey in global settings"); - } - - restclient = new ElastiCenterClient(ip, apikey); - - } catch (InvalidCredentialsException e) { - throw new CloudRuntimeException("InvalidCredentialsException:" + e.getMessage(), e); - } catch (InvalidParameterValueException e) { - throw new CloudRuntimeException("InvalidParameterValueException:" + e.getMessage(), e); - } catch (SSLHandshakeException e) { - throw new CloudRuntimeException("SSLHandshakeException:" + e.getMessage(), e); - } catch (ServiceUnavailableException e) { - throw new CloudRuntimeException("ServiceUnavailableException:" + e.getMessage(), e); - } - return restclient; - } - - public static void setElastistorApiKey(String value) { - s_esAPIKEYVAL = value; - } - - public static void setElastistorManagementIp(String value) { - s_esIPVAL = value; - } - - public static void setElastistorPoolId(String value) { - s_esPOOLIDVAL = value; - } - - public static void setElastistorAccountId(String value) { - s_esACCOUNTIDVAL = value; - } - - public static void setElastistorGateway(String value) { - s_esGATEWAYVAL = value; - } - - public static void setElastistorInterface(String value) { - s_esINTERFACEVAL = value; - } - - public static void setElastistorSubnet(String value) { - s_esSUBNETVAL = value; - } - - /** - * This creates a new Account in Elasticenter for the given Domain Name. - * - * @return - */ - public static String getElastistorAccountId(String domainName) throws Throwable { - - ListAccountResponse listAccountResponse = ListElastistorAccounts(); - - if (listAccountResponse.getAccounts().getCount() != 0) { - int i; - // check whether an account in elasticenter with given Domain name is - // already present in the list of accounts - for (i = 0; i < listAccountResponse.getAccounts().getCount(); i++) { - if (domainName.equals(listAccountResponse.getAccounts().getAccount(i).getName())) { - return listAccountResponse.getAccounts().getAccount(i).getUuid(); - } - } - - // if no account matches the give Domain Name , create one with the - // Domain name - CreateAccountResponse createAccountResponse = createElastistorAccount(domainName); - return createAccountResponse.getAccount().getUuid(); - - } else { - // if no account is present in the elasticenter create one - CreateAccountResponse createAccountResponse = createElastistorAccount(domainName); - return createAccountResponse.getAccount().getUuid(); - } - } - - /** - * This creates a new tenant storage machine(TSM) for the given storagepool - * ip in elastistor. - * - * @param domainName - * TODO - */ - public static Tsm createElastistorTsm(String storagePoolName, String storageIp, Long capacityBytes, Long capacityIops, String domainName) throws Throwable { - - String totalthroughput = String.valueOf(capacityIops * 4); - String totaliops = String.valueOf(capacityIops); - - String quotasize = convertCapacityBytes(capacityBytes); - - CreateTsmCmd createTsmCmd = new CreateTsmCmd(); - - if (null != ElastistorUtil.s_esACCOUNTIDVAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ACCOUNTID, domainName); - if (null != totalthroughput) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_TSM_THROUGHPUT, totalthroughput); - if (null != ElastistorUtil.s_esPOOLIDVAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_POOLID, ElastistorUtil.s_esPOOLIDVAL); - if (null != storagePoolName) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_NAME, storagePoolName); - if (null != quotasize) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_QUOTA_SIZE, quotasize); - if (null != storageIp) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_IPADDRESS, storageIp); - if (null != ElastistorUtil.s_esSUBNETVAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_SUBNET, ElastistorUtil.s_esSUBNETVAL); - if (null != ElastistorUtil.s_esGATEWAYVAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_GATEWAY, ElastistorUtil.s_esGATEWAYVAL); - if (null != ElastistorUtil.s_esINTERFACEVAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_INTERFACE, ElastistorUtil.s_esINTERFACEVAL); - if (null != ElastistorUtil.ES_NOOFCOPIES_VAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_NOOFCOPIES, ElastistorUtil.ES_NOOFCOPIES_VAL); - if (null != ElastistorUtil.ES_BLOCKSIZE_VAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_RECORDSIZE, ElastistorUtil.ES_BLOCKSIZE_VAL); - if (null != totaliops) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_TOTALIOPS, totaliops); - if (null != ElastistorUtil.ES_LATENCY_VAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_LATENCY, ElastistorUtil.ES_LATENCY_VAL); - if (null != ElastistorUtil.ES_BLOCKSIZE_VAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_BLOCKSIZE, ElastistorUtil.ES_BLOCKSIZE_VAL); - if (null != ElastistorUtil.ES_GRACEALLOWED_VAL) - createTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_GRACEALLOWED, ElastistorUtil.ES_GRACEALLOWED_VAL); - - CreateTsmCmdResponse createTsmCmdResponse; - Tsm tsm = null; - try { - createTsmCmdResponse = (CreateTsmCmdResponse) getElastistorRestClient().executeCommand(createTsmCmd); - - if (createTsmCmdResponse.getJobid() == null) { - throw new CloudRuntimeException("tsm creation failed , contact elatistor admin"); - } else { - tsm = queryAsyncTsmJobResult(createTsmCmdResponse.getJobid()); - if (tsm == null) { - throw new CloudRuntimeException("tsm queryAsync failed , contact elatistor admin"); - } - } - return tsm; - } catch (Exception e) { - throw new CloudRuntimeException("tsm creation failed , contact elatistor admin" + e.toString()); - } - - } - - /** - * This creates the specified volume on the created tsm. - */ - public static FileSystem createElastistorVolume(String volumeName, String tsmid, Long capacityBytes, Long capacityIops, String protocoltype, String mountpoint) throws Throwable { - - String datasetid; - String qosgroupid; - String VolumeName = volumeName; - String totaliops = String.valueOf(capacityIops); - String totalthroughput = "0"; - - String quotasize = convertCapacityBytes(capacityBytes); - - AddQosGroupCmd addQosGroupCmd = new AddQosGroupCmd(); - - ListTsmsResponse listTsmsResponse = listTsm(tsmid); - - tsmid = listTsmsResponse.getTsms().getTsm(0).getUuid(); - datasetid = listTsmsResponse.getTsms().getTsm(0).getDatasetid(); - - if (null != VolumeName) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_NAME, "QOS_" + VolumeName); - if (null != totaliops) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_IOPS, totaliops); - if (null != ElastistorUtil.ES_LATENCY_VAL) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_LATENCY, ElastistorUtil.ES_LATENCY_VAL); - if (null != totalthroughput) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_THROUGHPUT, totalthroughput); - if (null != ElastistorUtil.ES_MEMLIMIT_VAL) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_MEMLIMIT, ElastistorUtil.ES_MEMLIMIT_VAL); - if (null != ElastistorUtil.ES_NETWORKSPEED_VAL) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_NETWORKSPEED, ElastistorUtil.ES_NETWORKSPEED_VAL); - if (null != tsmid) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_TSMID, tsmid); - if (null != datasetid) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_DATASETID, datasetid); - if (null != ElastistorUtil.ES_GRACEALLOWED_VAL) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_GRACEALLOWED, ElastistorUtil.ES_GRACEALLOWED_VAL); - if (null != ElastistorUtil.ES_IOPSCONTROL_VAL) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_IOPSCONTROL, ElastistorUtil.ES_IOPSCONTROL_VAL); - if (null != ElastistorUtil.ES_TPCONTROL_VAL) - addQosGroupCmd.putCommandParameter(ElastistorUtil.REST_PARAM_TPCONTROL, ElastistorUtil.ES_TPCONTROL_VAL); - - AddQosGroupCmdResponse addQosGroupCmdResponse = (AddQosGroupCmdResponse) getElastistorRestClient().executeCommand(addQosGroupCmd); - - if (addQosGroupCmdResponse.getQoSGroup().getUuid() == null) { - - throw new CloudRuntimeException("adding qos group failed , contact elatistor admin"); - - } - - else { - - CreateVolumeCmd createVolumeCmd = new CreateVolumeCmd(); - - qosgroupid = addQosGroupCmdResponse.getQoSGroup().getUuid(); - - // if (null != - // ElastistorUtil.s_esACCOUNTIDVAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ACCOUNTID,ElastistorUtil.s_esACCOUNTIDVAL); - if (null != qosgroupid) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_QOSGROUPID, qosgroupid); - if (null != tsmid) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_TSMID, tsmid); - // if (null != - // ElastistorUtil.s_esPOOLIDVAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_POOLID,ElastistorUtil.s_esPOOLIDVAL); - if (null != VolumeName) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_NAME, VolumeName); - if (null != quotasize) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_QUOTA_SIZE, quotasize); - if (protocoltype.equalsIgnoreCase("nfs")) { - if (null != ElastistorUtil.ES_BLOCKSIZE_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_BLOCKSIZE, ElastistorUtil.ES_BLOCKSIZE_VAL); - if (null != ElastistorUtil.ES_BLOCKSIZE_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_RECORDSIZE, ElastistorUtil.ES_BLOCKSIZE_VAL); - } else { - if (null != ElastistorUtil.ES_BLOCKSIZE_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_BLOCKSIZE, "512B"); - if (null != ElastistorUtil.ES_BLOCKSIZE_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_RECORDSIZE, "512B"); - } - if (null != ElastistorUtil.ES_DEDUPLICATION_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_DEDUPLICATION, ElastistorUtil.ES_DEDUPLICATION_VAL); - if (null != ElastistorUtil.ES_SYNC_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_SYNC, ElastistorUtil.ES_SYNC_VAL); - if (null != ElastistorUtil.ES_COMPRESSION_VAL) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_COMPRESSION, ElastistorUtil.ES_COMPRESSION_VAL); - // if (null != - // ElastistorUtil.ES_NOOFCOPIES_VAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_NOOFCOPIES, - // ElastistorUtil.ES_NOOFCOPIES_VAL); - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_MOUNTPOINT, mountpoint); - // if (null != - // ElastistorUtil.ES_CASESENSITIVITY_VAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_CASESENSITIVITY, - // ElastistorUtil.ES_CASESENSITIVITY_VAL); - // if (null != - // ElastistorUtil.ES_READONLY_VAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_READONLY, - // ElastistorUtil.ES_READONLY_VAL); - if (null != datasetid) - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_DATASETID, datasetid); - // if (null != - // ElastistorUtil.ES_UNICODE_VAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_UNICODE, - // ElastistorUtil.ES_UNICODE_VAL); - createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_PROTOCOLTYPE, protocoltype); - // if (null != - // ElastistorUtil.ES_AUTHNETWORK_VAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_AUTHNETWORK, - // ElastistorUtil.ES_AUTHNETWORK_VAL); - // if (null != - // ElastistorUtil.ES_MAPUSERSTOROOT_VAL)createVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_MAPUSERSTOROOT, - // ElastistorUtil.ES_MAPUSERSTOROOT_VAL); - - CreateVolumeCmdResponse createVolumeCmdResponse; - FileSystem volume = null; - FileSystem fileSystem = null; - - try { - createVolumeCmdResponse = (CreateVolumeCmdResponse) getElastistorRestClient().executeCommand(createVolumeCmd); - - if (createVolumeCmdResponse.getJobid() == null) { - - throw new CloudRuntimeException("creating volume failed , contact elatistor admin"); - - } else { - volume = queryAsyncVolumeJobResult(createVolumeCmdResponse.getJobid()); - if (volume == null) { - throw new CloudRuntimeException("tsm queryAsync failed , contact elatistor admin"); - } else { - if (protocoltype.equalsIgnoreCase("nfs")) { - fileSystem = updateNfsService(volume.getUuid()); - - } else { - fileSystem = updateIscsiService(volume.getUuid()); - } - } - } - return fileSystem; - } catch (Exception e) { - throw new CloudRuntimeException("creating volume failed , contact elatistor admin", e); - } - - } - - } - - public static FileSystem updateNfsService(String volumeid) throws Throwable { - - FileSystem fileSystem = null; - - String datasetid = updateElastistorNfsVolume(volumeid); - - if (datasetid == null) { - throw new CloudRuntimeException("Updating Nfs Volume Failed"); - } else { - - fileSystem = listVolume(datasetid); - if (fileSystem == null) { - throw new CloudRuntimeException("Volume Creation failed : List Filesystem failed"); - } - } - return fileSystem; - - } - - public static FileSystem updateIscsiService(String volumeid) throws Throwable { - - Volumeiscsioptions volumeiscsioptions = null; - FileSystem fileSystem = null; - String accountId; - - fileSystem = listVolume(volumeid); - - accountId = fileSystem.getAccountid(); - - volumeiscsioptions = updateElastistorIscsiVolume(volumeid, accountId); - - if (volumeiscsioptions == null) { - throw new CloudRuntimeException("Updating Iscsi Volume Failed"); - } else { - - fileSystem = listVolume(volumeiscsioptions.getVolumeid()); - if (fileSystem == null) { - throw new CloudRuntimeException("Volume Creation failed : List Filesystem failed"); - } - } - return fileSystem; - - } - - public static String updateElastistorNfsVolume(String volumeid) throws Throwable { - - NfsServiceCmd nfsServiceCmd = new NfsServiceCmd(); - - nfsServiceCmd.putCommandParameter("datasetid", volumeid); - nfsServiceCmd.putCommandParameter("authnetwork", "all"); - nfsServiceCmd.putCommandParameter("managedstate", "true"); - nfsServiceCmd.putCommandParameter("alldirs", "yes"); - nfsServiceCmd.putCommandParameter("mapuserstoroot", "yes"); - nfsServiceCmd.putCommandParameter("readonly", "no"); - - NfsServiceResponse nfsServiceResponse = (NfsServiceResponse) getElastistorRestClient().executeCommand(nfsServiceCmd); - - if (nfsServiceResponse.getNfsService().getUuid() != null) { - - UpdateControllerCmd controllerCmd = new UpdateControllerCmd(); - - controllerCmd.putCommandParameter("nfsid", nfsServiceResponse.getNfsService().getUuid()); - controllerCmd.putCommandParameter("type", "configurenfs"); - controllerCmd.putCommandParameter("id", nfsServiceResponse.getNfsService().getControllerid()); - - UpdateControllerResponse controllerResponse = (UpdateControllerResponse) getElastistorRestClient().executeCommand(controllerCmd); - - if (controllerResponse.getController().getUuid() != null) { - LOGGER.info("updated nfs service to ALL"); - return nfsServiceResponse.getNfsService().getDatasetid(); - } else { - throw new CloudRuntimeException("Updating Nfs Volume Failed"); - } - - } - return null; - } - - public static Volumeiscsioptions updateElastistorIscsiVolume(String volumeid, String accountid) throws Throwable { - - // now listing the iscsi volume service group to get iscsi id - - ListVolumeiSCSIServiceCmd listVolumeiSCSIServiceCmd = new ListVolumeiSCSIServiceCmd(); - - if (null != volumeid) - listVolumeiSCSIServiceCmd.putCommandParameter(ElastistorUtil.REST_PARAM_STORAGEID, volumeid); - - ListVolumeiSCSIServiceResponse volumeiSCSIServiceResponse = (ListVolumeiSCSIServiceResponse) getElastistorRestClient().executeCommand(listVolumeiSCSIServiceCmd); - - String iscsiId = volumeiSCSIServiceResponse.getIscsiVolume().getIscsiVolume(0).getUuid(); - String AG_Id = volumeiSCSIServiceResponse.getIscsiVolume().getIscsiVolume(0).getAg_id(); - - // now listing the initiator group to get initiator id - - ListiSCSIInitiatorCmd initiatorCmd = new ListiSCSIInitiatorCmd(); - - if (null != volumeid) - initiatorCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ACCOUNTID, accountid); - - ListiSCSIInitiatorResponse initiatorResponse = (ListiSCSIInitiatorResponse) getElastistorRestClient().executeCommand(initiatorCmd); - - String IG_Id; - if (initiatorResponse.getIInitiator().getInterface(0).getInitiatorgroup().equalsIgnoreCase("ALL")) { - IG_Id = initiatorResponse.getIInitiator().getInterface(0).getUuid(); - } else { - IG_Id = initiatorResponse.getIInitiator().getInterface(1).getUuid(); - } - - if (iscsiId != null) { - - UpdateVolumeiSCSIServiceCmd updateVolumeiSCSIServiceCmd = new UpdateVolumeiSCSIServiceCmd(); - - if (null != volumeid) - updateVolumeiSCSIServiceCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ID, iscsiId); - if (null != volumeid) - updateVolumeiSCSIServiceCmd.putCommandParameter("status", "true"); - if (null != volumeid) - updateVolumeiSCSIServiceCmd.putCommandParameter("igid", IG_Id); - if (null != volumeid) - updateVolumeiSCSIServiceCmd.putCommandParameter("authgroupid", AG_Id); - if (null != volumeid) - updateVolumeiSCSIServiceCmd.putCommandParameter("initialdigest", "Auto"); - if (null != volumeid) - updateVolumeiSCSIServiceCmd.putCommandParameter("queuedepth", "32"); - - UpdateVolumeiSCSIServiceCmdResponse cmdResponse = (UpdateVolumeiSCSIServiceCmdResponse) getElastistorRestClient().executeCommand(updateVolumeiSCSIServiceCmd); - - if (cmdResponse.getVolumeiscsioptions().getVolumeid() == null) { - throw new CloudRuntimeException("Updating Iscsi Volume Failed"); - } - return cmdResponse.getVolumeiscsioptions(); - } - return null; - - } - - /** - * This deletes both the volume and the tsm in elastistor. - */ - public static boolean deleteElastistorTsm(String tsmid, boolean managed) throws Throwable { - - if (!managed) { - - LOGGER.info("elastistor pool is NOT a managed storage , hence deleting the volume then tsm"); - - String esvolumeid = null; - ListTsmsResponse listTsmsResponse = listTsm(tsmid); - - if (listTsmsResponse.getTsmsCount() != 0) { - - if (listTsmsResponse.getTsms().getTsm(0).checkvolume()) { - esvolumeid = listTsmsResponse.getTsms().getTsm(0).getVolumeProperties(0).getid(); - DeleteVolumeResponse deleteVolumeResponse = deleteVolume(esvolumeid, null); - - if (deleteVolumeResponse != null) { - String jobid = deleteVolumeResponse.getJobId(); - int jobstatus = queryAsyncJobResult(jobid); - - if (jobstatus == 1) { - LOGGER.info("elastistor volume successfully deleted"); - } else { - LOGGER.info("now farce deleting the volume"); - - while (jobstatus != 1) { - DeleteVolumeResponse deleteVolumeResponse1 = deleteVolume(esvolumeid, "true"); - - if (deleteVolumeResponse1 != null) { - String jobid1 = deleteVolumeResponse1.getJobId(); - jobstatus = queryAsyncJobResult(jobid1); - } - } - LOGGER.info("elastistor volume successfully deleted"); - } - } - } else { - LOGGER.info("no volume present in on the given tsm"); - } - - } - } - - LOGGER.info("now trying to delete elastistor tsm"); - - if (tsmid != null) { - DeleteTsmCmd deleteTsmCmd = new DeleteTsmCmd(); - deleteTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ID, tsmid); - DeleteTsmResponse deleteTsmResponse = (DeleteTsmResponse) getElastistorRestClient().executeCommand(deleteTsmCmd); - - if (deleteTsmResponse != null) { - String jobstatus = deleteTsmResponse.getJobStatus(); - - if (jobstatus.equalsIgnoreCase("true")) { - LOGGER.info("deletion of elastistor tsm successful"); - return true; - } else { - LOGGER.info("failed to delete elastistor tsm"); - return false; - } - } else { - LOGGER.info("elastistor tsm id not present"); - } - } - LOGGER.info("tsm id is null"); - return false; - } - - public static boolean deleteElastistorVolume(String esvolumeid) throws Throwable { - - FileSystem fileSystem = listVolume(esvolumeid); - - if (fileSystem != null) { - DeleteVolumeResponse deleteVolumeResponse = deleteVolume(esvolumeid, null); - - if (deleteVolumeResponse != null) { - String jobid = deleteVolumeResponse.getJobId(); - int jobstatus = queryAsyncJobResult(jobid); - - if (jobstatus == 1) { - LOGGER.info("elastistor volume successfully deleted"); - return true; - } else { - LOGGER.info("now force deleting the volume"); - - while (jobstatus != 1) { - DeleteVolumeResponse deleteVolumeResponse1 = deleteVolume(esvolumeid, "true"); - - if (deleteVolumeResponse1 != null) { - String jobid1 = deleteVolumeResponse1.getJobId(); - jobstatus = queryAsyncJobResult(jobid1); - } - } - LOGGER.info("elastistor volume successfully deleted"); - return true; - } - } else { - LOGGER.info("the given volume is not present on elastistor, datasetrespone is NULL"); - return false; - } - } else { - LOGGER.info("the given volume is not present on elastistor"); - return false; - } - - } - - /** - * This give a json response containing the list of Interface's in - * elastistor. - */ - - public static ListInterfacesResponse ListElastistorInterfaces(String controllerid) throws Throwable { - - ListInterfacesCmd listInterfacesCmd = new ListInterfacesCmd(); - listInterfacesCmd.putCommandParameter("controllerid", controllerid); - - ListInterfacesResponse interfacesResponse = (ListInterfacesResponse) getElastistorRestClient().executeCommand(listInterfacesCmd); - - if (interfacesResponse != null && interfacesResponse.getInterfaces() != null) { - return interfacesResponse; - } else { - throw new CloudRuntimeException("There are no elastistor interfaces."); - } - } - - /** - * This give a json response containing the list of Accounts's in - * elastistor. - */ - - public static CreateAccountResponse createElastistorAccount(String domainName) throws Throwable { - - CreateAccountCmd createAccountCmd = new CreateAccountCmd(); - - createAccountCmd.putCommandParameter("name", domainName); - CreateAccountResponse createAccountResponse = (CreateAccountResponse) getElastistorRestClient().executeCommand(createAccountCmd); - - if (createAccountResponse != null) { - return createAccountResponse; - } else { - throw new CloudRuntimeException("Creating Elastistor Account failed"); - } - - } - - /** - * This give a json response containing the list of Accounts's in - * elastistor. - */ - - public static ListAccountResponse ListElastistorAccounts() throws Throwable { - - ListAccountsCmd listAccountsCmd = new ListAccountsCmd(); - - ListAccountResponse accountResponse = (ListAccountResponse) getElastistorRestClient().executeCommand(listAccountsCmd); - - if (accountResponse != null) { - return accountResponse; - } else { - throw new CloudRuntimeException("List Elastistor Account failed"); - } - - } - - /** - * This give a json response containing the list of Pool's in elastistor. - */ - - public static ListPoolsResponse ListElastistorPools() throws Throwable { - - ListPoolsCmd listPoolsCmd = new ListPoolsCmd(); - - ListPoolsResponse listPoolsResponse = (ListPoolsResponse) getElastistorRestClient().executeCommand(listPoolsCmd); - - if (listPoolsResponse != null) { - return listPoolsResponse; - } else { - throw new CloudRuntimeException("List Elastistor pool failed"); - } - - } - - /** - * This give a json response containing the list of tsm's in elastistor. - */ - private static ListTsmsResponse listTsm(String uuid) throws Throwable { - - ListTsmCmd listTsmCmd = new ListTsmCmd(); - - listTsmCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ID, uuid); - - ListTsmsResponse listTsmsResponse = (ListTsmsResponse) getElastistorRestClient().executeCommand(listTsmCmd); - - return listTsmsResponse; - } - - /** - * This give a json response containing the list of Volume in elastistor. - */ - public static FileSystem listVolume(String uuid) throws Throwable { - - ListFileSystemCmd listFileSystemCmd = new ListFileSystemCmd(); - - listFileSystemCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ID, uuid); - - ListFileSystemResponse listFileSystemResponse = (ListFileSystemResponse) getElastistorRestClient().executeCommand(listFileSystemCmd); - - return listFileSystemResponse.getFilesystems().getFileSystem(0); - } - - private static DeleteVolumeResponse deleteVolume(String esvolumeid, String forcedelete) throws Throwable { - - DeleteVolumeCmd deleteVolumeCmd = new DeleteVolumeCmd(); - - deleteVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_ID, esvolumeid); - deleteVolumeCmd.putCommandParameter(ElastistorUtil.REST_PARAM_FORECEDELETE, forcedelete); - - DeleteVolumeResponse deleteVolumeResponse = (DeleteVolumeResponse) getElastistorRestClient().executeCommand(deleteVolumeCmd); - - return deleteVolumeResponse; - } - - private static int queryAsyncJobResult(String jobid) throws Throwable { - - QueryAsyncJobResultCmd asyncJobResultCmd = new QueryAsyncJobResultCmd(); - ElastiCenterClient restclient = getElastistorRestClient(); - - asyncJobResultCmd.putCommandParameter(ElastistorUtil.REST_PARAM_JOBID, jobid); - - QueryAsyncJobResultResponse asyncJobResultResponse = (QueryAsyncJobResultResponse) restclient.executeCommand(asyncJobResultCmd); - - if (asyncJobResultResponse != null) { - int jobstatus = asyncJobResultResponse.getAsync().getJobStatus(); - - while (jobstatus == 0) { - - QueryAsyncJobResultResponse jobResultResponse = (QueryAsyncJobResultResponse) restclient.executeCommand(asyncJobResultCmd); - - jobstatus = jobResultResponse.getAsync().getJobStatus(); - } - return jobstatus; - } - return 0; - - } - - private static Tsm queryAsyncTsmJobResult(String jobid) throws Throwable { - - QueryAsyncJobResultCmd asyncJobResultCmd = new QueryAsyncJobResultCmd(); - ElastiCenterClient restclient = getElastistorRestClient(); - - asyncJobResultCmd.putCommandParameter(ElastistorUtil.REST_PARAM_JOBID, jobid); - - QueryAsyncJobResultResponse asyncJobResultResponse = (QueryAsyncJobResultResponse) restclient.executeCommand(asyncJobResultCmd); - - if (asyncJobResultResponse != null) { - int jobstatus = asyncJobResultResponse.getAsync().getJobStatus(); - Tsm tsm = null; - while (jobstatus == 0) { - - asyncJobResultResponse = (QueryAsyncJobResultResponse) restclient.executeCommand(asyncJobResultCmd); - - jobstatus = asyncJobResultResponse.getAsync().getJobStatus(); - - } - if (jobstatus == 1) { - tsm = asyncJobResultResponse.getAsync().getJobResult().getTsm(); - return tsm; - } - } - return null; - - } - - private static FileSystem queryAsyncVolumeJobResult(String jobid) throws Throwable { - - QueryAsyncJobResultCmd asyncJobResultCmd = new QueryAsyncJobResultCmd(); - ElastiCenterClient restclient = getElastistorRestClient(); - - asyncJobResultCmd.putCommandParameter(ElastistorUtil.REST_PARAM_JOBID, jobid); - - QueryAsyncJobResultResponse asyncJobResultResponse = (QueryAsyncJobResultResponse) restclient.executeCommand(asyncJobResultCmd); - - if (asyncJobResultResponse != null) { - int jobstatus = asyncJobResultResponse.getAsync().getJobStatus(); - FileSystem volume = null; - while (jobstatus == 0) { - - asyncJobResultResponse = (QueryAsyncJobResultResponse) restclient.executeCommand(asyncJobResultCmd); - - jobstatus = asyncJobResultResponse.getAsync().getJobStatus(); - - } - if (jobstatus == 1) { - volume = asyncJobResultResponse.getAsync().getJobResult().getVolume(); - return volume; - } - } - return null; - - } - - /** - * this method converts the long capacitybytes to string format, which is - * feasible for elastistor rest api 214748364800 = 200G. - */ - private static String convertCapacityBytes(Long capacityBytes) { - - if ((1099511627776L) > capacityBytes && (capacityBytes > (1073741824))) { - return (String.valueOf(capacityBytes / (1024 * 1024 * 1024)) + "G"); - } else { - int temp1 = (int) (capacityBytes / (1024 * 1024 * 1024)); - int temp2 = temp1 / 1024; - return (String.valueOf(temp2) + "T"); - } - } - - static interface ElastiCenterCommand { - - /* - * Returns the command string to be sent to the ElastiCenter - */ - public String getCommandName(); - - /* - * Utility method to allow the client to validate the input parameters - * before sending to the ElastiCenter. - * - * This command will be executed by the ElastiCenterClient only this - * method returns true. - */ - public boolean validate(); - - /* - * Returns the query parameters that have to be passed to execute the - * command. - * - * Returns null if there are query parameters associated with the - * command - */ - public List> getCommandParameters(); - - /* - * Adds new key-value pair to the query parameters lists. - */ - public void putCommandParameter(String key, String value); - - /* - * Return an instance of the Response Object Type. - * - * Return null if no response is expected. - */ - public Object getResponseObject(); - } - - private static class BaseCommand implements ElastiCenterCommand { - - private String commandName = null; - private List> commandParameters = null; - private Object responseObject = null; - - /* - * Enforce the Commands to be initialized with command name and optional - * response object - */ - protected BaseCommand(String cmdName, Object responseObj) { - commandName = cmdName; - responseObject = responseObj; - } - - @Override - public String getCommandName() { - return commandName; - } - - @Override - public boolean validate() { - // TODO This method can be extended to do some generic - // validations. - return true; - } - - @Override - public List> getCommandParameters() { - return commandParameters; - } - - @Override - public void putCommandParameter(String key, String value) { - if (null == commandParameters) { - commandParameters = new ArrayList<>(); - } - commandParameters.add(new Pair<>(key, value)); - } - - @Override - public Object getResponseObject() { - return responseObject; - } - - } - - /** - * this is a rest client which is used to call the http rest calls to - * elastistor - * - * @author punith - * - */ - private static final class ElastiCenterClient { - - public static boolean debug = false; - - private boolean initialized = false; - - private String apiKey = null; - private String elastiCenterAddress = null; - private String responseType = "json"; - private boolean ignoreSSLCertificate = false; - - private String restprotocol = "https://"; - private String restpath = "/client/api"; - private String restdefaultcommand = "listCapabilities"; - - private String queryparamcommand = "command"; - private String queryparamapikey = "apikey"; - private String queryparamresponse = "response"; - - public ElastiCenterClient(String address, String key) throws InvalidCredentialsException, InvalidParameterValueException, SSLHandshakeException, ServiceUnavailableException { - elastiCenterAddress = address; - apiKey = key; - initialize(); - } - - public void initialize() throws InvalidParameterValueException, SSLHandshakeException, InvalidCredentialsException, ServiceUnavailableException { - - if (apiKey == null || apiKey.trim().isEmpty()) { - throw new InvalidParameterValueException("Unable to initialize. Please specify a valid API Key."); - } - - if (elastiCenterAddress == null || elastiCenterAddress.trim().isEmpty()) { - // TODO : Validate the format, like valid IP address or - // hostname. - throw new InvalidParameterValueException("Unable to initialize. Please specify a valid ElastiCenter IP Address or Hostname."); - } - - if (ignoreSSLCertificate) { - // Create a trust manager that does not validate certificate - // chains - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - - @Override - public void checkClientTrusted(X509Certificate[] certs, String authType) { - } - - @Override - public void checkServerTrusted(X509Certificate[] certs, String authType) { - } - } }; - - HostnameVerifier hv = new HostnameVerifier() { - @Override - public boolean verify(String urlHostName, SSLSession session) { - return true; - } - }; - - // Install the all-trusting trust manager - try { - SSLContext sc = SSLUtils.getSSLContext(); - sc.init(null, trustAllCerts, new SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(new SecureSSLSocketFactory(sc)); - HttpsURLConnection.setDefaultHostnameVerifier(hv); - } catch (Exception e) { - ; - } - } - - ListCapabilitiesResponse listCapabilitiesResponse = null; - try { - initialized = true; - listCapabilitiesResponse = (ListCapabilitiesResponse) executeCommand(restdefaultcommand, null, new ListCapabilitiesResponse()); - - } catch (Throwable t) { - initialized = false; - if (t instanceof InvalidCredentialsException) { - throw (InvalidCredentialsException) t; - } else if (t instanceof ServiceUnavailableException) { - throw (ServiceUnavailableException) t; - } else if (t.getCause() instanceof SSLHandshakeException) { - throw new SSLHandshakeException("Unable to initialize. An untrusted SSL Certificate was received from " + elastiCenterAddress - + ". Please verify your truststore or configure ElastiCenterClient to skip the SSL Validation. "); - } else if (t.getCause() instanceof ConnectException) { - throw new ServiceUnavailableException("Unable to initialize. Failed to connect to " + elastiCenterAddress - + ". Please verify the IP Address, Network Connectivity and ensure that Services are running on the ElastiCenter Server. "); - } - throw new ServiceUnavailableException("Unable to initialize. Please contact your ElastiCenter Administrator. Exception " + t.getMessage()); - } - - if (null == listCapabilitiesResponse || null == listCapabilitiesResponse.getCapabilities() || null == listCapabilitiesResponse.getCapabilities().getVersion()) { - initialized = false; - throw new ServiceUnavailableException("Unable to execute command on the server"); - } - - } - - public Object executeCommand(ElastiCenterCommand cmd) throws Throwable { - return executeCommand(cmd.getCommandName(), cmd.getCommandParameters(), cmd.getResponseObject()); - } - - public Object executeCommand(String command, List> params, Object responeObj) throws Throwable { - - if (!initialized) { - throw new IllegalStateException("Error : ElastiCenterClient is not initialized."); - } - - if (command == null || command.trim().isEmpty()) { - throw new InvalidParameterValueException("No command to execute."); - } - - try { - ClientConfig config = new ClientConfig(); - Client client = ClientBuilder.newClient(config); - WebTarget webResource = client.target(UriBuilder.fromUri(restprotocol + elastiCenterAddress + restpath).build()) - .queryParam(queryparamapikey, apiKey) - .queryParam(queryparamresponse, responseType) - .queryParam(queryparamcommand, command); - - if (null != params) { - for (Pair pair : params) { - webResource = webResource.queryParam(pair.first(), pair.second()); - } - } - if (debug) { - List> qryParams = new ArrayList<>(); - qryParams.add(new Pair<>(queryparamapikey, apiKey)); - qryParams.add(new Pair<>(queryparamresponse, responseType)); - qryParams.add(new Pair<>(queryparamcommand, command)); - qryParams.addAll(params); - System.out.println("Command Sent " + command + " : " + params); - } - ClientResponse response = webResource.request(MediaType.APPLICATION_JSON).get(ClientResponse.class); - - if (response.getStatus() >= 300) { - if (debug) - System.out.println("ElastiCenter returned error code : " + response.getStatus()); - if (401 == response.getStatus()) { - throw new InvalidCredentialsException("Please specify a valid API Key."); - } else if (431 == response.getStatus()) { - throw new InvalidParameterValueException(response.getHeaders().getFirst("X-Description")); - } else if (432 == response.getStatus()) { - throw new InvalidParameterValueException(command + " does not exist on the ElastiCenter server. Please specify a valid command or contact your ElastiCenter Administrator."); - } else { - throw new ServiceUnavailableException("Internal Error. Please contact your ElastiCenter Administrator."); - } - } else if (null != responeObj) { - String jsonResponse = String.valueOf(response.readEntity(String.class)); - if (debug) { - System.out.println("Command Response : " + jsonResponse); - } - Gson gson = new Gson(); - return gson.fromJson(jsonResponse, responeObj.getClass()); - } else { - return "Success"; - } - } catch (Throwable t) { - throw t; - } - } - } - - /** - * these are the list of Elastistor rest commands being called from the - * plugin. - */ - private static final class CreateTsmCmd extends BaseCommand { - - public CreateTsmCmd() { - super("createTsm", new CreateTsmCmdResponse()); - - } - - } - - private static final class AddQosGroupCmd extends BaseCommand { - - public AddQosGroupCmd() { - - super("addQosGroup", new AddQosGroupCmdResponse()); - - } - - } - - private static final class CreateVolumeCmd extends BaseCommand { - - public CreateVolumeCmd() { - super("createVolume", new CreateVolumeCmdResponse()); - - } - - } - - private static final class ListVolumeiSCSIServiceCmd extends BaseCommand { - - public ListVolumeiSCSIServiceCmd() { - super("listVolumeiSCSIService", new ListVolumeiSCSIServiceResponse()); - - } - - } - - private static final class ListiSCSIInitiatorCmd extends BaseCommand { - - public ListiSCSIInitiatorCmd() { - super("listiSCSIInitiator", new ListiSCSIInitiatorResponse()); - - } - - } - - private static final class NfsServiceCmd extends BaseCommand { - - public NfsServiceCmd() { - super("nfsService", new NfsServiceResponse()); - - } - - } - - private static final class UpdateControllerCmd extends BaseCommand { - - public UpdateControllerCmd() { - super("updateController", new UpdateControllerResponse()); - - } - - } - - private static final class UpdateVolumeiSCSIServiceCmd extends BaseCommand { - - public UpdateVolumeiSCSIServiceCmd() { - super("updateVolumeiSCSIService", new UpdateVolumeiSCSIServiceCmdResponse()); - - } - - } - - private static final class DeleteTsmCmd extends BaseCommand { - - public DeleteTsmCmd() { - super("deleteTsm", new DeleteTsmResponse()); - } - - } - - private static final class DeleteVolumeCmd extends BaseCommand { - - public DeleteVolumeCmd() { - super("deleteFileSystem", new DeleteVolumeResponse()); - } - - } - - private static final class QueryAsyncJobResultCmd extends BaseCommand { - - public QueryAsyncJobResultCmd() { - super("queryAsyncJobResult", new QueryAsyncJobResultResponse()); - } - - } - - private static final class ListTsmCmd extends BaseCommand { - - public ListTsmCmd() { - super("listTsm", new ListTsmsResponse()); - } - - } - - private static final class ListFileSystemCmd extends BaseCommand { - - public ListFileSystemCmd() { - super("listFileSystem", new ListFileSystemResponse()); - } - - } - - private static final class ListAccountsCmd extends BaseCommand { - - public ListAccountsCmd() { - super("listAccount", new ListAccountResponse()); - } - - } - - private static final class CreateAccountCmd extends BaseCommand { - - public CreateAccountCmd() { - super("createAccount", new CreateAccountResponse()); - } - - } - - private static final class ListInterfacesCmd extends BaseCommand { - - public ListInterfacesCmd() { - super("listSharedNICs", new ListInterfacesResponse()); - } - - } - - private static final class ListPoolsCmd extends BaseCommand { - - public ListPoolsCmd() { - super("listHAPool", new ListPoolsResponse()); - } - - } - - /** - * these are the list of Elastistor rest json response classes for parsing - * the json response sent by elastistor. - * - */ - public static final class CreateTsmCmdResponse { - - @SerializedName("addTsmResponse") - private JobId jobId; - - public String getJobid() { - return jobId.getJobid(); - } - - public String getJobStatus() { - return jobId.getJobStatus(); - } - - @SerializedName("createTsmResponse") - private TsmWrapper tsmWrapper; - - public Tsm getTsm() { - return tsmWrapper.getTsm(); - } - - } - - public static final class Tsm { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("datasetid") - private String datasetid; - - @SerializedName("ipaddress") - private String ipaddress; - - @SerializedName("volumes") - private VolumeProperties[] volumeProperties; - - public String getUuid() { - return uuid; - } - - public String getName() { - return name; - } - - public String getIpaddress() { - return ipaddress; - } - - public String getDatasetid() { - return datasetid; - } - - public boolean checkvolume() { - - if (volumeProperties != null) { - return true; - } else { - return false; - } - - } - - public VolumeProperties getVolumeProperties(int i) { - return volumeProperties[i]; - } - - } - - public static final class VolumeProperties { - - @SerializedName("id") - private String id; - - @SerializedName("groupid") - private String groupid; - - @SerializedName("iops") - private String iops; - - @SerializedName("name") - private String name; - - public String getid() { - return id; - } - - public String getQosgroupid() { - return groupid; - } - - public String getName() { - return name; - } - - public String getIops() { - return iops; - } - } - - public static final class TsmWrapper { - - @SerializedName("tsm") - private Tsm tsm; - - public Tsm getTsm() { - return tsm; - } - - } - - public static final class AddQosGroupCmdResponse { - - @SerializedName("addqosgroupresponse") - private QoSGroupWrapper qosGroupWrapper; - - public QoSGroup getQoSGroup() { - return qosGroupWrapper.getQosGroup(); - } - } - - public static final class QoSGroupWrapper { - - @SerializedName("qosgroup") - private QoSGroup qoSGroup; - - public QoSGroup getQosGroup() { - - return qoSGroup; - } - - } - - public static final class QoSGroup { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("qosgroupproperties") - private HashMap qosGroupProperties; - - public String getName() { - return name; - } - - public String getUuid() { - return uuid; - } - - public String getIops() { - return qosGroupProperties.get("iops"); - } - - public String getThroughput() { - return qosGroupProperties.get("throughput"); - } - - public String getLatency() { - return qosGroupProperties.get("latency"); - } - } - - public static final class UpdateVolumeiSCSIServiceCmdResponse { - - @SerializedName("updatingvolumeiscsidetails") - private VolumeiSCSIServiceWrapper volumeiSCSIServiceWrapper; - - public Volumeiscsioptions getVolumeiscsioptions() { - - return volumeiSCSIServiceWrapper.getVolumeiscsioptions(); - } - - } - - public static final class VolumeiSCSIServiceWrapper { - - @SerializedName("viscsioptions") - private Volumeiscsioptions viscsioptions; - - public Volumeiscsioptions getVolumeiscsioptions() { - return viscsioptions; - } - - } - - public static final class Volumeiscsioptions { - - @SerializedName("id") - private String uuid; - - @SerializedName("volume_id") - private String volumeid; - - @SerializedName("iqnname") - private String iqnname; - - public String getUuid() { - return uuid; - } - - public String getVolumeid() { - return volumeid; - } - - public String getIqn() { - return iqnname; - } - - } - - public static final class NfsServiceResponse { - - @SerializedName("nfsserviceprotocolresponse") - private NfsServiceWrapper nfsServiceWrapper; - - public NfsService getNfsService() { - - return nfsServiceWrapper.getNfsservice(); - } - - } - - public static final class NfsServiceWrapper { - - @SerializedName("nfs") - private NfsService nfsService; - - public NfsService getNfsservice() { - return nfsService; - } - - } - - public static final class NfsService { - - @SerializedName("id") - private String uuid; - - @SerializedName("STORAGEID") - private String datasetid; - - @SerializedName("controllerid") - private String controllerid; - - @SerializedName("authnetwork") - private String authnetwork; - - public String getUuid() { - return uuid; - } - - public String getDatasetid() { - return datasetid; - } - - public String getControllerid() { - return controllerid; - } - - public String getAuthnetwork() { - return authnetwork; - } - - } - - public static final class UpdateControllerResponse { - - @SerializedName("updateControllerResponse") - private UpdateControllerWrapper controllerWrapper; - - public Controller getController() { - - return controllerWrapper.getController(); - } - - } - - public static final class UpdateControllerWrapper { - - @SerializedName("controller") - private Controller controller; - - public Controller getController() { - return controller; - } - - } - - public static final class Controller { - - @SerializedName("id") - private String uuid; - - public String getUuid() { - return uuid; - } - - } - - public static final class CreateVolumeCmdResponse { - - @SerializedName("createvolumeresponse") - private JobId jobId; - - public String getJobid() { - return jobId.getJobid(); - } - - @SerializedName("adddatasetresponse") - private FileSystemWrapper fileSystemWrapper; - - public FileSystem getFileSystem() { - - return fileSystemWrapper.getFileSystem(); - } - - } - - public static final class FileSystemWrapper { - - @SerializedName("filesystem") - private FileSystem fileSystem; - - public FileSystem getFileSystem() { - return fileSystem; - } - - } - - public static final class FileSystem { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("quota") - private String quota; - - @SerializedName("accountid") - private String accountid; - - @SerializedName("iqnname") - private String iqnname; - - @SerializedName("nfsenabled") - private String nfsenabled; - - @SerializedName("iscsienabled") - private String iscsienabled; - - @SerializedName("path") - private String path; - - @SerializedName("groupid") - private String groupid; - - @SerializedName("compression") - private String compression; - - @SerializedName("sync") - private String sync; - - @SerializedName("deduplication") - private String deduplication; - - @SerializedName("graceallowed") - private String graceallowed; - - public String getCompression() { - return compression; - } - - public String getSync() { - return sync; - } - - public String getDeduplication() { - return deduplication; - } - - public String getGraceallowed() { - return graceallowed; - } - - public String getUuid() { - return uuid; - } - - public String getQosGroupid() { - return groupid; - } - - public String getName() { - return name; - } - - public String getNfsenabled() { - return nfsenabled; - } - - public String getIscsienabled() { - return iscsienabled; - } - - public String getPath() { - return path; - } - - public String getIqn() { - return iqnname; - } - - public String getQuota() { - return quota; - } - - public String getAccountid() { - return accountid; - } - - } - - public static final class DeleteTsmResponse { - - @SerializedName("deleteTsmResponse") - private JobId jobId; - - public String getJobStatus() { - return jobId.getJobStatus(); - } - - } - - public static final class JobId { - - @SerializedName("jobid") - private String jobid; - - @SerializedName("success") - private String jobStatus; - - @SerializedName("jobresult") - private JobResult jobresult; - - @SerializedName("tsm") - private Tsm tsm; - - @SerializedName("storage") - private FileSystem volume; - - public Tsm getTsm() { - return tsm; - } - - public FileSystem getVolume() { - return volume; - } - - public JobResult getJobResult() { - return jobresult; - } - - public String getJobid() { - return jobid; - } - - public String getJobStatus() { - return jobStatus; - } - - } - - public static final class JobResult { - - @SerializedName("tsm") - private Tsm tsm; - - @SerializedName("storage") - private FileSystem volume; - - public Tsm getTsm() { - return tsm; - } - - public FileSystem getVolume() { - return volume; - } - - } - - public static final class DeleteVolumeResponse { - - @SerializedName("deleteFileSystemResponse") - private JobId jobId; - - public String getJobId() { - return jobId.getJobid(); - } - - } - - public static final class ListCapabilitiesResponse { - - @SerializedName("listcapabilitiesresponse") - private Capabilities capabilities; - - public Capabilities getCapabilities() { - return capabilities; - } - } - - public static final class ListFileSystemResponse { - - @SerializedName("listFilesystemResponse") - private Filesystems filesystems; - - public int getFilesystemCount() { - return filesystems.getCount(); - } - - public Filesystems getFilesystems() { - return filesystems; - } - } - - public static final class Filesystems { - - @SerializedName("count") - private int count; - - @SerializedName("filesystem") - private FileSystem[] fileSystems; - - public int getCount() { - return count; - } - - public FileSystem getFileSystem(int i) { - return fileSystems[i]; - } - } - - public static final class ListPoolsResponse { - - @SerializedName("listHAPoolResponse") - private Pools pools; - - public Pools getPools() { - return pools; - } - } - - public static final class Pools { - - @SerializedName("hapool") - private Pool[] pool; - - @SerializedName("count") - private int count; - - public Pool getPool(int i) { - return pool[i]; - } - - public int getCount() { - return count; - } - } - - public static final class Pool { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("currentAvailableSpace") - private String currentAvailableSpace; - - @SerializedName("availIOPS") - private String availIOPS; - - @SerializedName("status") - private String state; - - @SerializedName("controllerid") - private String controllerid; - - @SerializedName("gateway") - private String gateway; - - public String getControllerid() { - return controllerid; - } - - public String getUuid() { - return uuid; - } - - public String getName() { - return name; - } - - public String getAvailableSpace() { - return currentAvailableSpace; - } - - public String getAvailIOPS() { - return availIOPS; - } - - public String getState() { - return state; - } - - public String getGateway() { - return gateway; - } - } - - public static final class ListInterfacesResponse { - - @SerializedName("listSharedNICsResponse") - private Interfaces interfaces; - - public Interfaces getInterfaces() { - return interfaces; - } - } - - public static final class Interfaces { - - @SerializedName("nic") - private Interface[] interfaces; - - @SerializedName("count") - private int count; - - public Interface getInterface(int i) { - return interfaces[i]; - } - - public int getCount() { - return count; - } - } - - public static final class Interface { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("status") - private String status; - - public String getUuid() { - return uuid; - } - - public String getName() { - return name; - } - - public String getStatus() { - return status; - } - } - - public static final class ListiSCSIInitiatorResponse { - - @SerializedName("listInitiatorsResponse") - private Initiators initiators; - - public Initiators getIInitiator() { - return initiators; - } - } - - public static final class Initiators { - - @SerializedName("initiator") - private Initiator[] initiators; - - @SerializedName("count") - private int count; - - public Initiator getInterface(int i) { - return initiators[i]; - } - - public int getCount() { - return count; - } - } - - public static final class Initiator { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("initiatorgroup") - private String initiatorgroup; - - public String getUuid() { - return uuid; - } - - public String getName() { - return name; - } - - public String getInitiatorgroup() { - return initiatorgroup; - } - } - - public static final class ListAccountResponse { - - @SerializedName("listAccountResponse") - private Accounts accounts; - - public Accounts getAccounts() { - return accounts; - } - } - - public static final class Accounts { - - @SerializedName("account") - private Account[] Accounts; - - @SerializedName("count") - private int count; - - public Account getAccount(int i) { - return Accounts[i]; - } - - public int getCount() { - return count; - } - } - - public static final class CreateAccountResponse { - - @SerializedName("createaccountresponse") - private Accounts2 accounts; - - public Account getAccount() { - return accounts.getAccount(); - } - } - - public static final class Accounts2 { - - @SerializedName("account2") - private Account Account; - - @SerializedName("count") - private int count; - - public Account getAccount() { - return Account; - } - - public int getCount() { - return count; - } - } - - public static final class Account { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - public String getUuid() { - return uuid; - } - - public String getName() { - return name; - } - } - - public static final class ListTsmsResponse { - - @SerializedName("listTsmResponse") - private Tsms tsms; - - public int getTsmsCount() { - return tsms.getCount(); - } - - public Tsms getTsms() { - return tsms; - } - } - - public static final class Tsms { - - @SerializedName("count") - private int count; - - @SerializedName("listTsm") - private Tsm[] tsms; - - public int getCount() { - return count; - } - - public Tsm getTsm(int i) { - return tsms[i]; - } - } - - public static final class ListVolumeiSCSIServiceResponse { - - @SerializedName("listVolumeiSCSIServiceResponse") - private IscsiVolumeService iscsiVolumes; - - public int getVolumeCount() { - return iscsiVolumes.getCount(); - } - - public IscsiVolumeService getIscsiVolume() { - return iscsiVolumes; - } - } - - public static final class IscsiVolumeService { - - @SerializedName("count") - private int count; - - @SerializedName("iSCSIService") - private IscsiVolume[] iscsiVolumes; - - public int getCount() { - return count; - } - - public IscsiVolume getIscsiVolume(int i) { - return iscsiVolumes[i]; - } - } - - public static final class IscsiVolume { - - @SerializedName("id") - private String uuid; - - @SerializedName("ag_id") - private String agid; - - @SerializedName("ig_id") - private String igid; - - public String getAg_id() { - return agid; - } - - public String getUuid() { - return uuid; - } - - public String getIg_id() { - return igid; - } - } - - public static final class QueryAsyncJobResultResponse { - - @SerializedName("queryasyncjobresultresponse") - private Async async; - - public Async getAsync() { - return async; - } - } - - public static final class Async { - - @SerializedName("jobstatus") - private int jobstatus; - - @SerializedName("jobresult") - private JobId jobresult; - - @SerializedName("cmd") - private String cmd; - - public int getJobStatus() { - return jobstatus; - } - - public JobId getJobResult() { - return jobresult; - } - - public String getCmd() { - return cmd; - } - - } - - public static final class Capabilities { - - @SerializedName("capability") - private HashMap capabilites; - - public String getVersion() { - return capabilites.get("cloudByteVersion"); - } - } - - /* - * - * change Volume IOPS - */ - - public static Answer updateElastistorVolumeQosGroup(String volumeId, Long newIOPS, String graceAllowed) throws Throwable { - - FileSystem fileSystem = listVolume(volumeId); - - String qosid = fileSystem.getQosGroupid(); - - if (qosid != null) { - - UpdateQosGroupCmdResponse qosGroupCmdResponse = updateQosGroupVolume(newIOPS.toString(), qosid, graceAllowed); - - if (qosGroupCmdResponse.getQoSGroup(0).uuid != null) { - return new Answer(null, true, null); - } else { - return new Answer(null, false, "Update Qos Group Failed"); - } - } else { - return new Answer(null, false, "Qos Group id is NULL"); - } - - } - - private static UpdateQosGroupCmdResponse updateQosGroupVolume(String iops, String qosgroupid, String graceAllowed) throws Throwable { - - UpdateQosGroupCmd updateQosGroupCmd = new UpdateQosGroupCmd(); - updateQosGroupCmd.putCommandParameter("id", qosgroupid); - updateQosGroupCmd.putCommandParameter("iops", iops); - updateQosGroupCmd.putCommandParameter("graceallowed", graceAllowed); - - UpdateQosGroupCmdResponse updateQosGroupCmdResponse = (UpdateQosGroupCmdResponse) getElastistorRestClient().executeCommand(updateQosGroupCmd); - - return updateQosGroupCmdResponse; - } - - private static final class UpdateQosGroupCmd extends BaseCommand { - - public UpdateQosGroupCmd() { - super("updateQosGroup", new UpdateQosGroupCmdResponse()); - } - - } - - public static final class UpdateQosGroupCmdResponse { - - @SerializedName("updateqosresponse") - private QoSGroupWrapperChangeVolumeIops qosGroupWrapper; - - public QoSGroup getQoSGroup(int i) { - return qosGroupWrapper.getQosGroup(i); - } - } - - public static final class QoSGroupWrapperChangeVolumeIops { - - @SerializedName("qosgroup") - private QoSGroup qoSGroup[]; - - public QoSGroup getQosGroup(int i) { - - return qoSGroup[i]; - } - - } - - /* - * resize volume - */ - - public static Boolean updateElastistorVolumeSize(String volumeId, Long newSize) throws Throwable { - - Boolean status = false; - - String quotasize = (String.valueOf(newSize / (1024 * 1024 * 1024)) + "G"); - - UpdateFileSystemCmdResponse fileSystemCmdResponse = updateFileSystem(quotasize, volumeId, null, null, null); - - if (fileSystemCmdResponse.getFileSystem(0).uuid != null) { - status = true; - return status; - } - - return status; - } - - public static UpdateFileSystemCmdResponse updateFileSystem(String quotasize, String esvolumeid, String dedeplication, String compression, String sync) throws Throwable { - - UpdateFileSystemCmd fileSystemCmd = new UpdateFileSystemCmd(); - - fileSystemCmd.putCommandParameter("id", esvolumeid); - if (null != quotasize) - fileSystemCmd.putCommandParameter("quotasize", quotasize); - if (null != dedeplication) - fileSystemCmd.putCommandParameter("deduplication", dedeplication); - if (null != compression) - fileSystemCmd.putCommandParameter("compression", compression); - if (null != sync) - fileSystemCmd.putCommandParameter("sync", sync); - - UpdateFileSystemCmdResponse fileSystemCmdResponse = (UpdateFileSystemCmdResponse) getElastistorRestClient().executeCommand(fileSystemCmd); - - return fileSystemCmdResponse; - } - - private static final class UpdateFileSystemCmd extends BaseCommand { - - public UpdateFileSystemCmd() { - super("updateFileSystem", new UpdateFileSystemCmdResponse()); - } - - } - - private static final class UpdateFileSystemCmdResponse { - - @SerializedName("updatefilesystemresponse") - private UpdateFileSystemWrapper fileSystemWrapper; - - public FileSystem getFileSystem(int i) { - - return fileSystemWrapper.getFileSystem(i); - } - } - - public class UpdateFileSystemWrapper { - - @SerializedName("filesystem") - private FileSystem fileSystem[]; - - public FileSystem getFileSystem(int i) { - return fileSystem[i]; - } - - } - /* - * create snapshot - */ - - public static Answer createElastistorVolumeSnapshot(String volumeId, String snapshotName) throws Throwable{ - - CreateStorageSnapshotCmd snapshotCmd = new CreateStorageSnapshotCmd(); - - snapshotCmd.putCommandParameter("id", volumeId); - snapshotCmd.putCommandParameter("name", snapshotName); - - CreateStorageSnapshotCmdResponse snapshotCmdResponse = (CreateStorageSnapshotCmdResponse) getElastistorRestClient().executeCommand(snapshotCmd); - - if(snapshotCmdResponse.getStorageSnapshot().getId() != null){ - return new Answer(null, true, snapshotCmdResponse.getStorageSnapshot().getId()); - }else{ - return new Answer(null, false, "snapshot failed"); - } - } - - private static final class CreateStorageSnapshotCmd extends BaseCommand { - - public CreateStorageSnapshotCmd() { - super("createStorageSnapshot", new CreateStorageSnapshotCmdResponse() ); - } - - } - - private static final class CreateStorageSnapshotCmdResponse { - - @SerializedName("createStorageSnapshotResponse") - private StorageSnapshotWrapper StorageSnapshot; - - public StorageSnapshot getStorageSnapshot() { - return StorageSnapshot.getStorageSnapshot(); - } - } - - public static final class StorageSnapshotWrapper { - - @SerializedName("StorageSnapshot") - private StorageSnapshot snapshot; - - - - public StorageSnapshot getStorageSnapshot() { - return snapshot; - } - - } - - public static final class StorageSnapshot { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - public String getId(){ - return uuid; - } - - public String getName(){ - return name; - } - } - - // update the TSM storage - public static UpdateTsmStorageCmdResponse updateElastistorTsmStorage(String capacityBytes,String uuid) throws Throwable{ - - Long size = (Long.parseLong(capacityBytes)/(1024 * 1024 * 1024)); - - String quotasize = null; - - if(size > 1024){ - quotasize = (String.valueOf(Long.parseLong(capacityBytes)/(1024)) + "T"); - }else{ - quotasize = String.valueOf(quotasize) + "G"; - } - LOGGER.info("elastistor tsm storage is updating to " + quotasize); - UpdateTsmStorageCmd updateTsmStorageCmd = new UpdateTsmStorageCmd(); - - updateTsmStorageCmd.putCommandParameter("id", uuid); - updateTsmStorageCmd.putCommandParameter("quotasize", quotasize); - - UpdateTsmStorageCmdResponse updateTsmStorageCmdResponse = (UpdateTsmStorageCmdResponse) getElastistorRestClient().executeCommand(updateTsmStorageCmd); - - return updateTsmStorageCmdResponse; - } - - private static final class UpdateTsmStorageCmd extends BaseCommand { - - public UpdateTsmStorageCmd() { - super("updateStorage", new UpdateTsmStorageCmdResponse()); - } - - } - - public static final class UpdateTsmStorageCmdResponse { - - @SerializedName("updatedatasetresponse") - private StorageWrapper storageWrapper; - - public Storage getStorage() { - return storageWrapper.getStorage(); - } - } - - public static final class StorageWrapper { - - @SerializedName("storage") - private Storage storage; - - public Storage getStorage() { - return storage; - } - - } - - public static final class Storage { - - @SerializedName("id") - private String uuid; - - @SerializedName("name") - private String name; - - @SerializedName("quota") - private String quota; - - public String getId(){ - return uuid; - } - - public String getName(){ - return name; - } - - public String getsize(){ - return quota; - } - } - - // update the TSM IOPS - public static UpdateTsmCmdResponse updateElastistorTsmIOPS(String capacityIOPs,String uuid) throws Throwable{ - - LOGGER.info("elastistor tsm IOPS is updating to " + capacityIOPs); - UpdateTsmCmd updateTsmCmd = new UpdateTsmCmd(); - String throughput = String.valueOf(Long.parseLong(capacityIOPs)*4); - - updateTsmCmd.putCommandParameter("id", uuid); - updateTsmCmd.putCommandParameter("iops", capacityIOPs); - updateTsmCmd.putCommandParameter("throughput", throughput); - - UpdateTsmCmdResponse updateTsmStorageCmdResponse = (UpdateTsmCmdResponse) getElastistorRestClient().executeCommand(updateTsmCmd); - - return updateTsmStorageCmdResponse; - } - - private static final class UpdateTsmCmd extends BaseCommand { - - public UpdateTsmCmd() { - super("updateTsm", new UpdateTsmCmdResponse()); - } - - } - - public static final class UpdateTsmCmdResponse { - - @SerializedName("updateTsmResponse") - private UpdateTsmWrapper tsmWrapper; - - public Tsm getTsm(int i) { - return tsmWrapper.getTsm(i); - } - } - - public static final class UpdateTsmWrapper { - - @SerializedName("count") - private int count; - - @SerializedName("tsm") - private Tsm[] tsms; - - public int getCount() { - return count; - } - - public Tsm getTsm(int i) { - return tsms[i]; - } - } - -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiService.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiService.java deleted file mode 100644 index 08dcb4333fe2..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiService.java +++ /dev/null @@ -1,33 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import org.apache.cloudstack.api.response.ListResponse; - -import com.cloud.utils.component.PluggableService; - -public interface ElastistorVolumeApiService extends PluggableService { - - ListResponse listElastistorVolume(ListElastistorVolumeCmd cmd); - - ListResponse listElastistorPools(ListElastistorPoolCmd cmd); - - ListResponse listElastistorInterfaces(ListElastistorInterfaceCmd cmd); -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiServiceImpl.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiServiceImpl.java deleted file mode 100644 index 83f7356eb440..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ElastistorVolumeApiServiceImpl.java +++ /dev/null @@ -1,206 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.api.response.ListResponse; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.provider.ElastistorPrimaryDataStoreProvider; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.FileSystem; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.ListInterfacesResponse; -import org.apache.cloudstack.storage.datastore.util.ElastistorUtil.ListPoolsResponse; - -import com.cloud.storage.dao.DiskOfferingDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeDetailsDao; -import com.cloud.utils.component.ManagerBase; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.dao.UserVmDao; - -@Component -public class ElastistorVolumeApiServiceImpl extends ManagerBase implements ElastistorVolumeApiService { - - @Inject - protected VolumeDao _volsDao; - @Inject - protected UserVmDao _userVmDao; - @Inject - protected DiskOfferingDao _diskOfferingDao; - @Inject - private PrimaryDataStoreDao _storagePoolDao; - @Inject - VolumeService volService; - @Inject - VolumeDataFactory volFactory; - @Inject - ElastistorPrimaryDataStoreProvider esProvider; - @Inject - VolumeDetailsDao volumeDetailsDao; - - @Override - public List> getCommands() { - - List> cmdList = new ArrayList>(); - cmdList.add(ListElastistorVolumeCmd.class); - cmdList.add(ListElastistorPoolCmd.class); - cmdList.add(ListElastistorInterfaceCmd.class); - - logger.info("Commands were registered successfully with elastistor volume api service. [cmdcount:" + cmdList.size() + "]"); - return cmdList; - - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - _configParams = params; - return true; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @SuppressWarnings("unchecked") - @Override - public ListResponse listElastistorVolume(ListElastistorVolumeCmd cmd) { - - try { - FileSystem listVolumeResponse = ElastistorUtil.listVolume(cmd.getId()); - - List volumeResponses = new ArrayList(); - - ListElastistorVolumeResponse volumeResponse; - - volumeResponse = new ListElastistorVolumeResponse(); - - volumeResponse.setId(listVolumeResponse.getUuid()); - volumeResponse.setName(listVolumeResponse.getName()); - volumeResponse.setGraceAllowed(listVolumeResponse.getGraceallowed()); - volumeResponse.setDeduplication(listVolumeResponse.getDeduplication()); - volumeResponse.setCompression(listVolumeResponse.getCompression()); - volumeResponse.setSync(listVolumeResponse.getSync()); - // set object name for a better json structure - volumeResponse.setObjectName("elastistorvolume"); - volumeResponses.add(volumeResponse); - - ListResponse response = new ListResponse(); - - response.setResponses(volumeResponses); - - return response; - } catch (Throwable e) { - logger.error("Unable to list elastistor volume.", e); - throw new CloudRuntimeException("Unable to list elastistor volume. " + e.getMessage()); - } - } - - @SuppressWarnings("unchecked") - @Override - public ListResponse listElastistorPools(ListElastistorPoolCmd cmd) { - - try { - ListPoolsResponse listPools = ElastistorUtil.ListElastistorPools(); - - List poolResponses = new ArrayList(); - - ListElastistorPoolResponse elastistorPoolResponse; - - for (int i = 0; i < listPools.getPools().getCount(); i++) { - // Always instantiate inside the loop - elastistorPoolResponse = new ListElastistorPoolResponse(); - - elastistorPoolResponse.setId(listPools.getPools().getPool(i).getUuid()); - elastistorPoolResponse.setName(listPools.getPools().getPool(i).getName()); - elastistorPoolResponse.setAvailIOPS(Long.parseLong(listPools.getPools().getPool(i).getAvailIOPS())); - elastistorPoolResponse.setCurrentAvailableSpace(Long.parseLong(listPools.getPools().getPool(i).getAvailableSpace())); - elastistorPoolResponse.setState(listPools.getPools().getPool(i).getState()); - elastistorPoolResponse.setControllerid(listPools.getPools().getPool(i).getControllerid()); - elastistorPoolResponse.setGateway(listPools.getPools().getPool(i).getGateway()); - - // set object name for a better json structure - elastistorPoolResponse.setObjectName("elastistorpool"); - poolResponses.add(elastistorPoolResponse); - } - - ListResponse response = new ListResponse(); - - response.setResponses(poolResponses); - - return response; - - } catch (Throwable e) { - logger.error("Unable to list elastistor pools.", e); - throw new CloudRuntimeException("Unable to list elastistor pools. " + e.getMessage()); - } - - } - - @Override - public ListResponse listElastistorInterfaces(ListElastistorInterfaceCmd cmd) { - try { - ListInterfacesResponse listInterfacesResponse = ElastistorUtil.ListElastistorInterfaces(cmd.getControllerId()); - - List interfaceResponses = new ArrayList(); - - ListElastistorInterfaceResponse interfaceResponse; - - for (int i = 0; i < listInterfacesResponse.getInterfaces().getCount(); i++) { - // Always instantiate inside the loop - interfaceResponse = new ListElastistorInterfaceResponse(); - - interfaceResponse.setId(listInterfacesResponse.getInterfaces().getInterface(i).getUuid()); - interfaceResponse.setName(listInterfacesResponse.getInterfaces().getInterface(i).getName()); - interfaceResponse.setStatus(listInterfacesResponse.getInterfaces().getInterface(i).getStatus()); - - // set object name for a better json structure - interfaceResponse.setObjectName("elastistorInterface"); - interfaceResponses.add(interfaceResponse); - } - - ListResponse response = new ListResponse(); - - response.setResponses(interfaceResponses); - - return response; - } catch (Throwable e) { - logger.error("Unable to list elastistor interfaces.", e); - throw new CloudRuntimeException("Unable to list elastistor interfaces. " + e.getMessage()); - } - - } - -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceCmd.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceCmd.java deleted file mode 100644 index 3e4881773ec2..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceCmd.java +++ /dev/null @@ -1,74 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.ListResponse; - -@APICommand(name = "listElastistorInterface", description = "Lists the network Interfaces of elastistor", responseObject = ListElastistorVolumeResponse.class) -public class ListElastistorInterfaceCmd extends BaseCmd { - private static final String s_name = "listElastistorInterfaceResponse"; - - @Inject - ElastistorVolumeApiService _ElastistorVolumeApiService; - - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - - @Parameter(name = "controllerid", type = CommandType.STRING, description = "Controller ID") - private String controllerid; - - // /////////////////////////////////////////////////// - // ///////////////// Accessors /////////////////////// - // /////////////////////////////////////////////////// - - public String getControllerId() { - return controllerid; - } - - // /////////////////////////////////////////////////// - // ///////////// API Implementation/////////////////// - // /////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public void execute() { - - ListResponse response = _ElastistorVolumeApiService.listElastistorInterfaces(this); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceResponse.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceResponse.java deleted file mode 100644 index 31219274900b..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorInterfaceResponse.java +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; - -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; - -@SuppressWarnings("unused") -public class ListElastistorInterfaceResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "The ID of the NIC") - private String id; - - @SerializedName(ApiConstants.NAME) - @Param(description = "The name of the NIC") - private String name; - - @SerializedName(ApiConstants.STATUS) - @Param(description = "The status of the NIC") - private String status; - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return id; - } - -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolCmd.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolCmd.java deleted file mode 100644 index 2cf44610e6ec..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolCmd.java +++ /dev/null @@ -1,77 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.BaseCmd.CommandType; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.ListResponse; - -@APICommand(name = "listElastistorPool", description = "Lists the pools of elastistor", - responseObject = ListElastistorPoolResponse.class) -public class ListElastistorPoolCmd extends BaseCmd { - private static final String s_name = "listElastistorPoolResponse"; - - @Inject - ElastistorVolumeApiService _ElastistorVolumeApiService; - - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "The ID of the Pool") - private Long id; - - // /////////////////////////////////////////////////// - // ///////////////// Accessors /////////////////////// - // /////////////////////////////////////////////////// - - public Long getId() { - return id; - } - - // /////////////////////////////////////////////////// - // ///////////// API Implementation/////////////////// - // /////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public void execute() { - - ListResponse response = _ElastistorVolumeApiService.listElastistorPools(this); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolResponse.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolResponse.java deleted file mode 100644 index d91c0833e8d3..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorPoolResponse.java +++ /dev/null @@ -1,117 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; - -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; - -public class ListElastistorPoolResponse extends BaseResponse { - @SerializedName("id") - @Param(description = "The ID of the storage pool") - private String id; - - @SerializedName("name") - @Param(description = "The name of the storage pool") - private String name; - - @SerializedName(ApiConstants.STATE) - @Param(description = "The state of the storage pool") - private String state; - - @SerializedName(ApiConstants.SIZE) - @Param(description = "The current available space of the pool") - private Long currentAvailableSpace; - - @SerializedName(ApiConstants.MAX_IOPS) - @Param(description = "Available IOPS of the pool") - private Long availIOPS; - - @SerializedName("controllerid") - @Param(description = "Controller of the pool") - private String controllerid; - - @SerializedName("gateway") - @Param(description = "Default gateway of the pool") - private String gateway; - - @Override - public String getObjectId() { - return this.getId(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public Long getCurrentAvailableSpace() { - return currentAvailableSpace; - } - - public void setCurrentAvailableSpace(Long currentAvailableSpace) { - this.currentAvailableSpace = currentAvailableSpace; - } - - public Long getAvailIOPS() { - return availIOPS; - } - - public void setAvailIOPS(Long availIOPS) { - this.availIOPS = availIOPS; - } - - public String getControllerid() { - return controllerid; - } - - public void setControllerid(String controllerid) { - this.controllerid = controllerid; - } - - public String getGateway() { - return gateway; - } - - public void setGateway(String gateway) { - this.gateway = gateway; - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeCmd.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeCmd.java deleted file mode 100644 index f877f7711e5c..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeCmd.java +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.APICommand; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseCmd; -import org.apache.cloudstack.api.Parameter; -import org.apache.cloudstack.api.response.ListResponse; - -@APICommand(name = "listElastistorVolume", description = "Lists the volumes of elastistor", responseObject = ListElastistorVolumeResponse.class) -public class ListElastistorVolumeCmd extends BaseCmd { - private static final String s_name = "listElastistorVolumeResponse"; - - @Inject - ElastistorVolumeApiService _ElastistorVolumeApiService; - - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.ID, type = CommandType.STRING, required = true, description = "The ID of the account") - private String id; - - // /////////////////////////////////////////////////// - // ///////////////// Accessors /////////////////////// - // /////////////////////////////////////////////////// - - public String getId() { - return id; - } - - // /////////////////////////////////////////////////// - // ///////////// API Implementation/////////////////// - // /////////////////////////////////////////////////// - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public void execute() { - - ListResponse response = _ElastistorVolumeApiService.listElastistorVolume(this); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } -} diff --git a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeResponse.java b/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeResponse.java deleted file mode 100644 index afbecd4fcd72..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/java/org/apache/cloudstack/storage/datastore/util/ListElastistorVolumeResponse.java +++ /dev/null @@ -1,102 +0,0 @@ -// -// 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 org.apache.cloudstack.storage.datastore.util; - -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseResponse; - -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; - -@SuppressWarnings("unused") -public class ListElastistorVolumeResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "The ID of the volume") - private String id; - - @SerializedName(ApiConstants.NAME) - @Param(description = "The name of the volume") - private String name; - - @SerializedName("graceallowed") - @Param(description = "graceallowed") - private String graceAllowed; - - @SerializedName("deduplication") - @Param(description = "Deduplication") - private String deduplication; - - @SerializedName("compression") - @Param(description = "Compression") - private String compression; - - @SerializedName("sync") - @Param(description = "Synchronization") - private String sync; - - public String getGraceAllowed() { - return graceAllowed; - } - - public void setGraceAllowed(String graceAllowed) { - this.graceAllowed = graceAllowed; - } - - public String getDeduplication() { - return deduplication; - } - - public void setDeduplication(String deduplication) { - this.deduplication = deduplication; - } - - public String getCompression() { - return compression; - } - - public void setCompression(String compression) { - this.compression = compression; - } - - public String getSync() { - return sync; - } - - public void setSync(String sync) { - this.sync = sync; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return id; - } - -} diff --git a/plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/module.properties b/plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/module.properties deleted file mode 100755 index c494608871bb..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/module.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# 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. -# - -name=storage-volume-cloudbyte -parent=storage diff --git a/plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/spring-storage-volume-cloudbyte-context.xml b/plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/spring-storage-volume-cloudbyte-context.xml deleted file mode 100755 index 2d64871dbc9e..000000000000 --- a/plugins/storage/volume/cloudbyte/src/main/resources/META-INF/cloudstack/storage-volume-cloudbyte/spring-storage-volume-cloudbyte-context.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - diff --git a/plugins/storage/volume/datera/pom.xml b/plugins/storage/volume/datera/pom.xml deleted file mode 100644 index 6c4b5808a890..000000000000 --- a/plugins/storage/volume/datera/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - cloud-plugin-storage-volume-datera - Apache CloudStack Plugin - Storage Volume Datera Provider - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../../pom.xml - - - - org.apache.cloudstack - cloud-plugin-storage-volume-default - ${project.version} - - - org.apache.cloudstack - cloud-engine-storage-volume - ${project.version} - - - com.google.code.gson - gson - - - org.aspectj - aspectjtools - test - - - com.google.http-client - google-http-client - 1.17.0-rc - - - - - - maven-surefire-plugin - - - integration-test - - test - - - - - - - diff --git a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/driver/DateraPrimaryDataStoreDriver.java b/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/driver/DateraPrimaryDataStoreDriver.java deleted file mode 100644 index 62393610499a..000000000000 --- a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/driver/DateraPrimaryDataStoreDriver.java +++ /dev/null @@ -1,1896 +0,0 @@ -// 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 org.apache.cloudstack.storage.datastore.driver; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; -import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreCapabilities; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.command.CreateObjectAnswer; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.DateraObject; -import org.apache.cloudstack.storage.datastore.util.DateraUtil; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.ClusterDetailsVO; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor; -import com.cloud.storage.ResizeVolumePayload; -import com.cloud.storage.Snapshot; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StoragePool; -import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeDetailVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; -import com.cloud.storage.dao.VMTemplatePoolDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeDetailsDao; -import com.cloud.utils.Pair; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; -import com.google.common.base.Preconditions; -import com.google.common.primitives.Ints; - -import static com.cloud.utils.NumbersUtil.toHumanReadableSize; - -public class DateraPrimaryDataStoreDriver implements PrimaryDataStoreDriver { - protected Logger logger = LogManager.getLogger(getClass()); - private static final int s_lockTimeInSeconds = 300; - private static final int s_lowestHypervisorSnapshotReserve = 10; - - @Inject - private ClusterDao _clusterDao; - @Inject - private ClusterDetailsDao _clusterDetailsDao; - @Inject - private HostDao _hostDao; - @Inject - private SnapshotDao _snapshotDao; - @Inject - private SnapshotDetailsDao _snapshotDetailsDao; - @Inject - private PrimaryDataStoreDao _storagePoolDao; - @Inject - private StoragePoolDetailsDao _storagePoolDetailsDao; - @Inject - private VolumeDao _volumeDao; - @Inject - private VMTemplatePoolDao tmpltPoolDao; - @Inject - private PrimaryDataStoreDao storagePoolDao; - @Inject - private VolumeDetailsDao volumeDetailsDao; - @Inject - private SnapshotDetailsDao snapshotDetailsDao; - @Inject - private VolumeDataFactory volumeDataFactory; - - /** - * Returns a map which lists the capabilities that this storage device can - * offer. Currently supported STORAGE_SYSTEM_SNAPSHOT: Has the ability to create - * native snapshots CAN_CREATE_VOLUME_FROM_SNAPSHOT: Can create new volumes from - * native snapshots. CAN_CREATE_VOLUME_FROM_VOLUME: Device can clone volumes. - * This is used for template caching. - * @return a Map which determines the capabilities of the driver - */ - @Override - public Map getCapabilities() { - Map mapCapabilities = new HashMap<>(); - - mapCapabilities.put(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString(), Boolean.TRUE.toString()); - mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_SNAPSHOT.toString(), Boolean.TRUE.toString()); - mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString(), Boolean.TRUE.toString()); - mapCapabilities.put(DataStoreCapabilities.CAN_REVERT_VOLUME_TO_SNAPSHOT.toString(), Boolean.TRUE.toString()); - - return mapCapabilities; - } - - @Override - public DataTO getTO(DataObject data) { - return null; - } - - @Override - public DataStoreTO getStoreTO(DataStore store) { - return null; - } - - @Override - public ChapInfo getChapInfo(DataObject dataObject) { - // We don't support auth yet - return null; - } - - /** - * Fetches an App Instance from Datera, throws exception if it doesn't find it - * @param conn Datera Connection - * @param appInstanceName Name of the Aplication Instance - * @return application instance - */ - public DateraObject.AppInstance getDateraAppInstance(DateraObject.DateraConnection conn, String appInstanceName) { - - DateraObject.AppInstance appInstance = null; - try { - appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - } catch (DateraObject.DateraError dateraError) { - logger.warn("Error getting appInstance " + appInstanceName, dateraError); - throw new CloudRuntimeException(dateraError.getMessage()); - } - - if (appInstance == null) { - throw new CloudRuntimeException("App instance not found " + appInstanceName); - } - - return appInstance; - } - - /** - * Given a {@code dataObject} this function makes sure that the {@code host} has - * access to it. All hosts which are in the same cluster are added to an - * initiator group and that group is assigned to the appInstance. If an - * initiator group does not exist, it is created. If the host does not have an - * initiator registered on dataera, that is created and added to the initiator - * group - * @param dataObject The volume that needs to be accessed - * @param host The host which needs to access the volume - * @param dataStore Identifies which primary storage the volume resides in - * @return True if access is granted. False otherwise - */ - @Override - public boolean grantAccess(DataObject dataObject, Host host, DataStore dataStore) { - - logger.debug("grantAccess() called"); - - Preconditions.checkArgument(dataObject != null, "'dataObject' should not be 'null'"); - Preconditions.checkArgument(host != null, "'host' should not be 'null'"); - Preconditions.checkArgument(dataStore != null, "'dataStore' should not be 'null'"); - - long storagePoolId = dataStore.getId(); - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - String appInstanceName = getAppInstanceName(dataObject); - DateraObject.AppInstance appInstance = getDateraAppInstance(conn, appInstanceName); - - Preconditions.checkArgument(appInstance != null); - - long clusterId = host.getClusterId(); - - ClusterVO cluster = _clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(s_lockTimeInSeconds)) { - logger.debug("Couldn't lock the DB (in grantAccess) on the following string: " + cluster.getUuid()); - } - - try { - - DateraObject.InitiatorGroup initiatorGroup = null; - String initiatorGroupKey = DateraUtil.getInitiatorGroupKey(storagePoolId); - - List hosts = _hostDao.findByClusterId(clusterId); - - if (!DateraUtil.hostsSupport_iScsi(hosts)) { - logger.debug("hostsSupport_iScsi() :Host does NOT support iscsci"); - return false; - } - - // We don't have the initiator group, create one - String initiatorGroupName = DateraUtil.INITIATOR_GROUP_PREFIX + "-" + cluster.getUuid(); - logger.debug("Will use initiator group " + String.valueOf(initiatorGroupName)); - - initiatorGroup = DateraUtil.getInitiatorGroup(conn, initiatorGroupName); - - if (initiatorGroup == null) { - logger.debug("create initiator group " + String.valueOf(initiatorGroupName)); - initiatorGroup = DateraUtil.createInitiatorGroup(conn, initiatorGroupName); - // Save it to the DB - ClusterDetailsVO clusterDetail = new ClusterDetailsVO(clusterId, initiatorGroupKey, initiatorGroupName); - _clusterDetailsDao.persist(clusterDetail); - - } else { - initiatorGroup = DateraUtil.getInitiatorGroup(conn, initiatorGroupName); - } - - Preconditions.checkNotNull(initiatorGroup, "initiatorGroup should not be Null"); - - // We create an initiator for every host in this cluster and add it to the - // initiator group - addClusterHostsToInitiatorGroup(conn, clusterId, initiatorGroupName); - - // assign the initiatorgroup to appInstance - - if (!isInitiatorGroupAssignedToAppInstance(conn, initiatorGroup, appInstance)) { - DateraUtil.assignGroupToAppInstance(conn, initiatorGroupName, appInstanceName); - int retries = DateraUtil.DEFAULT_RETRIES; - while (!isInitiatorGroupAssignedToAppInstance(conn, initiatorGroup, appInstance) && retries > 0) { - Thread.sleep(DateraUtil.POLL_TIMEOUT_MS); - retries--; - } - - Preconditions.checkArgument(isInitiatorGroupAssignedToAppInstance(conn, initiatorGroup, appInstance), - "Initgroup is not assigned to appinstance"); - // FIXME: Sleep anyways - logger.debug("sleep " + String.valueOf(DateraUtil.POLL_TIMEOUT_MS) + " msec for ACL to be applied"); - - Thread.sleep(DateraUtil.POLL_TIMEOUT_MS); // ms - logger.debug( - "Initiator group " + String.valueOf(initiatorGroupName) + " is assigned to " + appInstanceName); - - } - - return true; - } catch (DateraObject.DateraError | UnsupportedEncodingException | InterruptedException dateraError) { - logger.warn(dateraError.getMessage(), dateraError); - throw new CloudRuntimeException("Unable to grant access to volume " + dateraError.getMessage()); - } finally { - lock.unlock(); - lock.releaseRef(); - } - } - - private void addClusterHostsToInitiatorGroup(DateraObject.DateraConnection conn, long clusterId, - String initiatorGroupName) throws DateraObject.DateraError, UnsupportedEncodingException { - - List clusterHosts = _hostDao.findByClusterId(clusterId); - DateraObject.InitiatorGroup initiatorGroup = DateraUtil.getInitiatorGroup(conn, initiatorGroupName); - - for (HostVO host : clusterHosts) { - - // check if we have an initiator for the host - String iqn = host.getStorageUrl(); - - DateraObject.Initiator initiator = DateraUtil.getInitiator(conn, iqn); - String initiatorName = ""; - // initiator can not be found, create it - if (initiator == null) { - - initiatorName = DateraUtil.INITIATOR_PREFIX + "-" + host.getUuid(); - initiator = DateraUtil.createInitiator(conn, initiatorName, iqn); - logger.debug("Initiator " + initiatorName + " with " + iqn + "added "); - - } - Preconditions.checkNotNull(initiator); - - if (!DateraUtil.isInitiatorPresentInGroup(initiator, initiatorGroup)) { - logger.debug("Add " + initiatorName + " to " + initiatorGroupName); - DateraUtil.addInitiatorToGroup(conn, initiator.getPath(), initiatorGroupName); - } - } - } - - /** - * Checks if an initiator group is assigned to an appInstance - * @param conn Datera connection - * @param initiatorGroup Initiator group to check - * @param appInstance App Instance - * @return True if initiator group is assigned to app instnace, false otherwise - * @throws DateraObject.DateraError - */ - - private boolean isInitiatorGroupAssignedToAppInstance(DateraObject.DateraConnection conn, - DateraObject.InitiatorGroup initiatorGroup, DateraObject.AppInstance appInstance) - throws DateraObject.DateraError { - - Map assignedInitiatorGroups = DateraUtil - .getAppInstanceInitiatorGroups(conn, appInstance.getName()); - - Preconditions.checkNotNull(assignedInitiatorGroups); - - for (DateraObject.InitiatorGroup ig : assignedInitiatorGroups.values()) { - if (initiatorGroup.getName().equals(ig.getName())) { - return true; - } - } - - return false; - } - - /** - * Removes access of the initiator group to which {@code host} belongs from the - * appInstance given by {@code dataObject} - * @param dataObject Datera volume - * @param host the host which is currently having access to the volume - * @param dataStore The primary store to which volume belongs - */ - @Override - public void revokeAccess(DataObject dataObject, Host host, DataStore dataStore) { - logger.debug("revokeAccess() called"); - - Preconditions.checkArgument(dataObject != null, "'dataObject' should not be 'null'"); - Preconditions.checkArgument(host != null, "'host' should not be 'null'"); - Preconditions.checkArgument(dataStore != null, "'dataStore' should not be 'null'"); - - String appInstanceName = getAppInstanceName(dataObject); - long clusterId = host.getClusterId(); - long storagePoolId = dataStore.getId(); - - ClusterVO cluster = _clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(s_lockTimeInSeconds)) { - logger.debug("Couldn't lock the DB (in revokeAccess) on the following string: " + cluster.getUuid()); - } - - try { - - String initiatorGroupName = DateraUtil.INITIATOR_GROUP_PREFIX + "-" + cluster.getUuid(); - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - DateraObject.AppInstance appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - DateraObject.InitiatorGroup initiatorGroup = DateraUtil.getInitiatorGroup(conn, initiatorGroupName); - - if (initiatorGroup != null && appInstance != null) { - - DateraUtil.removeGroupFromAppInstance(conn, initiatorGroupName, appInstanceName); - int retries = DateraUtil.DEFAULT_RETRIES; - while (isInitiatorGroupAssignedToAppInstance(conn, initiatorGroup, appInstance) && retries > 0) { - Thread.sleep(DateraUtil.POLL_TIMEOUT_MS); - retries--; - } - } - - } catch (DateraObject.DateraError | UnsupportedEncodingException | InterruptedException dateraError) { - String errMesg = String.format("Error revoking access for Volume : %s", dataObject); - logger.warn(errMesg, dateraError); - throw new CloudRuntimeException(errMesg); - } finally { - lock.unlock(); - lock.releaseRef(); - } - } - - /** - * Returns the size of template on this primary storage. If we already have a - * template on this storage, we return 0 - * @param templateInfo Information about the template - * @param storagePool The pool where we want to store the template - * @return Size in bytes - */ - @Override - public long getBytesRequiredForTemplate(TemplateInfo templateInfo, StoragePool storagePool) { - - List lstTemplatePoolRefs = tmpltPoolDao.listByPoolId(storagePool.getId()); - - if (lstTemplatePoolRefs != null) { - for (VMTemplateStoragePoolVO templatePoolRef : lstTemplatePoolRefs) { - if (templatePoolRef.getTemplateId() == templateInfo.getId()) { - // This indicates that we already have this template stored on this primary - // storage, so - // we do not require additional space. - return 0; - } - } - } - - // This indicates that we do not have a copy of this template on this primary - // storage, so - // we need to take it into consideration from a space standpoint (ex. when a new - // VM is spun - // up and wants to use this particular template for its root disk). - return getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, storagePool); - } - - /** - * Returns Datera appInstanceName - * @param dataObject volume or template - * @return Derived Datera appInstanceName based on dataObject, Eg. - * CS-V-ROOT-123-6db58e3f-14c4-45ac-95e9-60e3a00ce7d0 - */ - private String getAppInstanceName(DataObject dataObject) { - - ArrayList name = new ArrayList<>(); - - name.add(DateraUtil.APPINSTANCE_PREFIX); // CS - - String dataObjectTypeString = dataObject.getType().name(); // TEMPLATE, VOLUME, SNAPSHOT - String dataObjectTypeBrief; - dataObjectTypeBrief = StringUtils.substring(dataObjectTypeString, 0, 1); - name.add(dataObjectTypeBrief); // T, V - - switch (dataObject.getType()) { - case TEMPLATE: - TemplateInfo templateInfo = (TemplateInfo) dataObject; - - name.add(dataObject.getUuid()); // 6db58e3f-14c4-45ac-95e9-60e3a00ce7d0 - - // For cached templates, we will also add the storage pool ID - name.add(String.valueOf(dataObject.getDataStore().getId())); - break; - - case VOLUME: - VolumeInfo volumeInfo = (VolumeInfo) dataObject; - String volumeName = volumeInfo.getName(); - name.add(String.valueOf(volumeName)); - name.add(dataObject.getUuid()); // 6db58e3f-14c4-45ac-95e9-60e3a00ce7d0 - - VolumeVO volumeVo = _volumeDao.findById(dataObject.getId()); - logger.debug("volumeName : " + volumeName); - break; - - case SNAPSHOT: - name.add(dataObject.getUuid()); // 6db58e3f-14c4-45ac-95e9-60e3a00ce7d0 - - } - - String appInstanceName = StringUtils.join("-", name.toArray()); - return StringUtils.substring(appInstanceName, 0, DateraUtil.APPINSTANCE_MAX_LENTH); - } - - // Not being used right now as Datera doesn't support min IOPS - private long getDefaultMinIops(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(storagePoolId, - DateraUtil.CLUSTER_DEFAULT_MIN_IOPS); - - String clusterDefaultMinIops = storagePoolDetail.getValue(); - - return Long.parseLong(clusterDefaultMinIops); - } - - /** - * If user doesn't specify the IOPS, use this IOPS - * @param storagePoolId the primary storage - * @return default max IOPS for this storage configured when the storage is - * added - */ - private long getDefaultMaxIops(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(storagePoolId, - DateraUtil.CLUSTER_DEFAULT_MAX_IOPS); - - String clusterDefaultMaxIops = storagePoolDetail.getValue(); - - return Long.parseLong(clusterDefaultMaxIops); - } - - /** - * Return the default number of replicas to use (configured at storage addition - * time) - * @param storagePoolId the primary storage - * @return the number of replicas to use - */ - private int getNumReplicas(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(storagePoolId, - DateraUtil.NUM_REPLICAS); - - String clusterDefaultReplicas = storagePoolDetail.getValue(); - - return Integer.parseInt(clusterDefaultReplicas); - - } - - /** - * Return the default volume placement to use (configured at storage addition - * time) - * @param storagePoolId the primary storage - * @return volume placement string - */ - private String getVolPlacement(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(storagePoolId, - DateraUtil.VOL_PLACEMENT); - - String clusterDefaultVolPlacement = storagePoolDetail.getValue(); - - return clusterDefaultVolPlacement; - - } - - /** - * Return the default IP pool name to use (configured at storage addition time) - * @param storagePoolId the primary storage - * @return IP pool name - */ - private String getIpPool(long storagePoolId) { - String ipPool = DateraUtil.DEFAULT_IP_POOL; - StoragePoolDetailVO storagePoolDetail = _storagePoolDetailsDao.findDetail(storagePoolId, DateraUtil.IP_POOL); - if (storagePoolDetail != null) { - ipPool = storagePoolDetail.getValue(); - } - logger.debug("ipPool: " + ipPool); - return ipPool; - - } - - @Override - public long getUsedBytes(StoragePool storagePool) { - return getUsedBytes(storagePool, Long.MIN_VALUE); - } - - /** - * Get the total space used by all the entities on the storage. - * Total space = volume space + snapshot space + template space - * @param storagePool Primary storage - * @param volumeIdToIgnore Ignore this volume (used when we delete a volume and - * want to update the space) - * @return size in bytes - */ - private long getUsedBytes(StoragePool storagePool, long volumeIdToIgnore) { - long usedSpaceBytes = 0; - - List lstVolumes = _volumeDao.findNonDestroyedVolumesByPoolId(storagePool.getId(), null); - - if (lstVolumes != null) { - for (VolumeVO volume : lstVolumes) { - if (volume.getId() == volumeIdToIgnore) { - continue; - } - - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volume.getId(), DateraUtil.VOLUME_SIZE); - - if (volumeDetail != null && volumeDetail.getValue() != null) { - long volumeSizeGib = Long.parseLong(volumeDetail.getValue()); - long volumeSizeBytes = DateraUtil.gibToBytes((int) (volumeSizeGib)); - usedSpaceBytes += volumeSizeBytes; - } else { - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePool.getId(), - _storagePoolDetailsDao); - try { - - String appInstanceName = getAppInstanceName(volumeDataFactory.getVolume(volume.getId())); - DateraObject.AppInstance appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - if (appInstance != null) { - usedSpaceBytes += DateraUtil.gibToBytes(appInstance.getSize()); - } - } catch (DateraObject.DateraError dateraError) { - String errMesg = String.format("Error getting used bytes for storage pool : %s", storagePool); - logger.warn(errMesg, dateraError); - throw new CloudRuntimeException(errMesg); - } - } - } - } - - List lstSnapshots = _snapshotDao.listAll(); - - if (lstSnapshots != null) { - for (SnapshotVO snapshot : lstSnapshots) { - SnapshotDetailsVO snapshotDetails = _snapshotDetailsDao.findDetail(snapshot.getId(), - DateraUtil.STORAGE_POOL_ID); - - // if this snapshot belongs to the storagePool that was passed in - if (snapshotDetails != null && snapshotDetails.getValue() != null - && Long.parseLong(snapshotDetails.getValue()) == storagePool.getId()) { - snapshotDetails = _snapshotDetailsDao.findDetail(snapshot.getId(), DateraUtil.VOLUME_SIZE); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - long snapshotSize = Long.parseLong(snapshotDetails.getValue()); - - usedSpaceBytes += snapshotSize; - } - } - } - } - - List lstTemplatePoolRefs = tmpltPoolDao.listByPoolId(storagePool.getId()); - - if (lstTemplatePoolRefs != null) { - for (VMTemplateStoragePoolVO templatePoolRef : lstTemplatePoolRefs) { - usedSpaceBytes += templatePoolRef.getTemplateSize(); - } - } - logger.debug("usedSpaceBytes: " + toHumanReadableSize(usedSpaceBytes)); - - return usedSpaceBytes; - } - - /** - * Get total IOPS used by the storage array. Since Datera doesn't support min - * IOPS, return zero for now - * @param storagePool primary storage - * @return total IOPS used - */ - @Override - public long getUsedIops(StoragePool storagePool) { - long usedIops = 0; - return usedIops; - } - - /** - * Rreturns the size of the volume including the hypervisor snapshot reserve - * (HSR). - * @param dataObject Volume or a Template - * @param pool primary storage where it resides - * @return size in bytes - */ - - @Override - public long getDataObjectSizeIncludingHypervisorSnapshotReserve(DataObject dataObject, StoragePool pool) { - - long volumeSize = 0; - - switch (dataObject.getType()) { - case VOLUME: - - VolumeInfo volume = (VolumeInfo) dataObject; - volumeSize = volume.getSize(); - Integer hypervisorSnapshotReserve = volume.getHypervisorSnapshotReserve(); - - if (hypervisorSnapshotReserve != null) { - hypervisorSnapshotReserve = Math.max(hypervisorSnapshotReserve, s_lowestHypervisorSnapshotReserve); - volumeSize += volumeSize * (hypervisorSnapshotReserve / 100f); - } - logger.debug("Volume size: " + toHumanReadableSize(volumeSize)); - break; - - case TEMPLATE: - - TemplateInfo templateInfo = (TemplateInfo) dataObject; - long templateSize = templateInfo.getSize() != null ? templateInfo.getSize() : 0; - - if (templateInfo.getHypervisorType() == Hypervisor.HypervisorType.KVM) { - volumeSize = templateSize; - } else { - volumeSize = (long) (templateSize + templateSize * (s_lowestHypervisorSnapshotReserve / 100f)); - } - logger.debug("Template volume size:" + toHumanReadableSize(volumeSize)); - - break; - } - return volumeSize; - } - - /** - * Deletes a volume from Datera. If we are using native snapshots, we first - * check if the volume is holding a native snapshot, if it does, then we don't - * delete it from Datera but instead mark it so that when the snapshot is - * deleted, we delete the volume - * - * @param volumeInfo The volume which needs to be deleted - * @param storagePoolId Primary storage where volume resides - */ - private void deleteVolume(VolumeInfo volumeInfo, long storagePoolId) { - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - Long volumeStoragePoolId = volumeInfo.getPoolId(); - long volumeId = volumeInfo.getId(); - - if (volumeStoragePoolId == null) { - return; // this volume was never assigned to a storage pool, so no SAN volume should - // exist for it - } - - try { - - // If there are native snapshots on this appInstance, we want to keep it on - // Datera - // but remove it from cloudstack - if (shouldDeleteVolume(volumeId, null)) { - DateraUtil.deleteAppInstance(conn, getAppInstanceName(volumeInfo)); - } - - volumeDetailsDao.removeDetails(volumeId); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long usedBytes = getUsedBytes(storagePool, volumeId); - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - storagePoolDao.update(storagePoolId, storagePool); - - } catch (UnsupportedEncodingException | DateraObject.DateraError e) { - String errMesg = String.format("Error deleting app instance for Volume: %s", volumeInfo); - logger.warn(errMesg, e); - throw new CloudRuntimeException(errMesg); - } - } - - /** - * given a {@code volumeInfo} and {@code storagePoolId}, creates an App instance - * on Datera. Updates the usedBytes count in the DB for this storage pool. A - * volume could be created in 3 ways - * - * 1) A fresh volume with no data: New volume created from Cloudstack - * - * 2) A volume created from a native snapshot. This is used when creating volume - * from snapshot and native snapshots are supported - * - * 3) A volume created by cloning from another volume: This is used when - * creating volume from template or volume from snapshot stored as another - * volume when native snapshots are not supported by the hypervisor - * - * - * @param volumeInfo Info about the volume like size,QoS - * @param storagePoolId The pool to create the vo - * @return returns the IQN path which will be used by storage substem - * - */ - - private String createVolume(VolumeInfo volumeInfo, long storagePoolId) { - logger.debug("createVolume() called"); - - Preconditions.checkArgument(volumeInfo != null, "volumeInfo cannot be null"); - Preconditions.checkArgument(storagePoolId > 0, "storagePoolId should be > 0"); - - verifySufficientBytesForStoragePool(volumeInfo, storagePoolId); - - DateraObject.AppInstance appInstance; - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - long csSnapshotId = getCsIdForCloning(volumeInfo.getId(), "cloneOfSnapshot"); - long csTemplateId = getCsIdForCloning(volumeInfo.getId(), "cloneOfTemplate"); - logger.debug("csTemplateId is " + String.valueOf(csTemplateId)); - - try { - - if (csSnapshotId > 0) { - // creating volume from snapshot. The snapshot could either be a native snapshot - // or another volume. - logger.debug("Creating volume from snapshot "); - appInstance = createDateraClone(conn, csSnapshotId, volumeInfo, storagePoolId, DataObjectType.SNAPSHOT); - - } else if (csTemplateId > 0) { - - // create volume from template. Invoked when creating new ROOT volume - logger.debug("Creating volume from template "); - - appInstance = createDateraClone(conn, csTemplateId, volumeInfo, storagePoolId, DataObjectType.TEMPLATE); - String appInstanceName = appInstance.getName(); - - long volumeSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, - storagePoolDao.findById(storagePoolId)); - - // expand the template - if (volumeSize > DateraUtil.gibToBytes(appInstance.getSize())) { - - // Expand the volume to include HSR depending on the volume's service offering - DateraUtil.updateAppInstanceSize(conn, appInstanceName, DateraUtil.bytesToGib(volumeSize)); - - // refresh appInstance - appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - - Preconditions.checkNotNull(appInstance); - // update IOPS - if ((volumeInfo.getMaxIops() != null) && (volumeInfo.getMaxIops() != appInstance.getTotalIops())) { - int newIops = Ints.checkedCast(volumeInfo.getMaxIops()); - DateraUtil.updateAppInstanceIops(conn, appInstanceName, newIops); - } - // refresh appInstance - appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - } - - } else { - // Just create a standard volume - logger.debug("Creating a standard volume "); - appInstance = createDateraVolume(conn, volumeInfo, storagePoolId); - } - } catch (UnsupportedEncodingException | DateraObject.DateraError e) { - String errMesg = "Unable to create Volume Error: " + e.getMessage(); - logger.warn(errMesg); - throw new CloudRuntimeException(errMesg, e); - } - - if (appInstance == null) { - String errMesg = "appInstance returned null"; - logger.warn(errMesg); - throw new CloudRuntimeException(errMesg); - } - - Preconditions.checkNotNull(appInstance); - String iqn = appInstance.getIqn(); - String iqnPath = DateraUtil.generateIqnPath(iqn); - - VolumeVO volumeVo = _volumeDao.findById(volumeInfo.getId()); - logger.debug(String.format("volume: %s", volumeInfo)); - - volumeVo.set_iScsiName(iqnPath); - volumeVo.setFolder(appInstance.getName()); - volumeVo.setPoolType(Storage.StoragePoolType.IscsiLUN); - volumeVo.setPoolId(storagePoolId); - - _volumeDao.update(volumeVo.getId(), volumeVo); - - updateVolumeDetails(volumeVo.getId(), appInstance.getSize()); - - StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); - - _storagePoolDao.update(storagePoolId, storagePool); - - return appInstance.getIqn(); - } - - /** - * Helper function to create a Datera app instance. Throws an exception if - * unsuccessful - * @param conn Datera connection - * @param volumeInfo Volume information - * @param storagePoolId primary storage - * @return The AppInstance which is created - * @throws UnsupportedEncodingException - * @throws DateraObject.DateraError - */ - private DateraObject.AppInstance createDateraVolume(DateraObject.DateraConnection conn, VolumeInfo volumeInfo, - long storagePoolId) throws UnsupportedEncodingException, DateraObject.DateraError { - - logger.debug("createDateraVolume() called"); - DateraObject.AppInstance appInstance = null; - try { - - int minIops = Ints.checkedCast( - volumeInfo.getMinIops() != null ? volumeInfo.getMinIops() : getDefaultMinIops(storagePoolId)); - - // int minIops = Ints.checkedCast(volumeInfo.getMinIops()); - - int maxIops = Ints.checkedCast( - volumeInfo.getMaxIops() != null ? volumeInfo.getMaxIops() : getDefaultMaxIops(storagePoolId)); - - // int maxIops = Ints.checkedCast(volumeInfo.getMaxIops()); - - if (maxIops <= 0) { // We don't care about min iops for now - maxIops = Ints.checkedCast(getDefaultMaxIops(storagePoolId)); - } - - int replicas = getNumReplicas(storagePoolId); - String volumePlacement = getVolPlacement(storagePoolId); - String ipPool = getIpPool(storagePoolId); - - long volumeSizeBytes = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, - _storagePoolDao.findById(storagePoolId)); - int volumeSizeGib = DateraUtil.bytesToGib(volumeSizeBytes); - if (volumePlacement == null) { - appInstance = DateraUtil.createAppInstance(conn, getAppInstanceName(volumeInfo), volumeSizeGib, maxIops, - replicas); - } else { - appInstance = DateraUtil.createAppInstance(conn, getAppInstanceName(volumeInfo), volumeSizeGib, maxIops, - replicas, volumePlacement, ipPool); - } - } catch (Exception ex) { - logger.debug("createDateraVolume() failed"); - logger.error(ex); - } - return appInstance; - } - - /** - * This function creates a new AppInstance on datera by cloning. We can clone - * either from a volume snapshot (in case of native snapshots) or clone from - * another app Instance in case of templates or snapshots as volumes - * - * @param conn Datera Connection - * @param dataObjectId The ID of the clone, used to fetch details on how to - * clone - * @param volumeInfo Information about the clone - * @param storagePoolId Primary store to create the clone on - * @param dataType Type of the source (snapshot or template) - * @return The cloned AppInstance - */ - private DateraObject.AppInstance createDateraClone(DateraObject.DateraConnection conn, long dataObjectId, - VolumeInfo volumeInfo, long storagePoolId, DataObjectType dataType) - throws UnsupportedEncodingException, DateraObject.DateraError { - - logger.debug("createDateraClone() called"); - - String clonedAppInstanceName = getAppInstanceName(volumeInfo); - String baseAppInstanceName = null; - DateraObject.AppInstance appInstance = null; - String ipPool = getIpPool(storagePoolId); - - if (dataType == DataObjectType.SNAPSHOT) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(dataObjectId, DateraUtil.SNAPSHOT_ID); - - // Clone volume from a snapshot - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - logger.debug("Clone volume from a snapshot"); - - appInstance = DateraUtil.cloneAppInstanceFromSnapshot(conn, clonedAppInstanceName, - snapshotDetails.getValue(), ipPool); - - if (volumeInfo.getMaxIops() != null) { - - int totalIops = Math.min(DateraUtil.MAX_IOPS, Ints.checkedCast(volumeInfo.getMaxIops())); - DateraUtil.updateAppInstanceIops(conn, clonedAppInstanceName, totalIops); - appInstance = DateraUtil.getAppInstance(conn, clonedAppInstanceName); - } - - if (appInstance == null) { - throw new CloudRuntimeException("Unable to create an app instance from snapshot " - + volumeInfo.getId() + " type " + dataType); - } - return appInstance; - - } else { - - // Clone volume from an appInstance - logger.debug("Clone volume from an appInstance"); - - snapshotDetails = snapshotDetailsDao.findDetail(dataObjectId, DateraUtil.VOLUME_ID); - baseAppInstanceName = snapshotDetails.getValue(); - - } - } else if (dataType == DataObjectType.TEMPLATE) { - logger.debug("Clone volume from a template"); - - VMTemplateStoragePoolVO templatePoolRef = tmpltPoolDao.findByPoolTemplate(storagePoolId, dataObjectId, null); - - if (templatePoolRef != null) { - baseAppInstanceName = templatePoolRef.getLocalDownloadPath(); - } - } - - if (baseAppInstanceName == null) { - throw new CloudRuntimeException( - "Unable to find a base volume to clone " + volumeInfo.getUuid() + " type " + dataType); - } - - // Clone the app Instance - appInstance = DateraUtil.cloneAppInstanceFromVolume(conn, clonedAppInstanceName, baseAppInstanceName, ipPool); - - if (dataType == DataObjectType.TEMPLATE) { - // Only update volume parameters if clone from cached template - // Update maxIops - if (volumeInfo.getMaxIops() != null) { - - int totalIops = Math.min(DateraUtil.MAX_IOPS, Ints.checkedCast(volumeInfo.getMaxIops())); - - DateraUtil.updateAppInstanceIops(conn, clonedAppInstanceName, totalIops); - appInstance = DateraUtil.getAppInstance(conn, clonedAppInstanceName); - } - // Update placementMode - String newPlacementMode = getVolPlacement(storagePoolId); - if (newPlacementMode != null) { - DateraUtil.updateAppInstancePlacement(conn, clonedAppInstanceName, newPlacementMode); - } - appInstance = DateraUtil.getAppInstance(conn, clonedAppInstanceName); - } - if (appInstance == null) { - throw new CloudRuntimeException("Unable to create an app instance from snapshot or template " - + volumeInfo.getUuid() + " type " + dataType); - } - logger.debug("Datera - Cloned " + baseAppInstanceName + " to " + clonedAppInstanceName); - - return appInstance; - } - - /** - * This function gets invoked when you want to do operations on a snapshot. The - * snapshot could be a native snapshot and you want to create a template out of - * it. Since snapshots don't have an IQN, we create a temp volume for this - * snapshot which will be used to carry out further operations. This function - * also handles deletion of temp volumes. A flag in the snapshot details table - * decides which action is performed. - * - * @param snapshotInfo snapshot on Datera - * @param storagePoolId primary store ID - */ - private void createTempVolume(SnapshotInfo snapshotInfo, long storagePoolId) { - logger.debug("createTempVolume() from snapshot called"); - String ipPool = getIpPool(storagePoolId); - long csSnapshotId = snapshotInfo.getId(); - - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.SNAPSHOT_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException("'createTempVolume(SnapshotInfo, long)' should not be invoked unless " - + DateraUtil.SNAPSHOT_ID + " exists."); - } - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, "tempVolume"); - - if (snapshotDetails != null && snapshotDetails.getValue() != null - && snapshotDetails.getValue().equalsIgnoreCase("create")) { - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.SNAPSHOT_ID); - String snapshotName = snapshotDetails.getValue(); - - String clonedAppInstanceName = getAppInstanceName(snapshotInfo); - DateraObject.AppInstance clonedAppInstance; - - try { - clonedAppInstance = DateraUtil.cloneAppInstanceFromSnapshot(conn, clonedAppInstanceName, snapshotName, - ipPool); - DateraUtil.pollAppInstanceAvailable(conn, clonedAppInstanceName); - } catch (DateraObject.DateraError | UnsupportedEncodingException e) { - String errMesg = "Unable to create temp volume " + csSnapshotId + "Error:" + e.getMessage(); - logger.error(errMesg, e); - throw new CloudRuntimeException(errMesg, e); - } - - if (clonedAppInstance == null) { - throw new CloudRuntimeException("Unable to clone volume for snapshot " + snapshotName); - } - logger.debug("Temp app_instance " + clonedAppInstanceName + " created"); - addTempVolumeToDb(csSnapshotId, clonedAppInstanceName); - handleSnapshotDetails(csSnapshotId, DiskTO.IQN, DateraUtil.generateIqnPath(clonedAppInstance.getIqn())); - - } else if (snapshotDetails != null && snapshotDetails.getValue() != null - && snapshotDetails.getValue().equalsIgnoreCase("delete")) { - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.VOLUME_ID); - try { - logger.debug("Deleting temp app_instance " + snapshotDetails.getValue()); - DateraUtil.deleteAppInstance(conn, snapshotDetails.getValue()); - } catch (UnsupportedEncodingException | DateraObject.DateraError dateraError) { - String errMesg = "Error deleting temp volume " + dateraError.getMessage(); - throw new CloudRuntimeException(errMesg, dateraError); - } - - removeTempVolumeFromDb(csSnapshotId); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DiskTO.IQN); - snapshotDetailsDao.remove(snapshotDetails.getId()); - } else { - throw new CloudRuntimeException("Invalid state in 'createTempVolume(SnapshotInfo, long)'"); - } - } - - /** - * This function gets invoked when we want to create a volume that caches the - * template on the primary storage. This 'template volume' will then be cloned - * to create new ROOT volumes. - * - * @param templateInfo Information about the template like id, size - * @param storagePoolId the primary store to create this volume on - * @return IQN of the template volume - */ - public String createTemplateVolume(TemplateInfo templateInfo, long storagePoolId) { - logger.debug("createTemplateVolume() as cache template called"); - - verifySufficientBytesForStoragePool(templateInfo, storagePoolId); - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - String iqn = null; - String appInstanceName = null; - try { - - long templateSizeBytes = getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, - storagePoolDao.findById(storagePoolId)); - - logger.debug("cached VM template sizeBytes: " + toHumanReadableSize(templateSizeBytes)); - - int templateSizeGib = DateraUtil.bytesToGib(templateSizeBytes); - - int templateIops = DateraUtil.MAX_IOPS; - int replicaCount = getNumReplicas(storagePoolId); - appInstanceName = getAppInstanceName(templateInfo); - String volumePlacement = getVolPlacement(storagePoolId); - String ipPool = getIpPool(storagePoolId); - - logger.debug("cached VM template app_instance: " + appInstanceName + " ipPool: " + ipPool + " sizeGib: " + String.valueOf(templateSizeGib)); - DateraObject.AppInstance appInstance = DateraUtil.createAppInstance(conn, appInstanceName, templateSizeGib, - templateIops, replicaCount, volumePlacement, ipPool); - - if (appInstance == null) { - throw new CloudRuntimeException(String.format("Unable to create Template volume %s", templateInfo.getUuid())); - } - - iqn = appInstance.getIqn(); - - VMTemplateStoragePoolVO templatePoolRef = tmpltPoolDao.findByPoolTemplate(storagePoolId, - templateInfo.getId(), null); - - templatePoolRef.setInstallPath(DateraUtil.generateIqnPath(iqn)); - templatePoolRef.setLocalDownloadPath(appInstance.getName()); - templatePoolRef.setTemplateSize(DateraUtil.gibToBytes(appInstance.getSize())); - - tmpltPoolDao.update(templatePoolRef.getId(), templatePoolRef); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - - } catch (UnsupportedEncodingException | DateraObject.DateraError dateraError) { - if (DateraObject.DateraErrorTypes.ConflictError.equals(dateraError)) { - String errMesg = "template app Instance " + appInstanceName + " exists"; - logger.debug(errMesg, dateraError); - } else { - String errMesg = "Unable to create template app Instance " + dateraError.getMessage(); - logger.error(errMesg, dateraError); - throw new CloudRuntimeException(errMesg, dateraError); - } - } - return DateraUtil.generateIqnPath(iqn); - } - - /** - * Entry point into the create logic. The storage subsystem call this method to - * create various data objects (volume/snapshot/template) - * - * @param dataStore - * @param dataObject - * @param callback - */ - @Override - public void createAsync(DataStore dataStore, DataObject dataObject, - AsyncCompletionCallback callback) { - String iqn = null; - String errMsg = null; - - try { - if (dataObject.getType() == DataObjectType.VOLUME) { - logger.debug("createAsync - creating volume"); - iqn = createVolume((VolumeInfo) dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.SNAPSHOT) { - logger.debug("createAsync - creating snapshot"); - createTempVolume((SnapshotInfo) dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.TEMPLATE) { - logger.debug("createAsync - creating template"); - iqn = createTemplateVolume((TemplateInfo) dataObject, dataStore.getId()); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to createAsync"; - logger.error(errMsg); - } - } catch (Exception ex) { - errMsg = ex.getMessage(); - - logger.error(errMsg); - - if (callback == null) { - throw ex; - } - } - - if (callback != null) { - - CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errMsg == null, errMsg)); - - result.setResult(errMsg); - - callback.complete(result); - } - } - - /** - * Helper function which updates volume size in the volume_details table - * @param volumeId Volume information - * @param volumeSize Size in GB - */ - private void updateVolumeDetails(long volumeId, long volumeSize) { - VolumeDetailVO volumeDetailVo = volumeDetailsDao.findDetail(volumeId, DateraUtil.VOLUME_SIZE); - - if (volumeDetailVo == null || volumeDetailVo.getValue() == null) { - volumeDetailVo = new VolumeDetailVO(volumeId, DateraUtil.VOLUME_SIZE, String.valueOf(volumeSize), false); - - volumeDetailsDao.persist(volumeDetailVo); - } - } - - /** - * Entrypoint for delete operations. - * - * @param dataStore Primary storage - * @param dataObject object to delete - * @param callback used for async, complete the callback after the operation - * is done. - */ - @Override - public void deleteAsync(DataStore dataStore, DataObject dataObject, - AsyncCompletionCallback callback) { - String errMsg = null; - - try { - if (dataObject.getType() == DataObjectType.VOLUME) { - logger.debug("deleteAsync - deleting volume"); - deleteVolume((VolumeInfo) dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.SNAPSHOT) { - logger.debug("deleteAsync - deleting snapshot"); - deleteSnapshot((SnapshotInfo) dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.TEMPLATE) { - logger.debug("deleteAsync - deleting template"); - deleteTemplate((TemplateInfo) dataObject, dataStore.getId()); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to deleteAsync"; - } - } catch (Exception ex) { - errMsg = ex.getMessage(); - - logger.error(errMsg); - } - - CommandResult result = new CommandResult(); - - result.setResult(errMsg); - - callback.complete(result); - - } - - @Override - public void copyAsync(DataObject srcData, DataObject destData, - AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public void copyAsync(DataObject srcData, DataObject destData, - Host destHost, AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean canCopy(DataObject srcData, DataObject destData) { - return false; - } - - /** - * Entry point for taking a snapshot. A native snpashot is taken if the - * hypervisor supports it, otherwise a volume is created and the data is copied - * via the hypervisor and Cloudstack will treat this volume as a snapshot. - * - * @param snapshotInfo Snapshot information - * @param callback Async context - */ - @Override - public void takeSnapshot(SnapshotInfo snapshotInfo, AsyncCompletionCallback callback) { - logger.debug("takeSnapshot() called"); - - CreateCmdResult result; - - try { - - VolumeInfo volumeInfo = snapshotInfo.getBaseVolume(); - VolumeVO volumeVO = _volumeDao.findById(volumeInfo.getId()); - - long storagePoolId = volumeVO.getPoolId(); - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - String baseAppInstanceName = getAppInstanceName(volumeInfo); - - DateraObject.AppInstance baseAppInstance = DateraUtil.getAppInstance(conn, baseAppInstanceName); - - Preconditions.checkNotNull(baseAppInstance); - - SnapshotObjectTO snapshotObjectTo = (SnapshotObjectTO) snapshotInfo.getTO(); - - if (shouldTakeSnapshot(snapshotInfo.getId())) { - - DateraObject.VolumeSnapshot volumeSnapshot = DateraUtil.takeVolumeSnapshot(conn, baseAppInstanceName); - if (volumeSnapshot == null) { - logger.error(String.format("Unable to take native snapshot appInstance name: %s volume: %s", baseAppInstanceName, volumeInfo)); - throw new CloudRuntimeException("Unable to take native snapshot for volume " + volumeInfo.getUuid()); - } - - String snapshotName = baseAppInstanceName + ":" + volumeSnapshot.getTimestamp(); - updateSnapshotDetails(snapshotInfo.getId(), baseAppInstanceName, snapshotName, storagePoolId, - baseAppInstance.getSize()); - - snapshotObjectTo.setPath("DateraSnapshotId=" + snapshotName); - logger.info(" snapshot taken: " + snapshotName); - - } else { - - StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - long usedBytes = getUsedBytes(storagePool); - int volumeSizeGib = baseAppInstance.getSize(); - long volumeSizeBytes = DateraUtil.gibToBytes(volumeSizeGib); - String volumePlacement = getVolPlacement(storagePoolId); - String ipPool = getIpPool(storagePoolId); - - usedBytes += volumeSizeBytes; - - if (usedBytes > capacityBytes) { - throw new CloudRuntimeException( - "Insufficient amount of space remains in this primary storage to create a snapshot volume"); - } - - String appInstanceName = getAppInstanceName(snapshotInfo); - DateraObject.AppInstance snapshotAppInstance = DateraUtil.createAppInstance(conn, appInstanceName, - volumeSizeGib, DateraUtil.MAX_IOPS, getNumReplicas(storagePoolId), volumePlacement, ipPool); - - snapshotObjectTo.setPath(snapshotAppInstance.getName()); - String iqnPath = DateraUtil.generateIqnPath(snapshotAppInstance.getIqn()); - updateSnapshotDetails(snapshotInfo.getId(), snapshotAppInstance.getName(), storagePoolId, - snapshotAppInstance.getSize(), iqnPath); - - snapshotObjectTo.setPath("DateraVolumeId=" + snapshotAppInstance.getName()); - - storagePool.setUsedBytes(usedBytes); - // update size in storage pool - _storagePoolDao.update(storagePoolId, storagePool); - } - - CreateObjectAnswer createObjectAnswer = new CreateObjectAnswer(snapshotObjectTo); - - result = new CreateCmdResult(null, createObjectAnswer); - - result.setResult(null); - } catch (Exception ex) { - logger.debug(String.format("Failed to take CloudStack snapshot: %s", snapshotInfo), ex); - - result = new CreateCmdResult(null, new CreateObjectAnswer(ex.toString())); - - result.setResult(ex.toString()); - } - - callback.complete(result); - } - - /** - * If a native snapshot is used, this function updates the snapshot_detauls - * table with the correct attributes - * - * @param csSnapshotId Cloudstack snapshot ID - * @param volumeId Base volume ID - * @param newSnapshotId SnapshotID on Datera (appInstanceName:Timestamp) - * @param storagePoolId Primary storage - * @param newVolumeSize VolumeSize in GB - */ - private void updateSnapshotDetails(long csSnapshotId, String volumeId, String newSnapshotId, long storagePoolId, - long newVolumeSize) { - SnapshotDetailsVO snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.VOLUME_ID, - String.valueOf(volumeId), false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.SNAPSHOT_ID, String.valueOf(newSnapshotId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.STORAGE_POOL_ID, String.valueOf(storagePoolId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.VOLUME_SIZE, String.valueOf(newVolumeSize), - false); - - snapshotDetailsDao.persist(snapshotDetail); - } - - /** - * If a snapshot is represented as a volume, this function updates the - * snapshot_details table with the right attributes so that Cloudstack knows - * that this snapshot is a volume on the backend - * - * @param csSnapshotId Snapshot ID on Cloudstack - * @param snapshotAppInstanceName snapshot name on Datera - * : - * @param storagePoolId primary storage - * @param snapshotSizeGb snapshotSize - * @param snapshotIqn IQN of snapshot - */ - private void updateSnapshotDetails(long csSnapshotId, String snapshotAppInstanceName, long storagePoolId, - long snapshotSizeGb, String snapshotIqn) { - SnapshotDetailsVO snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.VOLUME_ID, - String.valueOf(snapshotAppInstanceName), false); - - _snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.STORAGE_POOL_ID, String.valueOf(storagePoolId), - false); - - _snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DateraUtil.VOLUME_SIZE, String.valueOf(snapshotSizeGb), - false); - - _snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, DiskTO.IQN, snapshotIqn, false); - - _snapshotDetailsDao.persist(snapshotDetail); - } - - /** - * Deletes snapshot on Datera - * @param snapshotInfo snapshot information - * @param storagePoolId primary storage - * @throws UnsupportedEncodingException - * @throws DateraObject.DateraError - */ - private void deleteSnapshot(SnapshotInfo snapshotInfo, long storagePoolId) - throws UnsupportedEncodingException, DateraObject.DateraError { - - long csSnapshotId = snapshotInfo.getId(); - - try { - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.SNAPSHOT_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - // Native snapshot being used, delete that - - String snapshotName = snapshotDetails.getValue(); - - DateraUtil.deleteVolumeSnapshot(conn, snapshotName); - - // check if the underlying volume needs to be deleted - SnapshotVO snapshot = _snapshotDao.findById(csSnapshotId); - VolumeVO volume = _volumeDao.findById(snapshot.getVolumeId()); - - if (volume == null) { - - // deleted from Cloudstack. Check if other snapshots are using this volume - volume = _volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId()); - - if (shouldDeleteVolume(snapshot.getVolumeId(), snapshot.getId())) { - DateraUtil.deleteAppInstance(conn, volume.getFolder()); - } - } - } else { - - // An App Instance is being used to support the CloudStack volume snapshot. - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.VOLUME_ID); - String appInstanceName = snapshotDetails.getValue(); - - DateraUtil.deleteAppInstance(conn, appInstanceName); - } - - snapshotDetailsDao.removeDetails(csSnapshotId); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - // getUsedBytes(StoragePool) will not include the snapshot to delete because it - // has already been deleted by this point - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - } catch (Exception ex) { - logger.debug(String.format("Error in 'deleteSnapshot(SnapshotInfo, long)'. CloudStack snapshot: %s", snapshotInfo), - ex); - throw ex; - } - } - - /** - * Deletes a template from Datera - * @param templateInfo Information about Template - * @param storagePoolId Primary storage - * @throws UnsupportedEncodingException - * @throws DateraObject.DateraError - */ - private void deleteTemplate(TemplateInfo templateInfo, long storagePoolId) - throws UnsupportedEncodingException, DateraObject.DateraError { - try { - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - String appInstanceName = getAppInstanceName(templateInfo); - - DateraUtil.deleteAppInstance(conn, appInstanceName); - - VMTemplateStoragePoolVO templatePoolRef = tmpltPoolDao.findByPoolTemplate(storagePoolId, - templateInfo.getId(), null); - - tmpltPoolDao.remove(templatePoolRef.getId()); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - // getUsedBytes(StoragePool) will not include the template to delete because the - // "template_spool_ref" table has already been updated by this point - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - } catch (Exception ex) { - logger.debug(String.format("Failed to delete template volume. CloudStack template: %s", templateInfo), ex); - - throw ex; - } - } - - /** - * Revert snapshot for a volume - * - * @param snapshotInfo Information about volume snapshot - * @param snapshotOnPrimaryStore Not used - * @throws CloudRuntimeException - */ - @Override - public void revertSnapshot(SnapshotInfo snapshotInfo, SnapshotInfo snapshotOnPrimaryStore, - AsyncCompletionCallback callback) { - - VolumeInfo volumeInfo = snapshotInfo.getBaseVolume(); - VolumeVO volumeVO = _volumeDao.findById(volumeInfo.getId()); - - long storagePoolId = volumeVO.getPoolId(); - long csSnapshotId = snapshotInfo.getId(); - logger.info(String.format("Datera - restoreVolumeSnapshot from snapshot %s to volume %s", snapshotInfo, volumeVO)); - - DateraObject.AppInstance appInstance; - - try { - - if (volumeVO == null || volumeVO.getRemoved() != null) { - String errMsg = "The volume that the snapshot belongs to no longer exists."; - - CommandResult commandResult = new CommandResult(); - - commandResult.setResult(errMsg); - - callback.complete(commandResult); - - return; - } - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.SNAPSHOT_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - // Native snapshot being used, restore snapshot from Datera AppInstance - - String snapshotName = snapshotDetails.getValue(); - - logger.info("Datera - restoreVolumeSnapshot: " + snapshotName); - - appInstance = DateraUtil.restoreVolumeSnapshot(conn, snapshotName); - - Preconditions.checkNotNull(appInstance); - - updateVolumeDetails(volumeInfo.getId(), appInstance.getSize()); - } - - CommandResult commandResult = new CommandResult(); - - callback.complete(commandResult); - - } catch (Exception ex) { - logger.debug(String.format("Error in 'revertSnapshot()'. CloudStack snapshot: %s", snapshotInfo), ex); - throw new CloudRuntimeException(ex.getMessage()); - } - - } - - /** - * Resizes a volume on Datera, shrinking is not allowed. Resize also takes into - * account the HSR - * @param dataObject volume to resize - * @param callback async context - */ - @Override - public void resize(DataObject dataObject, AsyncCompletionCallback callback) { - String iqn = null; - String errMsg = null; - - if (dataObject.getType() == DataObjectType.VOLUME) { - VolumeInfo volumeInfo = (VolumeInfo) dataObject; - String iqnPath = volumeInfo.get_iScsiName(); - iqn = DateraUtil.extractIqn(iqnPath); - - long storagePoolId = volumeInfo.getPoolId(); - ResizeVolumePayload payload = (ResizeVolumePayload) volumeInfo.getpayload(); - String appInstanceName = getAppInstanceName(volumeInfo); - long newSizeBytes = payload.newSize; - - Integer hsr = volumeInfo.getHypervisorSnapshotReserve(); - - if (payload.newSize != null || payload.newHypervisorSnapshotReserve != null) { - if (payload.newHypervisorSnapshotReserve != null) { - if (hsr != null) { - if (payload.newHypervisorSnapshotReserve > hsr) { - hsr = payload.newHypervisorSnapshotReserve; - } - } else { - hsr = payload.newHypervisorSnapshotReserve; - } - } - - newSizeBytes = getVolumeSizeIncludingHypervisorSnapshotReserve(payload.newSize, hsr); - } - - int newSize = DateraUtil.bytesToGib(newSizeBytes); - - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePoolId, _storagePoolDetailsDao); - - try { - - DateraObject.AppInstance appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - - Preconditions.checkNotNull(appInstance); - - if (appInstance.getSize() < newSize) { - DateraUtil.updateAppInstanceSize(conn, appInstanceName, Ints.checkedCast(newSize)); - } - - if (payload.newMaxIops != null && appInstance.getTotalIops() != payload.newMaxIops) { - DateraUtil.updateAppInstanceIops(conn, appInstanceName, Ints.checkedCast(payload.newMaxIops)); - } - - appInstance = DateraUtil.getAppInstance(conn, appInstanceName); - - Preconditions.checkNotNull(appInstance); - - VolumeVO volume = _volumeDao.findById(volumeInfo.getId()); - - volume.setMinIops(payload.newMinIops); - volume.setMaxIops(payload.newMaxIops); - - _volumeDao.update(volume.getId(), volume); - - updateVolumeDetails(volume.getId(), appInstance.getSize()); - - Preconditions.checkNotNull(appInstance); - - } catch (DateraObject.DateraError | UnsupportedEncodingException dateraError) { - dateraError.printStackTrace(); - } - - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to resize"; - } - - CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errMsg == null, errMsg)); - - result.setResult(errMsg); - - callback.complete(result); - } - - /** - * Adding temp volume to the snapshot_details table. This is used if we are - * using a native snapshot and we want to create a template out of the snapshot - * - * @param csSnapshotId Source snasphot - * @param tempVolumeName temp volume app instance on Datera - */ - private void addTempVolumeToDb(long csSnapshotId, String tempVolumeName) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.VOLUME_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException( - "'addTempVolumeId' should not be invoked unless " + DateraUtil.VOLUME_ID + " exists."); - } - - String originalVolumeId = snapshotDetails.getValue(); - - handleSnapshotDetails(csSnapshotId, DateraUtil.TEMP_VOLUME_ID, originalVolumeId); - handleSnapshotDetails(csSnapshotId, DateraUtil.VOLUME_ID, tempVolumeName); - } - - private void removeTempVolumeFromDb(long csSnapshotId) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DateraUtil.TEMP_VOLUME_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException( - "'removeTempVolumeId' should not be invoked unless " + DateraUtil.TEMP_VOLUME_ID + " exists."); - } - - String originalVolumeId = snapshotDetails.getValue(); - - handleSnapshotDetails(csSnapshotId, DateraUtil.VOLUME_ID, originalVolumeId); - - snapshotDetailsDao.remove(snapshotDetails.getId()); - } - - /** - * Helper function to update snapshot_details table - * - * @param csSnapshotId Snapshot - * @param name attribute name - * @param value attribute value - */ - private void handleSnapshotDetails(long csSnapshotId, String name, String value) { - snapshotDetailsDao.removeDetail(csSnapshotId, name); - SnapshotDetailsVO snapshotDetails = new SnapshotDetailsVO(csSnapshotId, name, value, false); - snapshotDetailsDao.persist(snapshotDetails); - } - - private void verifySufficientBytesForStoragePool(DataObject dataObject, long storagePoolId) { - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long requestedBytes = getDataObjectSizeIncludingHypervisorSnapshotReserve(dataObject, storagePool); - - verifySufficientBytesForStoragePool(requestedBytes, storagePoolId); - } - - private void verifySufficientBytesForStoragePool(long requestedBytes, long storagePoolId) { - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - long usedBytes = getUsedBytes(storagePool); - - usedBytes += requestedBytes; - - if (usedBytes > capacityBytes) { - throw new CloudRuntimeException("Insufficient amount of space remains in this primary storage"); - } - } - - /** - * Returns true if we can take a native snapshot else returns false. Set in - * StorageSystemSnapshotStrategy - * @param snapshotId Snapshot - * @return true if native snapshot, false otherwise - */ - private boolean shouldTakeSnapshot(long snapshotId) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(snapshotId, "takeSnapshot"); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - return new Boolean(snapshotDetails.getValue()); - } - - return false; - } - - private long getCsIdForCloning(long volumeId, String cloneOf) { - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volumeId, cloneOf); - - if (volumeDetail != null && volumeDetail.getValue() != null) { - return new Long(volumeDetail.getValue()); - } - - return Long.MIN_VALUE; - } - - /** - * Checks if the volume can be safely deleted. ie it has no native snapshots - * @param csVolumeId Volume - * @param snapshotToIgnoreId Used to check if this is the only snapshot on the - * volume - * @return true if we can delete, false otherwise - */ - private boolean shouldDeleteVolume(Long csVolumeId, Long snapshotToIgnoreId) { - - List lstSnapshots = getNonDestroyedSnapshots(csVolumeId); - - for (SnapshotVO snapshot : lstSnapshots) { - if (snapshotToIgnoreId != null && snapshot.getId() == snapshotToIgnoreId) { - continue; - } - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(snapshot.getId(), DateraUtil.SNAPSHOT_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - return false; - } - } - - return true; - } - - private List getNonDestroyedSnapshots(long csVolumeId) { - List lstSnapshots = _snapshotDao.listByVolumeId(csVolumeId); - - if (lstSnapshots == null) { - lstSnapshots = new ArrayList<>(); - } - - List lstSnapshots2 = new ArrayList<>(); - - for (SnapshotVO snapshot : lstSnapshots) { - if (!Snapshot.State.Destroyed.equals(snapshot.getState())) { - lstSnapshots2.add(snapshot); - } - } - - return lstSnapshots2; - } - - private long getVolumeSizeIncludingHypervisorSnapshotReserve(long volumeSize, Integer hypervisorSnapshotReserve) { - if (hypervisorSnapshotReserve != null) { - hypervisorSnapshotReserve = Math.max(hypervisorSnapshotReserve, s_lowestHypervisorSnapshotReserve); - - volumeSize += volumeSize * (hypervisorSnapshotReserve / 100f); - } - - return volumeSize; - } - - @Override - public void handleQualityOfServiceForVolumeMigration(VolumeInfo volumeInfo, - QualityOfServiceState qualityOfServiceState) { - } - - @Override - public boolean canProvideStorageStats() { - return false; - } - - @Override - public Pair getStorageStats(StoragePool storagePool) { - return null; - } - - @Override - public boolean canProvideVolumeStats() { - return false; - } - - @Override - public Pair getVolumeStats(StoragePool storagePool, String volumeId) { - return null; - } - - @Override - public boolean canHostAccessStoragePool(Host host, StoragePool pool) { - return true; - } - - @Override - public boolean isVmInfoNeeded() { - return false; - } - - @Override - public void provideVmInfo(long vmId, long volumeId) { - } - - @Override - public boolean isVmTagsNeeded(String tagKey) { - return false; - } - - @Override - public void provideVmTags(long vmId, long volumeId, String tagValue) { - } - - @Override - public boolean isStorageSupportHA(StoragePoolType type) { - return false; - } - - @Override - public void detachVolumeFromAllStorageNodes(Volume volume) { - } - - @Override - public boolean volumesRequireGrantAccessWhenUsed() { - return true; - } -} diff --git a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/DateraPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/DateraPrimaryDataStoreLifeCycle.java deleted file mode 100644 index 537243dd3214..000000000000 --- a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/DateraPrimaryDataStoreLifeCycle.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.lifecycle; - -import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.capacity.CapacityManager; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceManager; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolAutomation; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; -import com.cloud.storage.dao.StoragePoolAndAccessGroupMapDao; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.exception.CloudRuntimeException; -import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.DateraUtil; -import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; - -import javax.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class DateraPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { - @Inject - private CapacityManager _capacityMgr; - @Inject - private DataCenterDao zoneDao; - @Inject - private ClusterDao _clusterDao; - @Inject - private ClusterDetailsDao _clusterDetailsDao; - @Inject - private PrimaryDataStoreDao storagePoolDao; - @Inject - private HostDao _hostDao; - @Inject - private PrimaryDataStoreHelper dataStoreHelper; - @Inject - private ResourceManager _resourceMgr; - @Inject - private SnapshotDao _snapshotDao; - @Inject - private SnapshotDetailsDao _snapshotDetailsDao; - @Inject - private StorageManager _storageMgr; - @Inject - private StoragePoolHostDao _storagePoolHostDao; - @Inject - private StoragePoolAutomation storagePoolAutomation; - @Inject - private StoragePoolAndAccessGroupMapDao storagePoolAndAccessGroupMapDao; - - @Override - public DataStore initialize(Map dsInfos) { - - String url = (String) dsInfos.get("url"); - Long zoneId = (Long) dsInfos.get("zoneId"); - Long podId = (Long) dsInfos.get("podId"); - Long clusterId = (Long) dsInfos.get("clusterId"); - String storagePoolName = (String) dsInfos.get("name"); - String providerName = (String) dsInfos.get("providerName"); - Long capacityBytes = (Long) dsInfos.get("capacityBytes"); - Long capacityIops = (Long) dsInfos.get("capacityIops"); - String tags = (String) dsInfos.get("tags"); - String storageAccessGroups = (String)dsInfos.get(ApiConstants.STORAGE_ACCESS_GROUPS); - boolean isTagARule = (Boolean)dsInfos.get("isTagARule"); - @SuppressWarnings("unchecked") - Map details = (Map) dsInfos.get("details"); - String domainName = details.get("domainname"); - - String storageVip = DateraUtil.getStorageVip(url); - - int storagePort = DateraUtil.getStoragePort(url); - int numReplicas = DateraUtil.getNumReplicas(url); - String volPlacement = DateraUtil.getVolPlacement(url); - String clusterAdminUsername = DateraUtil.getValue(DateraUtil.CLUSTER_ADMIN_USERNAME, url); - String clusterAdminPassword = DateraUtil.getValue(DateraUtil.CLUSTER_ADMIN_PASSWORD, url); - String uuid; - String randomString; - - PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); - - // checks if primary datastore is clusterwide. If so, uses the clusterId to set - // the uuid and then sets the podId and clusterId parameters - if (clusterId != null) { - if (podId == null) { - throw new CloudRuntimeException("The Pod ID must be specified."); - } - if (zoneId == null) { - throw new CloudRuntimeException("The Zone ID must be specified."); - } - ClusterVO cluster = _clusterDao.findById(clusterId); - String clusterUuid = cluster.getUuid(); - randomString = DateraUtil.generateUUID(clusterUuid); - // uuid = DateraUtil.PROVIDER_NAME + "_" + cluster.getUuid() + "_" + storageVip - // + "_" + clusterAdminUsername + "_" + numReplicas + "_" + volPlacement; - uuid = DateraUtil.PROVIDER_NAME + "_" + clusterUuid + "_" + randomString; - logger.debug("Datera - Setting Datera cluster-wide primary storage uuid to " + uuid); - parameters.setPodId(podId); - parameters.setClusterId(clusterId); - - HypervisorType hypervisorType = getHypervisorTypeForCluster(clusterId); - - if (!isSupportedHypervisorType(hypervisorType)) { - throw new CloudRuntimeException(hypervisorType + " is not a supported hypervisor type."); - } - - } - // sets the uuid with zoneid in it - else { - DataCenterVO zone = zoneDao.findById(zoneId); - String zoneUuid = zone.getUuid(); - randomString = DateraUtil.generateUUID(zoneUuid); - // uuid = DateraUtil.PROVIDER_NAME + "_" + zone.getUuid() + "_" + storageVip + - // "_" + clusterAdminUsername + "_" + numReplicas + "_" + volPlacement; - uuid = DateraUtil.PROVIDER_NAME + "_" + zoneUuid + "_" + randomString; - - logger.debug("Datera - Setting Datera zone-wide primary storage uuid to " + uuid); - } - if (capacityBytes == null || capacityBytes <= 0) { - throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0."); - } - - if (capacityIops == null || capacityIops <= 0) { - throw new IllegalArgumentException("'capacityIops' must be present and greater than 0."); - } - - if (domainName == null) { - domainName = "ROOT"; - logger.debug("setting the domain to ROOT"); - } - logger.debug("Datera - domainName: " + domainName); - - parameters.setHost(storageVip); - parameters.setPort(storagePort); - parameters.setPath(DateraUtil.getModifiedUrl(url)); - parameters.setType(StoragePoolType.Iscsi); - parameters.setUuid(uuid); - parameters.setZoneId(zoneId); - parameters.setName(storagePoolName); - parameters.setProviderName(providerName); - parameters.setManaged(true); - parameters.setCapacityBytes(capacityBytes); - parameters.setUsedBytes(0); - parameters.setCapacityIops(capacityIops); - parameters.setHypervisorType(HypervisorType.Any); - parameters.setTags(tags); - parameters.setStorageAccessGroups(storageAccessGroups); - parameters.setIsTagARule(isTagARule); - parameters.setDetails(details); - - String managementVip = DateraUtil.getManagementVip(url); - int managementPort = DateraUtil.getManagementPort(url); - - details.put(DateraUtil.MANAGEMENT_VIP, managementVip); - details.put(DateraUtil.MANAGEMENT_PORT, String.valueOf(managementPort)); - details.put(DateraUtil.CLUSTER_ADMIN_USERNAME, clusterAdminUsername); - details.put(DateraUtil.CLUSTER_ADMIN_PASSWORD, clusterAdminPassword); - - long lClusterDefaultMinIops = 100; - long lClusterDefaultMaxIops = 15000; - - try { - String clusterDefaultMinIops = DateraUtil.getValue(DateraUtil.CLUSTER_DEFAULT_MIN_IOPS, url); - - if (clusterDefaultMinIops != null && clusterDefaultMinIops.trim().length() > 0) { - lClusterDefaultMinIops = Long.parseLong(clusterDefaultMinIops); - } - } catch (NumberFormatException ex) { - logger.warn("Cannot parse the setting of " + DateraUtil.CLUSTER_DEFAULT_MIN_IOPS - + ", using default value: " + lClusterDefaultMinIops + ". Exception: " + ex); - } - - try { - String clusterDefaultMaxIops = DateraUtil.getValue(DateraUtil.CLUSTER_DEFAULT_MAX_IOPS, url); - - if (clusterDefaultMaxIops != null && clusterDefaultMaxIops.trim().length() > 0) { - lClusterDefaultMaxIops = Long.parseLong(clusterDefaultMaxIops); - } - } catch (NumberFormatException ex) { - logger.warn("Cannot parse the setting of " + DateraUtil.CLUSTER_DEFAULT_MAX_IOPS - + ", using default value: " + lClusterDefaultMaxIops + ". Exception: " + ex); - } - - if (lClusterDefaultMinIops > lClusterDefaultMaxIops) { - throw new CloudRuntimeException("The parameter '" + DateraUtil.CLUSTER_DEFAULT_MIN_IOPS - + "' must be less than or equal to the parameter '" + DateraUtil.CLUSTER_DEFAULT_MAX_IOPS + "'."); - } - - if (numReplicas < DateraUtil.MIN_NUM_REPLICAS || numReplicas > DateraUtil.MAX_NUM_REPLICAS) { - throw new CloudRuntimeException("The parameter '" + DateraUtil.NUM_REPLICAS + "' must be between " - + DateraUtil.CLUSTER_DEFAULT_MAX_IOPS + "' and " + DateraUtil.MAX_NUM_REPLICAS); - } - - details.put(DateraUtil.CLUSTER_DEFAULT_MIN_IOPS, String.valueOf(lClusterDefaultMinIops)); - details.put(DateraUtil.CLUSTER_DEFAULT_MAX_IOPS, String.valueOf(lClusterDefaultMaxIops)); - - details.put(DateraUtil.NUM_REPLICAS, String.valueOf(DateraUtil.getNumReplicas(url))); - details.put(DateraUtil.VOL_PLACEMENT, String.valueOf(DateraUtil.getVolPlacement(url))); - details.put(DateraUtil.IP_POOL, String.valueOf(DateraUtil.getIpPool(url))); - - return dataStoreHelper.createPrimaryDataStore(parameters); - } - - @Override - public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { - return true; // should be ignored for zone-wide-only plug-ins like - } - - @Override - public boolean attachCluster(DataStore datastore, ClusterScope scope) { - PrimaryDataStoreInfo primaryDataStoreInfo = (PrimaryDataStoreInfo) datastore; - List hostsToConnect = _resourceMgr.getEligibleUpHostsInClusterForStorageConnection(primaryDataStoreInfo); - - logger.debug(String.format("Attaching the pool to each of the hosts %s in the cluster: %s", hostsToConnect, primaryDataStoreInfo.getClusterId())); - - List poolHosts = new ArrayList(); - - for (HostVO host : hostsToConnect) { - try { - _storageMgr.connectHostToSharedPool(host, primaryDataStoreInfo.getId()); - - poolHosts.add(host); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + primaryDataStoreInfo, e); - } - } - - if (poolHosts.isEmpty()) { - logger.warn("No host can access storage pool '" + primaryDataStoreInfo + "' on cluster '" - + primaryDataStoreInfo.getClusterId() + "'."); - - storagePoolDao.expunge(primaryDataStoreInfo.getId()); - - throw new CloudRuntimeException("Failed to access storage pool"); - } - - dataStoreHelper.attachCluster(datastore); - - return true; - // throw new UnsupportedOperationException("Only Zone-wide scope is supported - // with the Datera Storage driver"); - } - - @Override - public boolean attachZone(DataStore dataStore, ZoneScope scope, HypervisorType hypervisorType) { - dataStoreHelper.attachZone(dataStore); - - List hostsToConnect = new ArrayList<>(); - HypervisorType[] hypervisorTypes = {HypervisorType.XenServer, HypervisorType.VMware, HypervisorType.KVM}; - - for (HypervisorType type : hypervisorTypes) { - hostsToConnect.addAll(_resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, scope.getScopeId(), type)); - } - - logger.debug(String.format("In createPool. Attaching the pool to each of the hosts in %s.", hostsToConnect)); - for (HostVO host : hostsToConnect) { - try { - _storageMgr.connectHostToSharedPool(host, dataStore.getId()); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); - } - } - - return true; - } - - @Override - public boolean maintain(DataStore dataStore) { - storagePoolAutomation.maintain(dataStore); - dataStoreHelper.maintain(dataStore); - - return true; - } - - @Override - public boolean cancelMaintain(DataStore store) { - dataStoreHelper.cancelMaintain(store); - storagePoolAutomation.cancelMaintain(store); - - return true; - } - - @Override - public boolean deleteDataStore(DataStore store) { - List lstSnapshots = _snapshotDao.listAll(); - - if (lstSnapshots != null) { - for (SnapshotVO snapshot : lstSnapshots) { - SnapshotDetailsVO snapshotDetails = _snapshotDetailsDao.findDetail(snapshot.getId(), - DateraUtil.STORAGE_POOL_ID); - - // if this snapshot belongs to the storagePool that was passed in - if (snapshotDetails != null && snapshotDetails.getValue() != null - && Long.parseLong(snapshotDetails.getValue()) == store.getId()) { - throw new CloudRuntimeException( - "This primary storage cannot be deleted because it currently contains one or more snapshots."); - } - } - } - - return dataStoreHelper.deletePrimaryDataStore(store); - } - - @Override - public boolean migrateToObjectStore(DataStore store) { - return false; - } - - @Override - public void updateStoragePool(StoragePool storagePool, Map details) { - StoragePoolVO storagePoolVo = storagePoolDao.findById(storagePool.getId()); - - String strCapacityBytes = details.get(PrimaryDataStoreLifeCycle.CAPACITY_BYTES); - Long capacityBytes = strCapacityBytes != null ? Long.parseLong(strCapacityBytes) : null; - - if (capacityBytes != null) { - long usedBytes = _capacityMgr.getUsedBytes(storagePoolVo); - - if (capacityBytes < usedBytes) { - throw new CloudRuntimeException( - "Cannot reduce the number of bytes for this storage pool as it would lead to an insufficient number of bytes"); - } - } - - String strCapacityIops = details.get(PrimaryDataStoreLifeCycle.CAPACITY_IOPS); - Long capacityIops = strCapacityIops != null ? Long.parseLong(strCapacityIops) : null; - - if (capacityIops != null) { - long usedIops = _capacityMgr.getUsedIops(storagePoolVo); - - if (capacityIops < usedIops) { - throw new CloudRuntimeException( - "Cannot reduce the number of IOPS for this storage pool as it would lead to an insufficient number of IOPS"); - } - } - } - - @Override - public void enableStoragePool(DataStore dataStore) { - dataStoreHelper.enable(dataStore); - } - - @Override - public void disableStoragePool(DataStore dataStore) { - dataStoreHelper.disable(dataStore); - } - - @Override - public void changeStoragePoolScopeToZone(DataStore store, ClusterScope clusterScope, HypervisorType hypervisorType) { - /* - * We need to attach all VMware, Xenserver and KVM hosts in the zone. - * So pass hypervisorType as null. - */ - super.changeStoragePoolScopeToZone(store, clusterScope, null); - } - - private HypervisorType getHypervisorTypeForCluster(long clusterId) { - ClusterVO cluster = _clusterDao.findById(clusterId); - - if (cluster == null) { - throw new CloudRuntimeException("Cluster ID '" + clusterId + "' was not found in the database."); - } - - return cluster.getHypervisorType(); - } - - private static boolean isSupportedHypervisorType(HypervisorType hypervisorType) { - return HypervisorType.XenServer.equals(hypervisorType) || HypervisorType.VMware.equals(hypervisorType) - || HypervisorType.KVM.equals(hypervisorType); - } - - private HypervisorType getHypervisorType(long hostId) { - HostVO host = _hostDao.findById(hostId); - - if (host != null) { - return host.getHypervisorType(); - } - - return HypervisorType.None; - } -} diff --git a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraHostListener.java b/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraHostListener.java deleted file mode 100644 index 08bc89737f26..000000000000 --- a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraHostListener.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.DateraObject; -import org.apache.cloudstack.storage.datastore.util.DateraUtil; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ModifyStoragePoolAnswer; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.agent.api.ModifyTargetsCommand; -import com.cloud.alert.AlertManager; -import com.cloud.dc.ClusterDetailsDao; -import com.cloud.dc.ClusterDetailsVO; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.dao.VMInstanceDao; - -public class DateraHostListener implements HypervisorHostListener { - protected Logger logger = LogManager.getLogger(getClass()); - - @Inject private AgentManager _agentMgr; - @Inject private AlertManager _alertMgr; - @Inject private ClusterDao _clusterDao; - @Inject private ClusterDetailsDao _clusterDetailsDao; - @Inject private DataStoreManager _dataStoreMgr; - @Inject private HostDao _hostDao; - @Inject private PrimaryDataStoreDao _storagePoolDao; - @Inject private StoragePoolDetailsDao _storagePoolDetailsDao; - @Inject private StoragePoolHostDao storagePoolHostDao; - @Inject private VMInstanceDao _vmDao; - @Inject private VolumeDao _volumeDao; - - @Override - public boolean hostAdded(long hostId) { - return true; - } - - @Override - public boolean hostConnect(long hostId, long storagePoolId) { - - HostVO host = _hostDao.findById(hostId); - - if (host == null) { - logger.error("Failed to add host by HostListener as host was not found with id : {}", hostId); - return false; - } - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(storagePoolId, hostId); - - if (storagePoolHost == null) { - storagePoolHost = new StoragePoolHostVO(storagePoolId, hostId, ""); - - storagePoolHostDao.persist(storagePoolHost); - } - - if (host.getHypervisorType().equals(HypervisorType.XenServer)) { - handleXenServer(host.getClusterId(), host.getId(), storagePoolId); - } - else if (host.getHypervisorType().equals(HypervisorType.KVM)) { - //handleKVM(host.getClusterId(), host.getId(), storagePoolId); - handleKVM(hostId, storagePoolId); - } - - return true; - } - - @Override - public boolean hostDisconnected(long hostId, long storagePoolId) { - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(storagePoolId, hostId); - - if (storagePoolHost != null) { - storagePoolHostDao.deleteStoragePoolHostDetails(hostId, storagePoolId); - } - - return true; - } - - @Override - public boolean hostAboutToBeRemoved(long hostId) { - HostVO host = _hostDao.findById(hostId); - - handleVMware(host, false); - - return true; - - } - - @Override - public boolean hostRemoved(long hostId, long clusterId) { - - ClusterVO clusterVO = _clusterDao.findById(clusterId); - HostVO hostVO = _hostDao.findByIdIncludingRemoved(hostId); - String initiatorName = DateraUtil.INITIATOR_PREFIX + "-" + hostVO.getUuid(); - - int s_lockTimeInSeconds = 5; - - GlobalLock lock = GlobalLock.getInternLock(clusterVO.getUuid()); - - if (!lock.lock(s_lockTimeInSeconds)) { - String errMsg = "Couldn't lock the DB on the following string: " + clusterVO.getUuid(); - - logger.debug(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - try { - List storagePools = _storagePoolDao.findPoolsByProvider(DateraUtil.PROVIDER_NAME); - - if (storagePools != null && storagePools.size() > 0) { - for (StoragePoolVO storagePool : storagePools) { - ClusterDetailsVO clusterDetail = _clusterDetailsDao.findDetail(clusterId, DateraUtil.getInitiatorGroupKey(storagePool.getId())); - - String initiatorGroupName = clusterDetail != null ? clusterDetail.getValue() : null; - - if (initiatorGroupName != null && DateraUtil.hostSupport_iScsi(hostVO) ) { - DateraObject.DateraConnection conn = DateraUtil.getDateraConnection(storagePool.getId(), _storagePoolDetailsDao); - DateraObject.Initiator initiator = DateraUtil.getInitiator(conn, hostVO.getStorageUrl()); - DateraObject.InitiatorGroup initiatorGroup = DateraUtil.getInitiatorGroup(conn, initiatorGroupName); - - if (initiator!= null && DateraUtil.isInitiatorPresentInGroup(initiator, initiatorGroup)) { - DateraUtil.removeInitiatorFromGroup(conn, initiator.getPath(), initiatorGroupName); - } - } - } - } - - } catch (DateraObject.DateraError | UnsupportedEncodingException e) { - logger.warn("Error while removing host from initiator groups ", e); - } finally { - lock.unlock(); - lock.releaseRef(); - } - - return true; - } - - @Override - public boolean hostEnabled(long hostId) { - return true; - } - - private void handleXenServer(long clusterId, long hostId, long storagePoolId) { - List storagePaths = getStoragePaths(clusterId, storagePoolId); - - StoragePool storagePool = (StoragePool)_dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - - for (String storagePath : storagePaths) { - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, storagePool); - - cmd.setStoragePath(storagePath); - - sendModifyStoragePoolCommand(cmd, storagePool, hostId); - } - } - - private void handleVMware(HostVO host, boolean add) { - if (HypervisorType.VMware.equals(host.getHypervisorType())) { - List storagePools = _storagePoolDao.findPoolsByProvider(DateraUtil.PROVIDER_NAME); - - if (storagePools != null && storagePools.size() > 0) { - List> targets = new ArrayList<>(); - - for (StoragePoolVO storagePool : storagePools) { - List> targetsForClusterAndStoragePool = getTargets(host.getClusterId(), storagePool.getId()); - - targets.addAll(targetsForClusterAndStoragePool); - } - - ModifyTargetsCommand cmd = new ModifyTargetsCommand(); - - cmd.setAdd(add); - cmd.setTargets(targets); - - sendModifyTargetsCommand(cmd, host.getId()); - } - } - } - - private void handleKVM(long clusterId, long hostId, long storagePoolId) { - List storagePaths = getStoragePaths(clusterId, storagePoolId); - - StoragePool storagePool = (StoragePool)_dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - - for (String storagePath : storagePaths) { - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, storagePool); - - cmd.setStoragePath(storagePath); - - sendModifyStoragePoolCommand(cmd, storagePool, hostId); - } - } - - private void handleKVM(long hostId, long storagePoolId) { - StoragePool storagePool = (StoragePool)_dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, storagePool); - - sendModifyStoragePoolCommand(cmd, storagePool, hostId); - } - - private List getStoragePaths(long clusterId, long storagePoolId) { - List storagePaths = new ArrayList<>(); - - // If you do not pass in null for the second parameter, you only get back applicable ROOT disks. - List volumes = _volumeDao.findNonDestroyedVolumesByPoolId(storagePoolId, null); - - if (volumes != null) { - for (VolumeVO volume : volumes) { - Long instanceId = volume.getInstanceId(); - - if (instanceId != null) { - VMInstanceVO vmInstance = _vmDao.findById(instanceId); - - Long hostIdForVm = vmInstance.getHostId() != null ? vmInstance.getHostId() : vmInstance.getLastHostId(); - - if (hostIdForVm != null ) { - HostVO hostForVm = _hostDao.findById(hostIdForVm); - - if (hostForVm.getClusterId().equals(clusterId)) { - storagePaths.add(volume.get_iScsiName()); - } - } - } - } - } - - return storagePaths; - } - - private void sendModifyTargetsCommand(ModifyTargetsCommand cmd, long hostId) { - Answer answer = _agentMgr.easySend(hostId, cmd); - - if (answer == null) { - throw new CloudRuntimeException("Unable to get an answer to the modify targets command"); - } - - if (!answer.getResult()) { - HostVO host = _hostDao.findById(hostId); - String msg = String.format("Unable to modify targets on the following host: %s", host); - - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), msg, msg); - - throw new CloudRuntimeException(msg); - } - } - - private void sendModifyStoragePoolCommand(ModifyStoragePoolCommand cmd, StoragePool storagePool, long hostId) { - Answer answer = _agentMgr.easySend(hostId, cmd); - - if (answer == null) { - throw new CloudRuntimeException(String.format("Unable to get an answer to the modify storage pool command (%s)", storagePool)); - } - - if (!answer.getResult()) { - String msg = String.format("Unable to attach storage pool %s to host %d", storagePool, hostId); - - _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, storagePool.getDataCenterId(), storagePool.getPodId(), msg, msg); - - throw new CloudRuntimeException(String.format( - "Unable to establish a connection from agent to storage pool %s due to %s", - storagePool, answer.getDetails())); - } - - assert (answer instanceof ModifyStoragePoolAnswer) : String.format("ModifyStoragePoolAnswer expected ; Pool = %s Host = %d", storagePool, hostId); - - logger.info("Connection established between storage pool {} and host + {}", storagePool, hostId); - } - - private List> getTargets(long clusterId, long storagePoolId) { - List> targets = new ArrayList<>(); - - StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); - - // If you do not pass in null for the second parameter, you only get back applicable ROOT disks. - List volumes = _volumeDao.findNonDestroyedVolumesByPoolId(storagePoolId, null); - - if (volumes != null) { - for (VolumeVO volume : volumes) { - Long instanceId = volume.getInstanceId(); - - if (instanceId != null) { - VMInstanceVO vmInstance = _vmDao.findById(instanceId); - - Long hostIdForVm = vmInstance.getHostId() != null ? vmInstance.getHostId() : vmInstance.getLastHostId(); - - if (hostIdForVm != null) { - HostVO hostForVm = _hostDao.findById(hostIdForVm); - - if (hostForVm.getClusterId().equals(clusterId)) { - Map details = new HashMap<>(); - - details.put(ModifyTargetsCommand.IQN, volume.get_iScsiName()); - details.put(ModifyTargetsCommand.STORAGE_HOST, storagePool.getHostAddress()); - details.put(ModifyTargetsCommand.STORAGE_PORT, String.valueOf(storagePool.getPort())); - - targets.add(details); - } - } - } - } - } - - return targets; - } -} diff --git a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraPrimaryDataStoreProvider.java b/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraPrimaryDataStoreProvider.java deleted file mode 100644 index 70f1f9ce6859..000000000000 --- a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/provider/DateraPrimaryDataStoreProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.apache.cloudstack.storage.datastore.driver.DateraPrimaryDataStoreDriver; -import org.apache.cloudstack.storage.datastore.lifecycle.DateraPrimaryDataStoreLifeCycle; -import org.apache.cloudstack.storage.datastore.util.DateraUtil; -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; - -import com.cloud.utils.component.ComponentContext; - -@Component -public class DateraPrimaryDataStoreProvider implements PrimaryDataStoreProvider { - private DataStoreLifeCycle lifecycle; - private PrimaryDataStoreDriver driver; - private HypervisorHostListener listener; - - DateraPrimaryDataStoreProvider() { - } - - @Override - public String getName() { - return DateraUtil.PROVIDER_NAME; - } - - @Override - public DataStoreLifeCycle getDataStoreLifeCycle() { - return lifecycle; - } - - @Override - public PrimaryDataStoreDriver getDataStoreDriver() { - return driver; - } - - @Override - public HypervisorHostListener getHostListener() { - return listener; - } - - @Override - public boolean configure(Map params) { - lifecycle = ComponentContext.inject(DateraPrimaryDataStoreLifeCycle.class); - driver = ComponentContext.inject(DateraPrimaryDataStoreDriver.class); - listener = ComponentContext.inject(DateraHostListener.class); - - return true; - } - - @Override - public Set getTypes() { - Set types = new HashSet(); - - types.add(DataStoreProviderType.PRIMARY); - - return types; - } -} diff --git a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraObject.java b/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraObject.java deleted file mode 100644 index 43dcb78bb67a..000000000000 --- a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraObject.java +++ /dev/null @@ -1,470 +0,0 @@ -// 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 org.apache.cloudstack.storage.datastore.util; - -import com.google.gson.annotations.SerializedName; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -public class DateraObject { - - public static final String DEFAULT_CREATE_MODE = "cloudstack"; - public static final String DEFAULT_STORAGE_NAME = "storage-1"; - public static final String DEFAULT_VOLUME_NAME = "volume-1"; - public static final String DEFAULT_ACL = "deny_all"; - public static final String DEFAULT_STORAGE_FORCE_BOOLEAN = "true"; - - public enum AppState { - ONLINE, OFFLINE; - - @Override - public String toString() { - return this.name().toLowerCase(); - } - } - - public enum DateraOperation { - ADD, REMOVE; - - @Override - public String toString() { - return this.name().toLowerCase(); - } - } - - public enum DateraErrorTypes { - PermissionDeniedError, InvalidRouteError, AuthFailedError, ValidationFailedError, InvalidRequestError, - NotFoundError, NotConnectedError, InvalidSessionKeyError, DatabaseError, InternalError,ConflictError; - - public boolean equals(DateraError err) { - return this.name().equals(err.getName()); - } - } - - public static class DateraConnection { - - private int managementPort; - private String managementIp; - private String username; - private String password; - - public DateraConnection(String managementIp, int managementPort, String username, String password) { - this.managementPort = managementPort; - this.managementIp = managementIp; - this.username = username; - this.password = password; - } - - public int getManagementPort() { - return managementPort; - } - - public String getManagementIp() { - return managementIp; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - } - - public static class DateraLogin { - - private final String name; - private final String password; - - public DateraLogin(String username, String password) { - this.name = username; - this.password = password; - } - } - - public static class DateraLoginResponse { - - private String key; - - public String getKey() { - return key; - } - } - - public class Access { - private String iqn; - private List ips; - - public Access(String iqn, List ips) { - this.iqn = iqn; - this.ips = ips; - } - - public String getIqn() { - return iqn; - } - } - - public static class PerformancePolicy { - - @SerializedName("total_iops_max") - private Integer totalIops; - - public PerformancePolicy(int totalIops) { - this.totalIops = totalIops; - } - - public Integer getTotalIops() { - return totalIops; - } - } - - public static class Volume { - - private String name; - private String path; - private Integer size; - - @SerializedName("replica_count") - private Integer replicaCount; - - @SerializedName("performance_policy") - private PerformancePolicy performancePolicy; - - @SerializedName("placement_mode") - private String placementMode; - - @SerializedName("op_state") - private String opState; - - public Volume(int size, int totalIops, int replicaCount) { - this.name = DEFAULT_VOLUME_NAME; - this.size = size; - this.replicaCount = replicaCount; - this.performancePolicy = new PerformancePolicy(totalIops); - } - - public Volume(int size, int totalIops, int replicaCount, String placementMode) { - this.name = DEFAULT_VOLUME_NAME; - this.size = size; - this.replicaCount = replicaCount; - this.performancePolicy = new PerformancePolicy(totalIops); - this.placementMode = placementMode; - } - - public Volume(Integer newSize) { - this.size = newSize; - } - - public Volume(String newPlacementMode) { - this.placementMode = newPlacementMode; - } - - public PerformancePolicy getPerformancePolicy() { - return performancePolicy; - } - - public int getSize() { - return size; - } - - public String getPlacementMode() { - return placementMode; - } - - public String getPath() { - return path; - } - - public String getOpState() { - return opState; - } - } - - public static class StorageInstance { - - private final String name = DEFAULT_STORAGE_NAME; - private Map volumes; - private Access access; - private String force; - - @SerializedName("ip_pool") - private String ipPool; - - public StorageInstance(int size, int totalIops, int replicaCount) { - Volume volume = new Volume(size, totalIops, replicaCount); - volumes = new HashMap(); - volumes.put(DEFAULT_VOLUME_NAME, volume); - } - - public StorageInstance(int size, int totalIops, int replicaCount, String placementMode, String ipPool) { - Volume volume = new Volume(size, totalIops, replicaCount, placementMode); - volumes = new HashMap(); - volumes.put(DEFAULT_VOLUME_NAME, volume); - this.ipPool = new StringBuilder("/access_network_ip_pools/").append(ipPool).toString(); - } - - public StorageInstance(int size, int totalIops, int replicaCount, String placementMode, String ipPool, String force) { - Volume volume = new Volume(size, totalIops, replicaCount, placementMode); - volumes = new HashMap(); - volumes.put(DEFAULT_VOLUME_NAME, volume); - this.ipPool = new StringBuilder("/access_network_ip_pools/").append(ipPool).toString(); - this.force = DEFAULT_STORAGE_FORCE_BOOLEAN; - } - - public Access getAccess() { - return access; - } - - public Volume getVolume() { - return volumes.get(DEFAULT_VOLUME_NAME); - } - - public int getSize() { - return getVolume().getSize(); - } - - public String getForce() { - return this.force; - } - - } - - public static class AppInstance { - - private String name; - - @SerializedName("access_control_mode") - private String accessControlMode; - - @SerializedName("create_mode") - private String createMode; - - @SerializedName("storage_instances") - private Map storageInstances; - - @SerializedName("clone_src") - private String cloneSrc; - - @SerializedName("admin_state") - private String adminState; - private Boolean force; - - public AppInstance(String name, int size, int totalIops, int replicaCount) { - this.name = name; - StorageInstance storageInstance = new StorageInstance(size, totalIops, replicaCount); - this.storageInstances = new HashMap(); - this.storageInstances.put(DEFAULT_STORAGE_NAME, storageInstance); - this.accessControlMode = DEFAULT_ACL; - this.createMode = DEFAULT_CREATE_MODE; - } - - public AppInstance(String name, int size, int totalIops, int replicaCount, String placementMode, - String ipPool) { - this.name = name; - StorageInstance storageInstance = new StorageInstance(size, totalIops, replicaCount, placementMode, ipPool); - this.storageInstances = new HashMap(); - this.storageInstances.put(DEFAULT_STORAGE_NAME, storageInstance); - this.accessControlMode = DEFAULT_ACL; - this.createMode = DEFAULT_CREATE_MODE; - } - - public AppInstance(AppState state) { - this.adminState = state.toString(); - this.force = true; - } - - public AppInstance(String name, String cloneSrc) { - this.name = name; - this.cloneSrc = cloneSrc; - } - - public String getIqn() { - StorageInstance storageInstance = storageInstances.get(DEFAULT_STORAGE_NAME); - return storageInstance.getAccess().getIqn(); - } - - public int getTotalIops() { - StorageInstance storageInstance = storageInstances.get(DEFAULT_STORAGE_NAME); - return storageInstance.getVolume().getPerformancePolicy().getTotalIops(); - } - - public String getName() { - return name; - } - - public int getSize() { - StorageInstance storageInstance = storageInstances.get(DEFAULT_STORAGE_NAME); - return storageInstance.getSize(); - } - - public String getVolumePath() { - StorageInstance storageInstance = storageInstances.get(DEFAULT_STORAGE_NAME); - return storageInstance.getVolume().getPath(); - } - - public String getVolumeOpState() { - StorageInstance storageInstance = storageInstances.get(DEFAULT_STORAGE_NAME); - return storageInstance.getVolume().getOpState(); - } - } - - public static class AccessNetworkIpPool { - @SerializedName("ip_pool") - private String ipPool; - - public AccessNetworkIpPool(String ipPool) { - this.ipPool = new StringBuilder("/access_network_ip_pools/").append(ipPool).toString(); - } - } - - public static class Initiator { - - private String id; // IQN - private String name; - private String path; - private String op; - - public Initiator(String name, String id) { - this.id = id; - this.name = name; - } - - public Initiator(String path, DateraOperation op) { - this.path = path; - this.op = op.toString(); - } - - public String getPath() { - return path; - } - } - - public static class InitiatorGroup { - - private String name; - private List members; - private String path; - private String op; - - public InitiatorGroup(String name, List members) { - this.name = name; - this.members = members; - } - - public InitiatorGroup(String path, DateraOperation op) { - this.path = path; - this.op = op.toString(); - } - - public String getPath() { - return path; - } - - public String getName() { - return name; - } - - public List getMembers() { - return members; - } - } - - public static class VolumeSnapshot { - - private String uuid; - private String timestamp; - private String path; - - @SerializedName("op_state") - private String opState; - - VolumeSnapshot(String uuid) { - this.uuid = uuid; - } - - public String getTimestamp() { - return timestamp; - } - - public String getOpState() { - return opState; - } - - public String getPath() { - return path; - } - } - - public static class VolumeSnapshotRestore { - - @SerializedName("restore_point") - private String restorePoint; - - VolumeSnapshotRestore(String restorePoint) { - this.restorePoint = restorePoint; - } - } - - public static class DateraError extends Exception { - - private String name; - private int code; - private List errors; - private String message; - - public DateraError(String name, int code, List errors, String message) { - this.name = name; - this.code = code; - this.errors = errors; - this.message = message; - } - - public List getErrors() { - return errors; - } - - public boolean isError() { - return message != null && name.endsWith("Error"); - } - - public String getMessage() { - - String errMesg = name + "\n"; - if (message != null) { - errMesg += message + "\n"; - } - - if (errors != null) { - errMesg += StringUtils.join(errors, "\n"); - - } - - return errMesg; - } - - public String getName() { - return name; - } - } -} diff --git a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraUtil.java b/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraUtil.java deleted file mode 100644 index 6aeedd275464..000000000000 --- a/plugins/storage/volume/datera/src/main/java/org/apache/cloudstack/storage/datastore/util/DateraUtil.java +++ /dev/null @@ -1,1029 +0,0 @@ -// 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 org.apache.cloudstack.storage.datastore.util; - -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.utils.exception.CloudRuntimeException; -import com.google.common.base.Preconditions; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.StringTokenizer; -import java.util.UUID; - -public class DateraUtil { - - protected static Logger LOGGER = LogManager.getLogger(DateraUtil.class); - private static final String API_VERSION = "v2"; - - public static final String PROVIDER_NAME = "Datera"; - public static final String DRIVER_VERSION = "4.13.0-v2.0.0"; - - private static final String HEADER_AUTH_TOKEN = "auth-token"; - private static final String HEADER_CONTENT_TYPE = "content-type"; - private static final String HEADER_VALUE_JSON = "application/json"; - - public static final String MANAGEMENT_VIP = "mVip"; - public static final String STORAGE_VIP = "sVip"; - - public static final String MANAGEMENT_PORT = "mPort"; - public static final String STORAGE_PORT = "sPort"; - public static final String DEFAULT_IP_POOL = "default"; - - private static final int DEFAULT_MANAGEMENT_PORT = 7717; - private static final int DEFAULT_STORAGE_PORT = 3260; - private static final int DEFAULT_NUM_REPLICAS = 3; - - private static final long ONEGIB_BYTES = 1073741824; - - private static final String DEFAULT_VOL_PLACEMENT = "hybrid"; - - public static final String CLUSTER_ADMIN_USERNAME = "clusterAdminUsername"; - public static final String CLUSTER_ADMIN_PASSWORD = "clusterAdminPassword"; - - public static final String CLUSTER_DEFAULT_MIN_IOPS = "clusterDefaultMinIops"; - public static final String CLUSTER_DEFAULT_MAX_IOPS = "clusterDefaultMaxIops"; - public static final String NUM_REPLICAS = "numReplicas"; - public static final String VOL_PLACEMENT = "volPlacement"; - - public static final String STORAGE_POOL_ID = "DateraStoragePoolId"; - public static final String VOLUME_SIZE = "DateraVolumeSize"; - public static final String VOLUME_ID = "DateraVolumeId"; - public static final String SNAPSHOT_ID = "DateraSnapshotId"; - public static final String TEMP_VOLUME_ID = "tempVolumeId"; - public static final String IP_POOL = "ipPool"; - - public static final int MAX_IOPS = 10000; // max IOPS that can be assigned to a volume - - public static final String INITIATOR_GROUP_PREFIX = "CS-InitiatorGroup"; - public static final String INITIATOR_PREFIX = "CS-Initiator"; - public static final String APPINSTANCE_PREFIX = "CS"; - public static final int APPINSTANCE_MAX_LENTH = 64; - - public static final int MIN_NUM_REPLICAS = 1; - public static final int MAX_NUM_REPLICAS = 5; - - public static final int POLL_TIMEOUT_MS = 3000; - public static final String STATE_AVAILABLE = "available"; - public static final int DEFAULT_RETRIES = 10; - - private static Gson gson = new GsonBuilder().create(); - - private int managementPort; - private String managementIp; - private String username; - private String password; - - private static final String SCHEME_HTTP = "http"; - private static final int UUID_LENGTH = 8; - - public DateraUtil(String managementIp, int managementPort, String username, String password) { - this.managementPort = managementPort; - this.managementIp = managementIp; - this.username = username; - this.password = password; - } - - public static String login(DateraObject.DateraConnection conn) - throws UnsupportedEncodingException, DateraObject.DateraError { - - DateraObject.DateraLogin loginParams = new DateraObject.DateraLogin(conn.getUsername(), conn.getPassword()); - HttpPut loginReq = new HttpPut(generateApiUrl("login")); - - StringEntity jsonParams = new StringEntity(gson.toJson(loginParams)); - loginReq.setEntity(jsonParams); - - String response = executeHttp(conn, loginReq); - DateraObject.DateraLoginResponse loginResponse = gson.fromJson(response, - DateraObject.DateraLoginResponse.class); - - return loginResponse.getKey(); - - } - - public static Map getAppInstances(DateraObject.DateraConnection conn) - throws DateraObject.DateraError { - - HttpGet getAppInstancesReq = new HttpGet(generateApiUrl("app_instances")); - String response = null; - - response = executeApiRequest(conn, getAppInstancesReq); - - Type responseType = new TypeToken>() { - }.getType(); - - return gson.fromJson(response, responseType); - } - - public static DateraObject.AppInstance getAppInstance(DateraObject.DateraConnection conn, String name) - throws DateraObject.DateraError { - - HttpGet url = new HttpGet(generateApiUrl("app_instances", name)); - - String response = null; - try { - response = executeApiRequest(conn, url); - return gson.fromJson(response, DateraObject.AppInstance.class); - } catch (DateraObject.DateraError dateraError) { - if (DateraObject.DateraErrorTypes.NotFoundError.equals(dateraError)) { - return null; - } else { - throw dateraError; - } - } - } - - public static DateraObject.PerformancePolicy getAppInstancePerformancePolicy(DateraObject.DateraConnection conn, - String appInstanceName) throws DateraObject.DateraError { - - HttpGet url = new HttpGet(generateApiUrl("app_instances", appInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME, "performance_policy")); - - try { - String response = executeApiRequest(conn, url); - return gson.fromJson(response, DateraObject.PerformancePolicy.class); - } catch (DateraObject.DateraError dateraError) { - if (DateraObject.DateraErrorTypes.NotFoundError.equals(dateraError)) { - return null; - } else { - throw dateraError; - } - } - - } - - public static DateraObject.PerformancePolicy createAppInstancePerformancePolicy(DateraObject.DateraConnection conn, - String appInstanceName, int totalIops) throws UnsupportedEncodingException, DateraObject.DateraError { - - HttpPost url = new HttpPost(generateApiUrl("app_instances", appInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME, "performance_policy")); - - DateraObject.PerformancePolicy performancePolicy = new DateraObject.PerformancePolicy(totalIops); - - url.setEntity(new StringEntity(gson.toJson(performancePolicy))); - - String response = executeApiRequest(conn, url); - - return gson.fromJson(response, DateraObject.PerformancePolicy.class); - } - - public static void updateAppInstanceIops(DateraObject.DateraConnection conn, String appInstance, int totalIops) - throws UnsupportedEncodingException, DateraObject.DateraError { - - if (getAppInstancePerformancePolicy(conn, appInstance) == null) { - createAppInstancePerformancePolicy(conn, appInstance, totalIops); - } else { - - HttpPut url = new HttpPut( - generateApiUrl("app_instances", appInstance, "storage_instances", DateraObject.DEFAULT_STORAGE_NAME, - "volumes", DateraObject.DEFAULT_VOLUME_NAME, "performance_policy")); - - DateraObject.PerformancePolicy performancePolicy = new DateraObject.PerformancePolicy(totalIops); - - url.setEntity(new StringEntity(gson.toJson(performancePolicy))); - executeApiRequest(conn, url); - } - } - - public static void updateAppInstanceSize(DateraObject.DateraConnection conn, String appInstanceName, int newSize) - throws UnsupportedEncodingException, DateraObject.DateraError { - - HttpPut url = new HttpPut(generateApiUrl("app_instances", appInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME)); - - DateraObject.Volume volume = new DateraObject.Volume(newSize); - url.setEntity(new StringEntity(gson.toJson(volume))); - executeApiRequest(conn, url); - - } - - public static void updateAppInstancePlacement(DateraObject.DateraConnection conn, String appInstanceName, - String newPlacementMode) throws UnsupportedEncodingException, DateraObject.DateraError { - HttpPut url = new HttpPut(generateApiUrl("app_instances", appInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME)); - - DateraObject.Volume volume = new DateraObject.Volume(newPlacementMode); - url.setEntity(new StringEntity(gson.toJson(volume))); - executeApiRequest(conn, url); - - } - - private static DateraObject.AppInstance createAppInstance(DateraObject.DateraConnection conn, String name, - StringEntity appInstanceEntity) throws DateraObject.DateraError { - - HttpPost createAppInstance = new HttpPost(generateApiUrl("app_instances")); - HttpGet getAppInstance = new HttpGet(generateApiUrl("app_instances", name)); - createAppInstance.setEntity(appInstanceEntity); - String response = null; - - executeApiRequest(conn, createAppInstance); - - // create is async, do a get to fetch the IQN - executeApiRequest(conn, getAppInstance); - - return pollAppInstanceAvailable(conn, name); - } - - public static DateraObject.AppInstance createAppInstance(DateraObject.DateraConnection conn, String name, int size, - int totalIops, int replicaCount) throws UnsupportedEncodingException, DateraObject.DateraError { - - DateraObject.AppInstance appInstance = new DateraObject.AppInstance(name, size, totalIops, replicaCount, - DEFAULT_VOL_PLACEMENT, DEFAULT_IP_POOL); - StringEntity appInstanceEntity = new StringEntity(gson.toJson(appInstance)); - - return createAppInstance(conn, name, appInstanceEntity); - } - - public static DateraObject.AppInstance createAppInstance(DateraObject.DateraConnection conn, String name, int size, - int totalIops, int replicaCount, String placementMode, String ipPool) - throws UnsupportedEncodingException, DateraObject.DateraError { - - DateraObject.AppInstance appInstance = new DateraObject.AppInstance(name, size, totalIops, replicaCount, - placementMode, ipPool); - StringEntity appInstanceEntity = new StringEntity(gson.toJson(appInstance)); - - return createAppInstance(conn, name, appInstanceEntity); - } - - public static DateraObject.AppInstance cloneAppInstanceFromVolume(DateraObject.DateraConnection conn, String name, - String srcCloneName) throws UnsupportedEncodingException, DateraObject.DateraError { - return null; - } - - public static DateraObject.AppInstance cloneAppInstanceFromVolume(DateraObject.DateraConnection conn, String name, - String srcCloneName, String ipPool) throws UnsupportedEncodingException, DateraObject.DateraError { - LOGGER.debug("cloneAppInstanceFromVolume() called"); - DateraObject.AppInstance srcAppInstance = getAppInstance(conn, srcCloneName); - - if (srcAppInstance == null) { - throw new DateraObject.DateraError("NotFoundError", 404, null, - "Unable to find the base app instance to clone from"); - } - - String srcClonePath = srcAppInstance.getVolumePath(); - - DateraObject.AppInstance appInstanceObj = new DateraObject.AppInstance(name, srcClonePath); - - StringEntity appInstanceEntity = new StringEntity(gson.toJson(appInstanceObj)); - DateraObject.AppInstance appInstance = createAppInstance(conn, name, appInstanceEntity); - - // Update ipPool - updateAppInstanceIpPool(conn, name, ipPool); - - // bring it online - updateAppInstanceAdminState(conn, name, DateraObject.AppState.ONLINE); - - return getAppInstance(conn, name); - } - - public static DateraObject.AppInstance pollAppInstanceAvailable(DateraObject.DateraConnection conn, - String appInstanceName) throws DateraObject.DateraError { - - int retries = DateraUtil.DEFAULT_RETRIES; - DateraObject.AppInstance appInstance = null; - do { - appInstance = getAppInstance(conn, appInstanceName); - try { - Thread.sleep(DateraUtil.POLL_TIMEOUT_MS); - } catch (InterruptedException e) { - return null; - } - retries--; - } while ((appInstance != null && !Objects.equals(appInstance.getVolumeOpState(), DateraUtil.STATE_AVAILABLE)) - && retries > 0); - return appInstance; - } - - public static DateraObject.Initiator createInitiator(DateraObject.DateraConnection conn, String name, String iqn) - throws DateraObject.DateraError, UnsupportedEncodingException { - - HttpPost req = new HttpPost(generateApiUrl("initiators")); - - DateraObject.Initiator initiator = new DateraObject.Initiator(name, iqn); - StringEntity httpEntity = new StringEntity(gson.toJson(initiator)); - req.setEntity(httpEntity); - - return gson.fromJson(executeApiRequest(conn, req), DateraObject.Initiator.class); - } - - public static DateraObject.Initiator getInitiator(DateraObject.DateraConnection conn, String iqn) - throws DateraObject.DateraError { - - try { - HttpGet getReq = new HttpGet(generateApiUrl("initiators", iqn)); - String response = executeApiRequest(conn, getReq); - return gson.fromJson(response, DateraObject.Initiator.class); - } catch (DateraObject.DateraError dateraError) { - if (DateraObject.DateraErrorTypes.NotFoundError.equals(dateraError)) { - return null; - } else { - throw dateraError; - } - } - } - - public static void deleteInitiator(DateraObject.DateraConnection conn, String iqn) throws DateraObject.DateraError { - - HttpDelete req = new HttpDelete(generateApiUrl("initiators", iqn)); - executeApiRequest(conn, req); - } - - public static DateraObject.InitiatorGroup createInitiatorGroup(DateraObject.DateraConnection conn, String name) - throws UnsupportedEncodingException, DateraObject.DateraError { - - HttpPost createReq = new HttpPost(generateApiUrl("initiator_groups")); - - DateraObject.InitiatorGroup group = new DateraObject.InitiatorGroup(name, Collections.emptyList()); - - StringEntity httpEntity = new StringEntity(gson.toJson(group)); - createReq.setEntity(httpEntity); - - String response = executeApiRequest(conn, createReq); - return gson.fromJson(response, DateraObject.InitiatorGroup.class); - } - - public static void deleteInitatorGroup(DateraObject.DateraConnection conn, String name) - throws DateraObject.DateraError { - HttpDelete delReq = new HttpDelete(generateApiUrl("initiator_groups", name)); - executeApiRequest(conn, delReq); - } - - public static DateraObject.InitiatorGroup getInitiatorGroup(DateraObject.DateraConnection conn, String name) - throws DateraObject.DateraError { - try { - HttpGet getReq = new HttpGet(generateApiUrl("initiator_groups", name)); - String response = executeApiRequest(conn, getReq); - return gson.fromJson(response, DateraObject.InitiatorGroup.class); - - } catch (DateraObject.DateraError dateraError) { - if (DateraObject.DateraErrorTypes.NotFoundError.equals(dateraError)) { - return null; - } else { - throw dateraError; - } - } - } - - public static void updateInitiatorGroup(DateraObject.DateraConnection conn, String initiatorPath, String groupName, - DateraObject.DateraOperation op) throws DateraObject.DateraError, UnsupportedEncodingException { - - DateraObject.InitiatorGroup initiatorGroup = getInitiatorGroup(conn, groupName); - - if (initiatorGroup == null) { - throw new CloudRuntimeException("Unable to find initiator group by name " + groupName); - } - - HttpPut addReq = new HttpPut(generateApiUrl("initiator_groups", groupName, "members")); - - DateraObject.Initiator initiator = new DateraObject.Initiator(initiatorPath, op); - - addReq.setEntity(new StringEntity(gson.toJson(initiator))); - executeApiRequest(conn, addReq); - } - - public static void addInitiatorToGroup(DateraObject.DateraConnection conn, String initiatorPath, String groupName) - throws UnsupportedEncodingException, DateraObject.DateraError { - updateInitiatorGroup(conn, initiatorPath, groupName, DateraObject.DateraOperation.ADD); - } - - public static void removeInitiatorFromGroup(DateraObject.DateraConnection conn, String initiatorPath, - String groupName) throws DateraObject.DateraError, UnsupportedEncodingException { - updateInitiatorGroup(conn, initiatorPath, groupName, DateraObject.DateraOperation.REMOVE); - } - - public static Map getAppInstanceInitiatorGroups( - DateraObject.DateraConnection conn, String appInstance) throws DateraObject.DateraError { - HttpGet req = new HttpGet(generateApiUrl("app_instances", appInstance, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "acl_policy", "initiator_groups")); - - String response = executeApiRequest(conn, req); - - if (response == null) { - return null; - } - - Type responseType = new TypeToken>() { - }.getType(); - - return gson.fromJson(response, responseType); - } - - public static void assignGroupToAppInstance(DateraObject.DateraConnection conn, String group, String appInstance) - throws DateraObject.DateraError, UnsupportedEncodingException { - - DateraObject.InitiatorGroup initiatorGroup = getInitiatorGroup(conn, group); - - if (initiatorGroup == null) { - throw new CloudRuntimeException("Initator group " + group + " not found "); - } - - Map initiatorGroups = getAppInstanceInitiatorGroups(conn, appInstance); - - if (initiatorGroups == null) { - throw new CloudRuntimeException("Initator group not found for appInstnace " + appInstance); - } - - for (DateraObject.InitiatorGroup ig : initiatorGroups.values()) { - if (ig.getName().equals(group)) { - // already assigned - return; - } - } - - HttpPut url = new HttpPut(generateApiUrl("app_instances", appInstance, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "acl_policy", "initiator_groups")); - - url.setEntity(new StringEntity(gson - .toJson(new DateraObject.InitiatorGroup(initiatorGroup.getPath(), DateraObject.DateraOperation.ADD)))); - - executeApiRequest(conn, url); - } - - public static void removeGroupFromAppInstance(DateraObject.DateraConnection conn, String group, String appInstance) - throws DateraObject.DateraError, UnsupportedEncodingException { - - DateraObject.InitiatorGroup initiatorGroup = getInitiatorGroup(conn, group); - - if (initiatorGroup == null) { - throw new CloudRuntimeException("Initator groups not found for appInstnace " + appInstance); - } - - Map initiatorGroups = getAppInstanceInitiatorGroups(conn, appInstance); - - if (initiatorGroups == null) { - throw new CloudRuntimeException("Initator group not found for appInstnace " + appInstance); - } - - boolean groupAssigned = false; - - for (DateraObject.InitiatorGroup ig : initiatorGroups.values()) { - if (ig.getName().equals(group)) { - groupAssigned = true; - break; - } - } - - if (!groupAssigned) { - return; // already removed - } - - HttpPut url = new HttpPut(generateApiUrl("app_instances", appInstance, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "acl_policy", "initiator_groups")); - - url.setEntity(new StringEntity(gson.toJson( - new DateraObject.InitiatorGroup(initiatorGroup.getPath(), DateraObject.DateraOperation.REMOVE)))); - - executeApiRequest(conn, url); - } - - public static void updateAppInstanceAdminState(DateraObject.DateraConnection conn, String appInstanceName, - DateraObject.AppState appState) throws UnsupportedEncodingException, DateraObject.DateraError { - - DateraObject.AppInstance appInstance = new DateraObject.AppInstance(appState); - HttpPut updateAppInstanceReq = new HttpPut(generateApiUrl("app_instances", appInstanceName)); - - updateAppInstanceReq.setEntity(new StringEntity(gson.toJson(appInstance))); - executeApiRequest(conn, updateAppInstanceReq); - } - - public static void updateAppInstanceIpPool(DateraObject.DateraConnection conn, String appInstanceName, - String ipPool) throws UnsupportedEncodingException, DateraObject.DateraError { - - HttpPut url = new HttpPut(generateApiUrl("app_instances", appInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME)); - - url.setEntity(new StringEntity(gson.toJson(new DateraObject.AccessNetworkIpPool(ipPool)))); - - executeApiRequest(conn, url); - } - - public static void deleteAppInstance(DateraObject.DateraConnection conn, String name) - throws UnsupportedEncodingException, DateraObject.DateraError { - - HttpDelete deleteAppInstanceReq = new HttpDelete(generateApiUrl("app_instances", name)); - updateAppInstanceAdminState(conn, name, DateraObject.AppState.OFFLINE); - executeApiRequest(conn, deleteAppInstanceReq); - } - - public static DateraObject.AppInstance cloneAppInstanceFromSnapshot(DateraObject.DateraConnection conn, - String newAppInstanceName, String snapshotName) - throws DateraObject.DateraError, UnsupportedEncodingException { - - return cloneAppInstanceFromSnapshot(conn, newAppInstanceName, snapshotName, DEFAULT_IP_POOL); - } - - public static DateraObject.AppInstance cloneAppInstanceFromSnapshot(DateraObject.DateraConnection conn, - String newAppInstanceName, String snapshotName, String ipPool) - throws DateraObject.DateraError, UnsupportedEncodingException { - - // split the snapshot name to appInstanceName and the snapshot timestamp - String[] tokens = snapshotName.split(":"); - Preconditions.checkArgument(tokens.length == 2); - - // A snapshot is stored in Cloudstack as : - String appInstanceName = tokens[0]; - String snapshotTime = tokens[1]; - - // get the snapshot from Datera - HttpGet getSnasphotReq = new HttpGet( - generateApiUrl("app_instances", appInstanceName, "storage_instances", DateraObject.DEFAULT_STORAGE_NAME, - "volumes", DateraObject.DEFAULT_VOLUME_NAME, "snapshots", snapshotTime)); - - String resp = executeApiRequest(conn, getSnasphotReq); - - DateraObject.VolumeSnapshot snapshot = gson.fromJson(resp, DateraObject.VolumeSnapshot.class); - - String snapshotPath = snapshot.getPath(); - - DateraObject.AppInstance appInstanceObj = new DateraObject.AppInstance(newAppInstanceName, snapshotPath); - - StringEntity appInstanceEntity = new StringEntity(gson.toJson(appInstanceObj)); - - DateraObject.AppInstance appInstance = createAppInstance(conn, newAppInstanceName, appInstanceEntity); - - // Update ipPool - updateAppInstanceIpPool(conn, newAppInstanceName, ipPool); - - // bring it online - updateAppInstanceAdminState(conn, newAppInstanceName, DateraObject.AppState.ONLINE); - - return getAppInstance(conn, newAppInstanceName); - } - - public static void deleteVolumeSnapshot(DateraObject.DateraConnection conn, String snapshotName) - throws DateraObject.DateraError { - - // split the snapshot name to appInstanceName and the snapshot timestamp - String[] tokens = snapshotName.split(":"); - Preconditions.checkArgument(tokens.length == 2); - - // A snapshot is stored in Cloudstack as : - String appInstanceName = tokens[0]; - String snapshotTime = tokens[1]; - - HttpDelete deleteSnapshotReq = new HttpDelete( - generateApiUrl("app_instances", appInstanceName, "storage_instances", DateraObject.DEFAULT_STORAGE_NAME, - "volumes", DateraObject.DEFAULT_VOLUME_NAME, "snapshots", snapshotTime)); - - executeApiRequest(conn, deleteSnapshotReq); - } - - public static DateraObject.VolumeSnapshot getVolumeSnapshot(DateraObject.DateraConnection conn, - String appInstanceName, String snapshotTime) throws DateraObject.DateraError { - - HttpGet getSnapshotReq = new HttpGet( - generateApiUrl("app_instances", appInstanceName, "storage_instances", DateraObject.DEFAULT_STORAGE_NAME, - "volumes", DateraObject.DEFAULT_VOLUME_NAME, "snapshots", snapshotTime)); - - String resp = executeApiRequest(conn, getSnapshotReq); - return gson.fromJson(resp, DateraObject.VolumeSnapshot.class); - } - - public static DateraObject.VolumeSnapshot takeVolumeSnapshot(DateraObject.DateraConnection conn, - String baseAppInstanceName) throws UnsupportedEncodingException, DateraObject.DateraError { - - HttpPost takeSnasphotReq = new HttpPost( - generateApiUrl("app_instances", baseAppInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME, "snapshots")); - - String snapshotUuid = UUID.randomUUID().toString(); - DateraObject.VolumeSnapshot volumeSnapshot = new DateraObject.VolumeSnapshot(snapshotUuid); - takeSnasphotReq.setEntity(new StringEntity(gson.toJson(volumeSnapshot))); - String snapshotResponse = executeApiRequest(conn, takeSnasphotReq); - volumeSnapshot = gson.fromJson(snapshotResponse, DateraObject.VolumeSnapshot.class); - String snapshotTime = volumeSnapshot.getTimestamp(); - - int retries = DateraUtil.DEFAULT_RETRIES; - - do { - try { - Thread.sleep(DateraUtil.POLL_TIMEOUT_MS); - } catch (InterruptedException e) { - return null; - } - volumeSnapshot = getVolumeSnapshot(conn, baseAppInstanceName, snapshotTime); - } while ((!Objects.equals(volumeSnapshot.getOpState(), DateraUtil.STATE_AVAILABLE)) && --retries > 0); - - return volumeSnapshot; - } - - public static DateraObject.AppInstance restoreVolumeSnapshot(DateraObject.DateraConnection conn, - String snapshotName) throws DateraObject.DateraError { - - // split the snapshot name to appInstanceName and the snapshot timestamp - String[] tokens = snapshotName.split(":"); - Preconditions.checkArgument(tokens.length == 2); - - // A snapshot is stored in Cloudstack as : - String appInstanceName = tokens[0]; - String snapshotTime = tokens[1]; - - HttpPut restoreSnapshotReq = new HttpPut(generateApiUrl("app_instances", appInstanceName, "storage_instances", - DateraObject.DEFAULT_STORAGE_NAME, "volumes", DateraObject.DEFAULT_VOLUME_NAME)); - - try { - // bring appInstance offline - updateAppInstanceAdminState(conn, appInstanceName, DateraObject.AppState.OFFLINE); - - DateraObject.VolumeSnapshotRestore volumeSnapshotRestore = new DateraObject.VolumeSnapshotRestore( - snapshotTime); - - StringEntity jsonParams = new StringEntity(gson.toJson(volumeSnapshotRestore)); - restoreSnapshotReq.setEntity(jsonParams); - executeApiRequest(conn, restoreSnapshotReq); - // bring appInstance online - updateAppInstanceAdminState(conn, appInstanceName, DateraObject.AppState.ONLINE); - - } catch (UnsupportedEncodingException e) { - throw new CloudRuntimeException("Failed to restore volume snapshot" + e.getMessage()); - } - return getAppInstance(conn, appInstanceName); - - } - - private static String executeApiRequest(DateraObject.DateraConnection conn, HttpRequest apiReq) - throws DateraObject.DateraError { - - // Get the token first - String authToken = null; - try { - authToken = login(conn); - } catch (UnsupportedEncodingException e) { - throw new CloudRuntimeException("Unable to login to Datera " + e.getMessage()); - } - - if (authToken == null) { - throw new CloudRuntimeException("Unable to login to Datera: error getting auth token "); - } - - apiReq.addHeader(HEADER_AUTH_TOKEN, authToken); - - return executeHttp(conn, apiReq); - } - - private static String executeHttp(DateraObject.DateraConnection conn, HttpRequest request) - throws DateraObject.DateraError { - CloseableHttpClient httpclient = HttpClientBuilder.create().build(); - String response = null; - - if (null == httpclient) { - throw new CloudRuntimeException("Unable to create httpClient for request"); - } - - try { - - request.setHeader(HEADER_CONTENT_TYPE, HEADER_VALUE_JSON); - - HttpHost target = new HttpHost(conn.getManagementIp(), conn.getManagementPort(), SCHEME_HTTP); - - HttpResponse httpResponse = httpclient.execute(target, request); - - HttpEntity entity = httpResponse.getEntity(); - StatusLine status = httpResponse.getStatusLine(); - response = EntityUtils.toString(entity); - - assert response != null; - - if (status.getStatusCode() != HttpStatus.SC_OK) { - // check if this is an error - DateraObject.DateraError error = gson.fromJson(response, DateraObject.DateraError.class); - if (error != null && error.isError()) { - throw error; - } else { - throw new CloudRuntimeException("Error while trying to get HTTP object from Datera"); - } - - } - - } catch (IOException e) { - throw new CloudRuntimeException("Error while sending request to Datera. Error " + e.getMessage()); - } - - return response; - } - - protected static String generateApiUrl(String... args) { - ArrayList urlList = new ArrayList(Arrays.asList(args)); - - urlList.add(0, API_VERSION); - urlList.add(0, ""); - - return StringUtils.join(urlList, "/"); - } - - public static String getManagementVip(String url) { - return getVip(DateraUtil.MANAGEMENT_VIP, url); - } - - public static String getStorageVip(String url) { - return getVip(DateraUtil.STORAGE_VIP, url); - } - - public static int getManagementPort(String url) { - return getPort(DateraUtil.MANAGEMENT_VIP, url, DEFAULT_MANAGEMENT_PORT); - } - - public static int getStoragePort(String url) { - return getPort(DateraUtil.STORAGE_VIP, url, DEFAULT_STORAGE_PORT); - } - - public static int getNumReplicas(String url) { - try { - String value = getValue(DateraUtil.NUM_REPLICAS, url, false); - return Integer.parseInt(value); - } catch (NumberFormatException ex) { - return DEFAULT_NUM_REPLICAS; - } - - } - - public static String getVolPlacement(String url) { - String volPlacement = getValue(DateraUtil.VOL_PLACEMENT, url, false); - if (volPlacement == null) { - return DEFAULT_VOL_PLACEMENT; - } else { - return volPlacement; - } - } - - public static String getIpPool(String url) { - String ipPool = getValue(DateraUtil.IP_POOL, url, false); - if (ipPool == null) { - return DEFAULT_IP_POOL; - } else { - return ipPool; - } - } - - private static String getVip(String keyToMatch, String url) { - String delimiter = ":"; - - String storageVip = getValue(keyToMatch, url); - - int index = storageVip.indexOf(delimiter); - - if (index != -1) { - return storageVip.substring(0, index); - } - - return storageVip; - } - - private static int getPort(String keyToMatch, String url, int defaultPortNumber) { - String delimiter = ":"; - - String storageVip = getValue(keyToMatch, url); - - int index = storageVip.indexOf(delimiter); - - int portNumber = defaultPortNumber; - - if (index != -1) { - String port = storageVip.substring(index + delimiter.length()); - - try { - portNumber = Integer.parseInt(port); - } catch (NumberFormatException ex) { - throw new IllegalArgumentException("Invalid URL format (port is not an integer)"); - } - } - - return portNumber; - } - - public static String getValue(String keyToMatch, String url) { - return getValue(keyToMatch, url, true); - } - - public static String getValue(String keyToMatch, String url, boolean throwExceptionIfNotFound) { - String delimiter1 = ";"; - String delimiter2 = "="; - - StringTokenizer st = new StringTokenizer(url, delimiter1); - - while (st.hasMoreElements()) { - String token = st.nextElement().toString(); - - int index = token.indexOf(delimiter2); - - if (index == -1) { - throw new CloudRuntimeException("Invalid URL format"); - } - - String key = token.substring(0, index); - - if (key.equalsIgnoreCase(keyToMatch)) { - return token.substring(index + delimiter2.length()); - } - } - - if (throwExceptionIfNotFound) { - throw new CloudRuntimeException("Key not found in URL"); - } - - return null; - } - - public static String getModifiedUrl(String originalUrl) { - StringBuilder sb = new StringBuilder(); - - String delimiter = ";"; - - StringTokenizer st = new StringTokenizer(originalUrl, delimiter); - - while (st.hasMoreElements()) { - String token = st.nextElement().toString().toUpperCase(); - - if (token.startsWith(DateraUtil.MANAGEMENT_VIP.toUpperCase()) - || token.startsWith(DateraUtil.STORAGE_VIP.toUpperCase())) { - sb.append(token).append(delimiter); - } - } - - String modifiedUrl = sb.toString(); - int lastIndexOf = modifiedUrl.lastIndexOf(delimiter); - - if (lastIndexOf == (modifiedUrl.length() - delimiter.length())) { - return modifiedUrl.substring(0, lastIndexOf); - } - - return modifiedUrl; - } - - public static DateraObject.DateraConnection getDateraConnection(long storagePoolId, - StoragePoolDetailsDao storagePoolDetailsDao) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, - DateraUtil.MANAGEMENT_VIP); - - String mVip = storagePoolDetail.getValue(); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, DateraUtil.MANAGEMENT_PORT); - - int mPort = Integer.parseInt(storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, DateraUtil.CLUSTER_ADMIN_USERNAME); - - String clusterAdminUsername = storagePoolDetail.getValue(); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, DateraUtil.CLUSTER_ADMIN_PASSWORD); - - String clusterAdminPassword = storagePoolDetail.getValue(); - - return new DateraObject.DateraConnection(mVip, mPort, clusterAdminUsername, clusterAdminPassword); - } - - public static boolean hostsSupport_iScsi(List hosts) { - if (hosts == null || hosts.size() == 0) { - return false; - } - - for (Host host : hosts) { - if (!hostSupport_iScsi(host)) { - return false; - } - } - - return true; - } - - public static boolean hostSupport_iScsi(Host host) { - if (host == null || host.getStorageUrl() == null || host.getStorageUrl().trim().length() == 0 - || !host.getStorageUrl().startsWith("iqn")) { - return false; - } - return true; - } - - public static String getInitiatorGroupKey(long storagePoolId) { - return "DateraInitiatorGroup-" + storagePoolId; - } - - /** - * Checks whether a host initiator is present in an initiator group - * - * @param initiator Host initiator to check - * @param initiatorGroup the initiator group - * @return true if host initiator is in the group, false otherwise - */ - public static boolean isInitiatorPresentInGroup(DateraObject.Initiator initiator, - DateraObject.InitiatorGroup initiatorGroup) { - - for (String memberPath : initiatorGroup.getMembers()) { - if (memberPath.equals(initiator.getPath())) { - return true; - } - } - - return false; - } - - public static int bytesToGib(long volumeSizeBytes) { - return (int) Math.ceil(volumeSizeBytes / (double) ONEGIB_BYTES); - } - - public static long gibToBytes(int volumeSizeGb) { - return volumeSizeGb * ONEGIB_BYTES; - } - - /** - * IQN path is stored in the DB by cloudstack it is of the form //0 - * - * @param iqn: IQN of the LUN - * @return IQN path as defined above - */ - public static String generateIqnPath(String iqn) { - if (iqn != null) { - return "/" + iqn + "/0"; - } - return null; - } - - /** - * Does the opposite of generateIqnPath - * - * @param iqnPath - * @return timmed IQN path - */ - - public static String extractIqn(String iqnPath) { - - if (iqnPath == null) { - return null; - } - - if (iqnPath.endsWith("/")) { - iqnPath = iqnPath.substring(0, iqnPath.length() - 1); - } - - final String tokens[] = iqnPath.split("/"); - if (tokens.length != 3) { - final String msg = "Wrong iscsi path " + iqnPath + " it should be /targetIQN/LUN"; - LOGGER.warn(msg); - return null; - } - - return tokens[1].trim(); - } - - /** - * Generate random uuid - * - * @param seed - * @param length ( default to 8 ) - * @return String uuid - */ - public static String generateUUID(String seed) { - int length = UUID_LENGTH; - // creating UUID - UUID uid = UUID.fromString(seed); - String uuid = String.valueOf(uid.randomUUID()).substring(0, length); - - return uuid; - } - -} diff --git a/plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/module.properties b/plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/module.properties deleted file mode 100644 index cecb8b15436d..000000000000 --- a/plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=storage-volume-datera -parent=storage diff --git a/plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/spring-storage-volume-datera-context.xml b/plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/spring-storage-volume-datera-context.xml deleted file mode 100644 index 84ca8fd4141a..000000000000 --- a/plugins/storage/volume/datera/src/main/resources/META-INF/cloudstack/storage-volume-datera/spring-storage-volume-datera-context.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - diff --git a/plugins/storage/volume/nexenta/pom.xml b/plugins/storage/volume/nexenta/pom.xml deleted file mode 100644 index d1de59bd24e4..000000000000 --- a/plugins/storage/volume/nexenta/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - cloud-plugin-storage-volume-nexenta - Apache CloudStack Plugin - Storage Volume Nexenta Provider - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../../pom.xml - - - - org.apache.cloudstack - cloud-engine-storage-volume - ${project.version} - - - - - - maven-surefire-plugin - - - integration-test - - test - - - - - - - diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java deleted file mode 100644 index dad4819c83e2..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/driver/NexentaPrimaryDataStoreDriver.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.driver; - -import static org.apache.cloudstack.storage.datastore.util.NexentaUtil.NexentaPluginParameters; - -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; -import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance; -import org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.NexentaStorZvol; -import org.apache.cloudstack.storage.datastore.util.NexentaUtil; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.host.Host; -import com.cloud.storage.Storage; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StoragePool; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.Pair; - -public class NexentaPrimaryDataStoreDriver implements PrimaryDataStoreDriver { - protected Logger logger = LogManager.getLogger(getClass()); - - @Override - public boolean grantAccess(DataObject dataObject, Host host, DataStore dataStore) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void revokeAccess(DataObject dataObject, Host host, DataStore dataStore) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public long getUsedBytes(StoragePool storagePool) { - return 0; - } - - @Override - public long getUsedIops(StoragePool storagePool) { - return 0; - } - - @Override - public long getDataObjectSizeIncludingHypervisorSnapshotReserve(DataObject dataObject, StoragePool pool) { - return 0; - } - - @Override - public long getBytesRequiredForTemplate(TemplateInfo templateInfo, StoragePool storagePool) { - return 0; - } - - @Inject - private VolumeDao _volumeDao; - @Inject - PrimaryDataStoreDao _storagePoolDao; - @Inject - private StoragePoolDetailsDao _storagePoolDetailsDao; - @Inject - private AccountDao _accountDao; - - @Override - public Map getCapabilities() { - return null; - } - - @Override - public ChapInfo getChapInfo(DataObject dataObject) { - return null; - } - - @Override - public DataTO getTO(DataObject data) { - return null; - } - - @Override - public DataStoreTO getStoreTO(DataStore store) { - return null; - } - - private NexentaStorAppliance getNexentaStorAppliance(long storagePoolId) { - NexentaPluginParameters parameters = new NexentaPluginParameters(); - - parameters.setNmsUrl(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.NMS_URL).getValue()); - parameters.setVolume(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.VOLUME).getValue()); - parameters.setStorageType(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_TYPE).getValue()); - parameters.setStorageHost(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_HOST).getValue()); - parameters.setStoragePort(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_PORT).getValue()); - parameters.setStoragePath(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.STORAGE_PATH).getValue()); - parameters.setSparseVolumes(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.SPARSE_VOLUMES).getValue()); - parameters.setVolumeBlockSize(_storagePoolDetailsDao.findDetail(storagePoolId, NexentaUtil.VOLUME_BLOCK_SIZE).getValue()); - - return new NexentaStorAppliance(parameters); - } - - @Override - public void takeSnapshot(SnapshotInfo snapshot, AsyncCompletionCallback callback) {} - - @Override - public void revertSnapshot(SnapshotInfo snapshot, SnapshotInfo snapshotOnPrimaryStore, AsyncCompletionCallback callback) {} - - @Override - public void createAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { - String iqn = null; - String errorMessage = null; - - if (dataObject.getType() != DataObjectType.VOLUME) { - errorMessage = "Invalid DataObjectType (" + dataObject.getType() + ") passed to createAsync"; - } else { - VolumeInfo volumeInfo = (VolumeInfo) dataObject; - - long storagePoolId = dataStore.getId(); - NexentaStorAppliance appliance = getNexentaStorAppliance(storagePoolId); - - // TODO: maybe we should use md5(volume name) as volume name - NexentaStorZvol zvol = (NexentaStorZvol) appliance.createVolume(volumeInfo.getName(), volumeInfo.getSize()); - iqn = zvol.getIqn(); - - VolumeVO volume = this._volumeDao.findById(volumeInfo.getId()); - volume.set_iScsiName(iqn); - volume.setFolder(zvol.getName()); - volume.setPoolType(Storage.StoragePoolType.IscsiLUN); - volume.setPoolId(storagePoolId); - _volumeDao.update(volume.getId(), volume); - - StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); - long capacityBytes = storagePool.getCapacityBytes(); - long usedBytes = storagePool.getUsedBytes(); - usedBytes += volumeInfo.getSize(); - storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); - _storagePoolDao.update(storagePoolId, storagePool); - } - - CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errorMessage == null, errorMessage)); - result.setResult(errorMessage); - callback.complete(result); - } - - @Override - public void deleteAsync(DataStore store, DataObject data, AsyncCompletionCallback callback) { - String errorMessage = null; - if (data.getType() == DataObjectType.VOLUME) { - VolumeInfo volumeInfo = (VolumeInfo) data; - long storagePoolId = store.getId(); - NexentaStorAppliance appliance = getNexentaStorAppliance(storagePoolId); - StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); - - } else { - errorMessage = String.format( - "Invalid DataObjectType(%s) passed to deleteAsync", - data.getType()); - } - CommandResult result = new CommandResult(); - result.setResult(errorMessage); - callback.complete(result); - } - - @Override - public void copyAsync(DataObject srcdata, DataObject destData, AsyncCompletionCallback callback) {} - - @Override - public void copyAsync(DataObject srcData, DataObject destData, Host destHost, AsyncCompletionCallback callback) { - } - - @Override - public boolean canCopy(DataObject srcData, DataObject destData) { - return false; - } - - @Override - public void resize(DataObject data, AsyncCompletionCallback callback) {} - - @Override - public void handleQualityOfServiceForVolumeMigration(VolumeInfo volumeInfo, QualityOfServiceState qualityOfServiceState) {} - - @Override - public boolean canProvideStorageStats() { - return false; - } - - @Override - public boolean canProvideVolumeStats() { - return false; - } - - @Override - public Pair getVolumeStats(StoragePool storagePool, String volumeId) { - return null; - } - - @Override - public Pair getStorageStats(StoragePool storagePool) { - return null; - } - - @Override - public boolean canHostAccessStoragePool(Host host, StoragePool pool) { - return true; - } - - @Override - public boolean isVmInfoNeeded() { - return false; - } - - @Override - public void provideVmInfo(long vmId, long volumeId) { - } - - @Override - public boolean isVmTagsNeeded(String tagKey) { - return false; - } - - @Override - public void provideVmTags(long vmId, long volumeId, String tagValue) { - } - - @Override - public boolean isStorageSupportHA(StoragePoolType type) { - return false; - } - - @Override - public void detachVolumeFromAllStorageNodes(Volume volume) { - } - - @Override - public boolean volumesRequireGrantAccessWhenUsed() { - return true; - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java deleted file mode 100644 index 431346105524..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.lifecylce; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import com.cloud.storage.dao.StoragePoolAndAccessGroupMapDao; -import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.storage.datastore.lifecycle.BasePrimaryDataStoreLifeCycleImpl; -import org.apache.cloudstack.storage.datastore.util.NexentaUtil; -import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; - -import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.Hypervisor; -import com.cloud.resource.ResourceManager; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolAutomation; - -public class NexentaPrimaryDataStoreLifeCycle - extends BasePrimaryDataStoreLifeCycleImpl - implements PrimaryDataStoreLifeCycle { - - @Inject - private DataCenterDao zoneDao; - @Inject - private PrimaryDataStoreHelper dataStoreHelper; - @Inject - private ResourceManager _resourceMgr; - @Inject - StorageManager _storageMgr; - @Inject - private StoragePoolAutomation storagePoolAutomation; - @Inject - private StoragePoolAndAccessGroupMapDao storagePoolAndAccessGroupMapDao; - - @Override - public DataStore initialize(Map dsInfos) { - String url = (String) dsInfos.get("url"); - Long zoneId = (Long) dsInfos.get("zoneId"); - String storagePoolName = (String) dsInfos.get("name"); - String providerName = (String) dsInfos.get("providerName"); - Long capacityBytes = (Long)dsInfos.get("capacityBytes"); - Long capacityIops = (Long)dsInfos.get("capacityIops"); - String tags = (String)dsInfos.get("tags"); - Boolean isTagARule = (Boolean) dsInfos.get("isTagARule"); - Map details = (Map) dsInfos.get("details"); - NexentaUtil.NexentaPluginParameters params = NexentaUtil.parseNexentaPluginUrl(url); - DataCenterVO zone = zoneDao.findById(zoneId); - String uuid = String.format("%s_%s_%s", NexentaUtil.PROVIDER_NAME, zone.getUuid(), params.getNmsUrl().getHost()); - - if (capacityBytes == null || capacityBytes <= 0) { - throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0."); - } - - if (capacityIops == null || capacityIops <= 0) { - throw new IllegalArgumentException("'capacityIops' must be present and greater than 0."); - } - - PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); - - parameters.setHost(params.getStorageHost()); - parameters.setPort(params.getStoragePort()); - parameters.setPath(params.getStoragePath()); - parameters.setType(params.getStorageType()); - parameters.setUuid(uuid); - parameters.setZoneId(zoneId); - parameters.setName(storagePoolName); - parameters.setProviderName(providerName); - parameters.setManaged(true); - parameters.setCapacityBytes(capacityBytes); - parameters.setUsedBytes(0); - parameters.setCapacityIops(capacityIops); - parameters.setHypervisorType(Hypervisor.HypervisorType.Any); - parameters.setTags(tags); - parameters.setIsTagARule(isTagARule); - - details.put(NexentaUtil.NMS_URL, params.getNmsUrl().toString()); - - details.put(NexentaUtil.VOLUME, params.getVolume()); - details.put(NexentaUtil.SPARSE_VOLUMES, params.isSparseVolumes().toString()); - - details.put(NexentaUtil.STORAGE_TYPE, params.getStorageType().toString()); - details.put(NexentaUtil.STORAGE_HOST, params.getStorageHost()); - details.put(NexentaUtil.STORAGE_PORT, params.getStoragePort().toString()); - details.put(NexentaUtil.STORAGE_PATH, params.getStoragePath()); - - parameters.setDetails(details); - - // this adds a row in the cloud.storage_pool table for this SolidFire cluster - return dataStoreHelper.createPrimaryDataStore(parameters); - } - - @Override - public boolean attachCluster(DataStore store, ClusterScope scope) { - return true; - } - - @Override - public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { - return true; - } - - @Override - public boolean attachZone(DataStore dataStore, ZoneScope scope, Hypervisor.HypervisorType hypervisorType) { - dataStoreHelper.attachZone(dataStore); - - List hostsToConnect = new ArrayList<>(); - Hypervisor.HypervisorType[] hypervisorTypes = {Hypervisor.HypervisorType.XenServer, Hypervisor.HypervisorType.VMware, Hypervisor.HypervisorType.KVM}; - - for (Hypervisor.HypervisorType type : hypervisorTypes) { - hostsToConnect.addAll(_resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, scope.getScopeId(), type)); - } - logger.debug(String.format("In createPool. Attaching the pool to each of the hosts in %s.", hostsToConnect)); - for (HostVO host : hostsToConnect) { - try { - _storageMgr.connectHostToSharedPool(host, dataStore.getId()); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); - } - } - - return true; - } - - @Override - public boolean maintain(DataStore store) { - storagePoolAutomation.maintain(store); - dataStoreHelper.maintain(store); - - return true; - } - - @Override - public boolean cancelMaintain(DataStore store) { - dataStoreHelper.cancelMaintain(store); - storagePoolAutomation.cancelMaintain(store); - - return true; - } - - @Override - public void enableStoragePool(DataStore dataStore) { - dataStoreHelper.enable(dataStore); - } - - @Override - public void disableStoragePool(DataStore dataStore) { - dataStoreHelper.disable(dataStore); - } - - @Override - public void changeStoragePoolScopeToZone(DataStore store, ClusterScope clusterScope, Hypervisor.HypervisorType hypervisorType) { - /* - * We need to attach all VMware, Xenserver and KVM hosts in the zone. - * So pass hypervisorType as null. - */ - super.changeStoragePoolScopeToZone(store, clusterScope, null); - } - - @Override - public boolean deleteDataStore(DataStore store) { - return dataStoreHelper.deletePrimaryDataStore(store); - } - - @Override - public boolean migrateToObjectStore(DataStore store) { - return false; - } - - @Override - public void updateStoragePool(StoragePool storagePool, Map details) { - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java deleted file mode 100644 index 376cd29d2eb3..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaHostListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; - -public class NexentaHostListener implements HypervisorHostListener { - protected Logger logger = LogManager.getLogger(getClass()); - - @Override - public boolean hostAdded(long hostId) { - logger.trace("hostAdded(long) invoked"); - - return true; - } - - @Override - public boolean hostConnect(long hostId, long poolId) { - logger.trace("hostConnect(long, long) invoked"); - - return true; - } - - @Override - public boolean hostDisconnected(long hostId, long poolId) { - logger.trace("hostDisconnected(long, long) invoked"); - - return true; - } - - @Override - public boolean hostAboutToBeRemoved(long hostId) { - logger.trace("hostAboutToBeRemoved(long) invoked"); - - return true; - } - - @Override - public boolean hostRemoved(long hostId, long clusterId) { - logger.trace("hostRemoved(long) invoked"); - - return true; - } - - @Override - public boolean hostEnabled(long hostId) { - return true; - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java deleted file mode 100644 index afd7e35c2570..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/provider/NexentaPrimaryDataStoreProvider.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; -import org.apache.cloudstack.storage.datastore.driver.NexentaPrimaryDataStoreDriver; -import org.apache.cloudstack.storage.datastore.lifecylce.NexentaPrimaryDataStoreLifeCycle; -import org.apache.cloudstack.storage.datastore.util.NexentaUtil; - -import com.cloud.utils.component.ComponentContext; - -@Component -public class NexentaPrimaryDataStoreProvider implements PrimaryDataStoreProvider { - private DataStoreLifeCycle lifeCycle; - private PrimaryDataStoreDriver driver; - private HypervisorHostListener listener; - - @Override - public DataStoreLifeCycle getDataStoreLifeCycle() { - return lifeCycle; - } - - @Override - public DataStoreDriver getDataStoreDriver() { - return driver; - } - - @Override - public HypervisorHostListener getHostListener() { - return listener; - } - - @Override - public String getName() { - return NexentaUtil.PROVIDER_NAME; - } - - @Override - public boolean configure(Map params) { - lifeCycle = ComponentContext.inject(NexentaPrimaryDataStoreLifeCycle.class); - driver = ComponentContext.inject(NexentaPrimaryDataStoreDriver.class); - listener = ComponentContext.inject(NexentaHostListener.class); - - return true; - } - - @Override - public Set getTypes() { - Set types = new HashSet(); - - types.add(DataStoreProviderType.PRIMARY); - - return types; - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java deleted file mode 100644 index 73f3fa0be78d..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsClient.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.BasicClientConnectionManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.apache.cloudstack.utils.security.SSLUtils; - -import com.google.gson.Gson; -import com.google.gson.annotations.SerializedName; - -import com.cloud.utils.exception.CloudRuntimeException; - -public class NexentaNmsClient { - protected Logger logger = LogManager.getLogger(getClass()); - - protected NexentaNmsUrl nmsUrl = null; - protected DefaultHttpClient httpClient = null; - - NexentaNmsClient(NexentaNmsUrl nmsUrl) { - this.nmsUrl = nmsUrl; - } - - private static boolean isSuccess(int iCode) { - return iCode >= 200 && iCode < 300; - } - - protected DefaultHttpClient getClient() { - if (httpClient == null) { - if (nmsUrl.getSchema().equalsIgnoreCase("http")) { - httpClient = getHttpClient(); - } else { - httpClient = getHttpsClient(); - } - AuthScope authScope = new AuthScope(nmsUrl.getHost(), nmsUrl.getPort(), AuthScope.ANY_SCHEME, "basic"); - UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(nmsUrl.getUsername(), nmsUrl.getPassword()); - httpClient.getCredentialsProvider().setCredentials(authScope, credentials); - } - return httpClient; - } - - protected DefaultHttpClient getHttpsClient() { - try { - SSLContext sslContext = SSLUtils.getSSLContext(); - X509TrustManager tm = new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - }; - - sslContext.init(null, new TrustManager[] {tm}, new SecureRandom()); - - SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - SchemeRegistry registry = new SchemeRegistry(); - - registry.register(new Scheme("https", nmsUrl.getPort(), socketFactory)); - - BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry); - - return new DefaultHttpClient(mgr); - } catch (NoSuchAlgorithmException ex) { - throw new CloudRuntimeException(ex.getMessage()); - } catch (KeyManagementException ex) { - throw new CloudRuntimeException(ex.getMessage()); - } - } - - protected DefaultHttpClient getHttpClient() { - return new DefaultHttpClient(); - } - - @SuppressWarnings("unused") - static class NmsRequest { - private String method; - private String object; - private Object[] params; - - NmsRequest(String object, String method) { - this(object, method, (Object[])null); - } - - NmsRequest(String object, String method, Object... params) { - this.method = method; - this.object = object; - this.params = params; - } - - @Override - public String toString() { - StringBuffer b = new StringBuffer(); - b.append("Request to ").append(object).append(" method ").append(method); - if (params != null) { - b.append(" params:"); - for (Object param:params) { - b.append(" ").append(param).append(","); - } - } - return b.toString(); - } - } - - @SuppressWarnings("unused") - static class NmsError { - private String message; - - public String getMesssage() { - return message; - } - } - - @SuppressWarnings("unused") - static class NmsResponse { - @SerializedName("tg_flash") protected String tgFlash; - - protected NmsError error; - - NmsResponse() {} - - NmsResponse(String tgFlash, NmsError error) { - this.tgFlash = tgFlash; - this.error = error; - } - - public String getTgFlash() { - return tgFlash; - } - - public NmsError getError() { - return error; - } - } - - public NmsResponse execute(Class responseClass, String object, String method, Object... params) { - StringBuilder sb = new StringBuilder(); - NmsRequest nmsRequest = new NmsRequest(object, method, params); - if (logger.isDebugEnabled()) { - logger.debug(nmsRequest); - } - final Gson gson = new Gson(); - String jsonRequest = gson.toJson(nmsRequest); - StringEntity input = new StringEntity(jsonRequest, ContentType.APPLICATION_JSON); - HttpPost postRequest = new HttpPost(nmsUrl.toString()); - postRequest.setEntity(input); - - DefaultHttpClient httpClient = getClient(); - try { - HttpResponse response = httpClient.execute(postRequest); - final int status = response.getStatusLine().getStatusCode(); - if (!isSuccess(status)) { - throw new CloudRuntimeException("Failed on JSON-RPC API call. HTTP error code = " + status); - } - try(BufferedReader buffer = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));) { - String tmp; - while ((tmp = buffer.readLine()) != null) { - sb.append(tmp); - } - }catch (IOException ex) { - throw new CloudRuntimeException(ex.getMessage()); - } - } catch (ClientProtocolException ex) { - throw new CloudRuntimeException(ex.getMessage()); - } catch (IOException ex) { - throw new CloudRuntimeException(ex.getMessage()); - } finally { - if (httpClient != null) { - try { - httpClient.getConnectionManager().shutdown(); - } catch (Exception t) { - logger.debug(t.getMessage()); - } - } - } - - String responseString = sb.toString(); - if (logger.isDebugEnabled()) { - logger.debug("NexentaStor Appliance response: " + responseString); - } - - NmsResponse nmsResponse = (NmsResponse) gson.fromJson(responseString, responseClass); - if (nmsResponse.getError() != null) { - throw new CloudRuntimeException(nmsResponse.getError().getMesssage()); - } - - return nmsResponse; - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java deleted file mode 100644 index 684b8dc1d0c3..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaNmsUrl.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.util; - -public class NexentaNmsUrl { - protected final boolean isAuto; - protected String schema; - protected final String username; - protected final String password; - protected final String host; - protected int port; - - public NexentaNmsUrl(boolean isAuto, String schema, String username, String password, String host, int port) { - this.isAuto = isAuto; - this.schema = schema; - this.username = username; - this.password = password; - this.host = host; - this.port = port; - } - - public boolean isAuto() { - return this.isAuto; - } - - public void setSchema(String schema) { - this.schema = schema; - } - - public String getSchema() { - return this.schema; - } - - public String getUsername() { - return this.username; - } - - public String getPassword() { - return this.password; - } - - public String getHost() { - return this.host; - } - - public int getPort() { - return this.port; - } - - public String getPath() { - return "/rest/nms"; - } - - public String toString() { - StringBuilder b = new StringBuilder(); - if (isAuto) { - b.append("auto://"); - } else { - b.append(schema).append("://"); - } - if (username != null && password != null) { - b.append(username).append(":").append(password).append("@"); - } else if (username != null) { - b.append(username).append("@"); - } - b.append(host).append(":").append(port).append("/rest/nms/"); - return b.toString(); - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java deleted file mode 100644 index 8c22908c64db..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaStorAppliance.java +++ /dev/null @@ -1,418 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.util; - -import java.util.HashMap; -import java.util.LinkedList; - -import org.apache.cloudstack.storage.datastore.util.NexentaNmsClient.NmsResponse; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.utils.exception.CloudRuntimeException; -import com.google.gson.annotations.SerializedName; - -public class NexentaStorAppliance { - protected Logger logger = LogManager.getLogger(getClass()); - - protected NexentaNmsClient client; - protected NexentaUtil.NexentaPluginParameters parameters; - - public NexentaStorAppliance(NexentaUtil.NexentaPluginParameters parameters) { - client = new NexentaNmsClient(parameters.getNmsUrl()); - this.parameters = parameters; - } - - NexentaStorAppliance(NexentaNmsClient client, NexentaUtil.NexentaPluginParameters parameters) { - this.client = client; - this.parameters = parameters; - } - - String getVolumeName(String volumeName) { - if (volumeName.startsWith("/")) { - return String.format("%s%s", parameters.getVolume(), volumeName); - } - return String.format("%s/%s", parameters.getVolume(), volumeName); - } - - static String getTargetName(String volumeName) { - return NexentaUtil.ISCSI_TARGET_NAME_PREFIX + volumeName; - } - - static String getTargetGroupName(String volumeName) { - return NexentaUtil.ISCSI_TARGET_GROUP_PREFIX + volumeName; - } - - @SuppressWarnings("unused") - static final class IntegerNmsResponse extends NmsResponse { - Integer result; - - IntegerNmsResponse(int result) { - this.result = Integer.valueOf(result); - } - - public Integer getResult() { - return result; - } - } - - @SuppressWarnings("unused") - static final class IscsiTarget { - protected String status; - protected String protocol; - protected String name; - protected String sessions; - protected String alias; - protected String provider; - - IscsiTarget(String status, String protocol, String name, String sessions, String alias, String provider) { - this.status = status; - this.protocol = protocol; - this.name = name; - this.sessions = sessions; - this.alias = alias; - this.provider = provider; - } - } - - @SuppressWarnings("unused") - static final class ListOfIscsiTargetsNmsResponse extends NmsResponse { - protected HashMap result; - - ListOfIscsiTargetsNmsResponse() {} - - ListOfIscsiTargetsNmsResponse(HashMap result) { - this.result = result; - } - - public HashMap getResult() { - return result; - } - } - - /** - * Checks if iSCSI target exists. - * @param targetName iSCSI target name - * @return true if iSCSI target exists, else false - */ - boolean isIscsiTargetExists(String targetName) { - ListOfIscsiTargetsNmsResponse response = (ListOfIscsiTargetsNmsResponse) client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets"); - if (response == null) { - return false; - } - HashMap result = response.getResult(); - return result != null && result.keySet().contains(targetName); - } - - @SuppressWarnings("unused") - static final class CreateIscsiTargetRequestParams { - @SerializedName("target_name") String targetName; - - CreateIscsiTargetRequestParams(String targetName) { - this.targetName = targetName; - } - - @Override - public boolean equals(Object other) { - return other instanceof CreateIscsiTargetRequestParams && targetName.equals(((CreateIscsiTargetRequestParams) other).targetName); - } - } - - /** - * Creates iSCSI target on NexentaStor Appliance. - * @param targetName iSCSI target name - */ - void createIscsiTarget(String targetName) { - try { - client.execute(NmsResponse.class, "iscsitarget", "create_target", new CreateIscsiTargetRequestParams(targetName)); - } catch (CloudRuntimeException ex) { - if (!ex.getMessage().contains("already configured")) { - throw ex; - } - logger.debug("Ignored target creation error: " + ex); - } - } - - @SuppressWarnings("unused") - static final class ListOfStringsNmsResponse extends NmsResponse { - LinkedList result; - - ListOfStringsNmsResponse() {} - - ListOfStringsNmsResponse(LinkedList result) { - this.result = result; - } - - public LinkedList getResult() { - return result; - } - } - - /** - * Checks if iSCSI target group already exists on NexentaStor Appliance. - * @param targetGroupName iSCSI target group name - * @return true if iSCSI target group already exists, else false - */ - boolean isIscsiTargetGroupExists(String targetGroupName) { - ListOfStringsNmsResponse response = (ListOfStringsNmsResponse) client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups"); - if (response == null) { - return false; - } - LinkedList result = response.getResult(); - return result != null && result.contains(targetGroupName); - } - - /** - * Creates iSCSI target group on NexentaStor Appliance. - * @param targetGroupName iSCSI target group name - */ - void createIscsiTargetGroup(String targetGroupName) { - try { - client.execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName); - } catch (CloudRuntimeException ex) { - if (!ex.getMessage().contains("already exists") && !ex.getMessage().contains("target must be offline")) { - throw ex; - } - logger.info("Ignored target group creation error: " + ex); - } - } - - /** - * Checks if iSCSI target is member of target group. - * @param targetGroupName iSCSI target group name - * @param targetName iSCSI target name - * @return true if target is member of iSCSI target group, else false - */ - boolean isTargetMemberOfTargetGroup(String targetGroupName, String targetName) { - ListOfStringsNmsResponse response = (ListOfStringsNmsResponse) client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName); - if (response == null) { - return false; - } - LinkedList result = response.getResult(); - return result != null && result.contains(targetName); - } - - /** - * Adds iSCSI target to target group. - * @param targetGroupName iSCSI target group name - * @param targetName iSCSI target name - */ - void addTargetGroupMember(String targetGroupName, String targetName) { - try { - client.execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName); - } catch (CloudRuntimeException ex) { - if (!ex.getMessage().contains("already exists") && !ex.getMessage().contains("target must be offline")) { - throw ex; - } - logger.debug("Ignored target group member addition error: " + ex); - } - } - - /** - * Checks if LU already exists on NexentaStor appliance. - * @param luName LU name - * @return true if LU already exists, else false - */ - boolean isLuExists(String luName) { - IntegerNmsResponse response; - try { - response = (IntegerNmsResponse) client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", luName); - } catch (CloudRuntimeException ex) { - if (ex.getMessage().contains("does not exist")) { - return false; - } - throw ex; - } - return response!= null && response.getResult() > 0; - } - - @SuppressWarnings("unused") - static final class LuParams { - @Override - public boolean equals(Object other) { - return other instanceof LuParams; - } - } - - /** - * Creates LU for volume. - * @param volumeName volume name - */ - void createLu(String volumeName) { - try { - client.execute(NmsResponse.class, "scsidisk", "create_lu", volumeName, new LuParams()); - } catch (CloudRuntimeException ex) { - if (!ex.getMessage().contains("in use")) { - throw ex; - } - logger.info("Ignored LU creation error: " + ex); - } - } - - /** - * Checks if LU shared on NexentaStor appliance. - * @param luName LU name - * @return true if LU was already shared, else false - */ - boolean isLuShared(String luName) { - IntegerNmsResponse response; - try { - response = (IntegerNmsResponse) client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName); - } catch (CloudRuntimeException ex) { - if (ex.getMessage().contains("does not exist")) { - return false; - } - throw ex; - } - return response != null && response.getResult() > 0; - } - - @SuppressWarnings("unused") - static final class MappingEntry { - @SerializedName("target_group") String targetGroup; - String lun; - String zvol; - @SerializedName("host_group") String hostGroup; - @SerializedName("entry_number") String entryNumber; - - MappingEntry(String targetGroup, String lun) { - this.targetGroup = targetGroup; - this.lun = lun; - } - - static boolean isEquals(Object a, Object b) { - return (a == null && b == null) || (a != null && a.equals(b)); - } - - @Override - public boolean equals(Object other) { - if (other instanceof MappingEntry) { - MappingEntry o = (MappingEntry) other; - return isEquals(targetGroup, o.targetGroup) && isEquals(lun, o.lun) && isEquals(zvol, o.zvol) && - isEquals(hostGroup, o.hostGroup) && isEquals(entryNumber, o.entryNumber); - } - return false; - } - } - - @SuppressWarnings("unused") - static final class AddMappingEntryNmsResponse extends NmsResponse { - MappingEntry result; - } - - /** - * Adds LU mapping entry to iSCSI target group. - * @param luName LU name - * @param targetGroupName iSCSI target group name - */ - void addLuMappingEntry(String luName, String targetGroupName) { - MappingEntry mappingEntry = new MappingEntry(targetGroupName, "0"); - try { - client.execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry); - } catch (CloudRuntimeException ex) { - if (!ex.getMessage().contains("view already exists")) { - throw ex; - } - logger.debug("Ignored LU mapping entry addition error " + ex); - } - } - - NexentaStorZvol createIscsiVolume(String volumeName, Long volumeSize) { - final String zvolName = getVolumeName(volumeName); - String volumeSizeString = String.format("%dB", volumeSize); - - client.execute(NmsResponse.class, "zvol", "create", zvolName, volumeSizeString, parameters.getVolumeBlockSize(), parameters.isSparseVolumes()); - - final String targetName = getTargetName(volumeName); - final String targetGroupName = getTargetGroupName(volumeName); - - if (!isIscsiTargetExists(targetName)) { - createIscsiTarget(targetName); - } - - if (!isIscsiTargetGroupExists(targetGroupName)) { - createIscsiTargetGroup(targetGroupName); - } - - if (!isTargetMemberOfTargetGroup(targetGroupName, targetName)) { - addTargetGroupMember(targetGroupName, targetName); - } - - if (!isLuExists(zvolName)) { - createLu(zvolName); - } - - if (!isLuShared(zvolName)) { - addLuMappingEntry(zvolName, targetGroupName); - } - - return new NexentaStorZvol(zvolName, targetName); - } - - static abstract class NexentaStorVolume { - protected String name; - - NexentaStorVolume(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return name; - } - } - - public static final class NexentaStorZvol extends NexentaStorVolume { - protected String iqn; - - public NexentaStorZvol(String name, String iqn) { - super(name); - this.iqn = iqn; - } - - public String getIqn() { - return iqn; - } - } - - public void deleteIscsiVolume(String volumeName) { - try { - NmsResponse response = client.execute(NmsResponse.class, "zvol", "destroy", volumeName, ""); - } catch (CloudRuntimeException ex) { - if (!ex.getMessage().contains("does not exist")) { - throw ex; - } - logger.debug(String.format( - "Volume %s does not exist, it seems it was already " + - "deleted.", volumeName)); - } - } - - public NexentaStorVolume createVolume(String volumeName, Long volumeSize) { - return createIscsiVolume(volumeName, volumeSize); - } - - public void deleteVolume(String volumeName) { - deleteIscsiVolume(volumeName); - } -} diff --git a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java b/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java deleted file mode 100644 index 7eef85b281ee..000000000000 --- a/plugins/storage/volume/nexenta/src/main/java/org/apache/cloudstack/storage/datastore/util/NexentaUtil.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.util; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.StringTokenizer; - -import com.cloud.storage.Storage; - -public class NexentaUtil { - public static final String PROVIDER_NAME = "Nexenta"; - - public static final String NMS_URL = "nmsUrl"; - public static final String VOLUME = "volume"; - - public static final String STORAGE_HOST = "storageHost"; - public static final String STORAGE_PORT = "storagePort"; - public static final String STORAGE_TYPE = "storageType"; - public static final String STORAGE_PATH = "storagePath"; - - public static final String DEFAULT_NMS_USER = "admin"; - public static final String DEFAULT_NMS_PASSWORD = "nexenta"; - - public static final String SPARSE_VOLUMES = "sparseVolumes"; - public static final String VOLUME_BLOCK_SIZE = "volumeBlockSize"; - - public static final int DEFAULT_NMS_PORT = 2000; - public static final int DEFAULT_ISCSI_TARGET_PORTAL_PORT = 3260; - public static final int DEFAULT_NFS_PORT = 2049; - - public static final String ISCSI_TARGET_NAME_PREFIX = "iqn.1986-03.com.sun:02:cloudstack-"; - public static final String ISCSI_TARGET_GROUP_PREFIX = "cloudstack/"; - - /** - * Parse NMS url into normalized parts like scheme, user, host and others. - * - * Example NMS URL: - * auto://admin:nexenta@192.168.1.1:2000/ - * - * NMS URL parts: - * auto true if url starts with auto://, protocol will be automatically switched to https if http not supported; - * scheme (auto) connection protocol (http or https); - * user (admin) NMS user; - * password (nexenta) NMS password; - * host (192.168.1.1) NMS host; - * port (2000) NMS port. - * - * @param nmsUrl url string to parse - * @return instance of NexentaConnection class - */ - public static NexentaNmsUrl parseNmsUrl(String nmsUrl) { - URI uri; - - try { - uri = new URI(nmsUrl); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid URI: " + nmsUrl); - } - - boolean isAuto = false; - String schema = uri.getScheme(); - if (schema == null || schema.isEmpty() || "auto".equalsIgnoreCase(schema)) { - schema = "http"; - isAuto = true; - } - - String username, password, userInfo = uri.getUserInfo(); - if (userInfo == null) { - username = DEFAULT_NMS_USER; - password = DEFAULT_NMS_PASSWORD; - } else { - if (userInfo.indexOf(':') < 0) { - username = userInfo; - password = DEFAULT_NMS_PASSWORD; - } else { - String[] parts = userInfo.split(":", 2); - username = parts[0]; - password = parts[1]; - } - } - - String host = uri.getHost(); - if (host == null) { - throw new IllegalArgumentException(String.format("NMS host required: %s.", nmsUrl)); - } - - int port = uri.getPort(); - if (port == -1) { - port = DEFAULT_NMS_PORT; - } - - return new NexentaNmsUrl(isAuto, schema, username, password, host, port); - } - - public static Storage.StoragePoolType getStorageType(String v) { - if ("iSCSI".equalsIgnoreCase(v)) { - return Storage.StoragePoolType.Iscsi; - } else if ("NFS".equalsIgnoreCase(v)) { - return Storage.StoragePoolType.NetworkFilesystem; - } - return Storage.StoragePoolType.Iscsi; - } - - public static class NexentaPluginParameters { - protected NexentaNmsUrl nmsUrl; - protected String volume; - protected Storage.StoragePoolType storageType = Storage.StoragePoolType.Iscsi; - protected String storageHost; - protected Integer storagePort; - protected String storagePath; - protected Boolean sparseVolumes = false; - protected String volumeBlockSize = "8K"; - - public void setNmsUrl(String url) { - this.nmsUrl = NexentaUtil.parseNmsUrl(url); - } - - public NexentaNmsUrl getNmsUrl() { - return nmsUrl; - } - - public void setVolume(String volume) { - if (volume.endsWith("/")) { - this.volume = volume.substring(0, volume.length() - 1); - } else { - this.volume = volume; - } - } - - public String getVolume() { - return volume; - } - - public void setStorageType(String storageType) { - this.storageType = NexentaUtil.getStorageType(storageType); - } - - public Storage.StoragePoolType getStorageType() { - return storageType; - } - - public void setStorageHost(String host) { - this.storageHost = host; - } - - public String getStorageHost() { - if (storageHost == null && nmsUrl != null) { - return nmsUrl.getHost(); - } - return storageHost; - } - - public void setStoragePort(String port) { - this.storagePort = Integer.parseInt(port); - } - - public Integer getStoragePort() { - if (storagePort == null && storageType != null) { - if (storageType == Storage.StoragePoolType.Iscsi) { - return DEFAULT_ISCSI_TARGET_PORTAL_PORT; - } else { - return DEFAULT_NFS_PORT; - } - } - return storagePort; - } - - public void setStoragePath(String path) { - this.storagePath = path; - } - - public String getStoragePath() { - return storagePath; - } - - public void setSparseVolumes(String sparseVolumes) { - this.sparseVolumes = Boolean.TRUE.toString().equalsIgnoreCase(sparseVolumes); - } - - public Boolean isSparseVolumes() { - return sparseVolumes; - } - - public void setVolumeBlockSize(String volumeBlockSize) { - this.volumeBlockSize = volumeBlockSize; - } - - public String getVolumeBlockSize() { - return volumeBlockSize; - } - } - - public static NexentaPluginParameters parseNexentaPluginUrl(String url) { - final String delimiter1 = ";"; - final String delimiter2 = "="; - StringTokenizer st = new StringTokenizer(url, delimiter1); - NexentaPluginParameters params = new NexentaPluginParameters(); - while (st.hasMoreElements()) { - String token = st.nextElement().toString(); - int idx = token.indexOf(delimiter2); - if (idx == -1) { - throw new RuntimeException("Invalid URL format"); - } - String[] urlKeyAndValue = token.split(delimiter2, 2); - if (NMS_URL.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setNmsUrl(urlKeyAndValue[1]); - } else if (VOLUME.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setVolume(urlKeyAndValue[1]); - } else if (STORAGE_TYPE.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setStorageType(urlKeyAndValue[1]); - } else if (STORAGE_HOST.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setStorageHost(urlKeyAndValue[1]); - } else if (STORAGE_PORT.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setStoragePort(urlKeyAndValue[1]); - } else if (STORAGE_PATH.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setStoragePath(urlKeyAndValue[1]); - } else if (SPARSE_VOLUMES.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setSparseVolumes(urlKeyAndValue[1]); - } else if (VOLUME_BLOCK_SIZE.equalsIgnoreCase(urlKeyAndValue[0])) { - params.setVolumeBlockSize(urlKeyAndValue[1]); - } - } - return params; - } -} diff --git a/plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties b/plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties deleted file mode 100644 index fe95f289dcd0..000000000000 --- a/plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=storage-volume-nexenta -parent=storage diff --git a/plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml b/plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml deleted file mode 100644 index c1dae747505d..000000000000 --- a/plugins/storage/volume/nexenta/src/main/resources/META-INF.cloudstack.storage-volume-solidfire/spring-storage-volume-nexenta-context.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - diff --git a/plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java b/plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java deleted file mode 100644 index d283e4c35d74..000000000000 --- a/plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaStorApplianceTest.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.util; - -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.IscsiTarget; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.ListOfIscsiTargetsNmsResponse; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.CreateIscsiTargetRequestParams; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.ListOfStringsNmsResponse; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.IntegerNmsResponse; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.LuParams; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.MappingEntry; -import static org.apache.cloudstack.storage.datastore.util.NexentaStorAppliance.AddMappingEntryNmsResponse; -import static org.apache.cloudstack.storage.datastore.util.NexentaNmsClient.NmsResponse; - - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.LinkedList; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; - -import com.cloud.utils.exception.CloudRuntimeException; - -@RunWith(MockitoJUnitRunner.class) -public class NexentaStorApplianceTest { - private NexentaNmsClient client; - - private NexentaStorAppliance appliance; - - @Rule - public ExpectedException exception = ExpectedException.none(); - - @Before - public void init() { - final String url = "nmsUrl=https://admin:nexenta@10.1.3.182:8457;volume=cloudstack;storageType=iscsi"; - NexentaUtil.NexentaPluginParameters parameters = NexentaUtil.parseNexentaPluginUrl(url); - client = mock(NexentaNmsClient.class); - appliance = new NexentaStorAppliance(client, parameters); - } - - @Test - public void testIsIscsiTargetExists() { - final String targetName = NexentaStorAppliance.getTargetName("volume1"); - - when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(null); - assertFalse(appliance.isIscsiTargetExists(targetName)); - - when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(new ListOfIscsiTargetsNmsResponse()); - assertFalse(appliance.isIscsiTargetExists(targetName)); - - final HashMap result = new HashMap(); - - result.put("any", new IscsiTarget("Online", "iSCSI", "any", "0", "-", "iscsit")); - when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(new ListOfIscsiTargetsNmsResponse(result)); - assertFalse(appliance.isIscsiTargetExists(targetName)); - - result.put(targetName, new IscsiTarget("Online", "iSCSI", targetName, "0", "-", "iscsit")); - when(client.execute(ListOfIscsiTargetsNmsResponse.class, "stmf", "list_targets")).thenReturn(new ListOfIscsiTargetsNmsResponse(result)); - assertTrue(appliance.isIscsiTargetExists(targetName)); - } - - final static String ISCSI_TARGET_ALREADY_CONFIGURED_ERROR = "Unable to create iscsi target\\n iSCSI target %s already configured\\n itadm create-target failed with error " + - "17\\n"; - - @Test - public void testCreateIscsiTarget() { - final String targetName = NexentaStorAppliance.getTargetName("volume1"); - final CreateIscsiTargetRequestParams p = new CreateIscsiTargetRequestParams(targetName); - - appliance.createIscsiTarget(targetName); - verify(client).execute(NmsResponse.class, "iscsitarget", "create_target", p); - - final String error = String.format(ISCSI_TARGET_ALREADY_CONFIGURED_ERROR, targetName); - when(client.execute(NmsResponse.class, "iscsitarget", "create_target", p)).thenThrow(new CloudRuntimeException(error)); - appliance.createIscsiTarget(targetName); - } - - @Test - public void testCreateIscsiTargetFails() { - final String targetName = NexentaStorAppliance.getTargetName("volume1"); - final CreateIscsiTargetRequestParams p = new CreateIscsiTargetRequestParams(targetName); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - when(client.execute(NmsResponse.class, "iscsitarget", "create_target", p)).thenThrow(new CloudRuntimeException("any exception")); - appliance.createIscsiTarget(targetName); - } - - @Test - public void testIsIscsiTargetGroupExists() { - final String targetGroup = NexentaStorAppliance.getTargetGroupName("volume1"); - - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(null); - assertFalse(appliance.isIscsiTargetGroupExists(targetGroup)); - - assertFalse(appliance.isIscsiTargetGroupExists(targetGroup)); - - LinkedList result = new LinkedList(); - - result.add("any"); - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(new ListOfStringsNmsResponse(result)); - assertFalse(appliance.isIscsiTargetGroupExists(targetGroup)); - - result.add(targetGroup); - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroups")).thenReturn(new ListOfStringsNmsResponse(result)); - assertTrue(appliance.isIscsiTargetGroupExists(targetGroup)); - } - - final static String ISCSI_TARGET_GROUP_EXISTS_ERROR = "Unable to create targetgroup: stmfadm: %s: already exists\\n"; - - @Test - public void testCreateIscsiTargetGroup() { - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - - appliance.createIscsiTargetGroup(targetGroupName); - verify(client).execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName); - - final String error = String.format(ISCSI_TARGET_GROUP_EXISTS_ERROR, targetGroupName); - when(client.execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName)).thenThrow(new CloudRuntimeException(error)); - appliance.createIscsiTargetGroup(targetGroupName); - } - - @Test - public void testCreateIscsiTargetGroupFails() { - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - when(client.execute(NmsResponse.class, "stmf", "create_targetgroup", targetGroupName)).thenThrow(new CloudRuntimeException("any exception")); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - appliance.createIscsiTargetGroup(targetGroupName); - } - - @Test - public void testIsMemberOfTargetGroup() { - final String targetName = NexentaStorAppliance.getTargetName("volume1"); - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(null); - assertFalse(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); - - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(new ListOfStringsNmsResponse()); - assertFalse(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); - - LinkedList result = new LinkedList(); - - result.add("any"); - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(new ListOfStringsNmsResponse(result)); - assertFalse(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); - - result.add(targetName); - when(client.execute(ListOfStringsNmsResponse.class, "stmf", "list_targetgroup_members", targetGroupName)).thenReturn(new ListOfStringsNmsResponse(result)); - assertTrue(appliance.isTargetMemberOfTargetGroup(targetGroupName, targetName)); - } - - @Test - public void testAddTargetGroupMember() { - final String targetName = NexentaStorAppliance.getTargetName("volume1"); - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - - appliance.addTargetGroupMember(targetGroupName, targetName); - verify(client).execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName); - - String error = String.format(ISCSI_TARGET_ALREADY_EXISTS_IN_TARGET_GROUP_ERROR, targetName); - when(client.execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName)).thenThrow(new CloudRuntimeException(error)); - appliance.addTargetGroupMember(targetGroupName, targetName); - } - - final static String ISCSI_TARGET_ALREADY_EXISTS_IN_TARGET_GROUP_ERROR = "Unable to add member to targetgroup: stmfadm: %s: already exists\\n"; - - @Test - public void testAddTargetGroupMemberFails() { - final String targetName = NexentaStorAppliance.getTargetName("volume1"); - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - - when(client.execute(NmsResponse.class, "stmf", "add_targetgroup_member", targetGroupName, targetName)).thenThrow(new CloudRuntimeException("any exception")); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - appliance.addTargetGroupMember(targetGroupName, targetName); - } - - @Test - public void testIsLuExists() { - final String volumeName = appliance.getVolumeName("volume1"); - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenReturn(null); - assertFalse(appliance.isLuExists(volumeName)); - - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenReturn(new IntegerNmsResponse(0)); - assertFalse(appliance.isLuExists(volumeName)); - - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenReturn(new IntegerNmsResponse(1)); - assertTrue(appliance.isLuExists(volumeName)); - - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenThrow(new CloudRuntimeException("does not exist")); - assertFalse(appliance.isLuExists(volumeName)); - } - - @Test - public void testIsLuExistsFails() { - final String volumeName = appliance.getVolumeName("volume1"); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_exists", volumeName)).thenThrow(new CloudRuntimeException("any exception")); - assertTrue(appliance.isLuExists(volumeName)); - } - - final static String CREATE_LU_IN_USE_ERROR = "Unable to create lu with " + - "zvol '%s':\\n stmfadm: filename /dev/zvol/rdsk/%s: in use\\n"; - - @Test - public void testCreateLu() { - final String luName = appliance.getVolumeName("volume1"); - final LuParams p = new LuParams(); - - appliance.createLu(luName); - verify(client).execute(NmsResponse.class, "scsidisk", "create_lu", luName, p); - - String error = String.format(CREATE_LU_IN_USE_ERROR, luName, luName); - when(client.execute(NmsResponse.class, "scsidisk", "create_lu", luName, p)).thenThrow(new CloudRuntimeException(error)); - appliance.createLu(luName); - } - - @Test - public void testCreateLuFails() { - final String luName = appliance.getVolumeName("volume1"); - when(client.execute(NmsResponse.class, "scsidisk", "create_lu", luName, new LuParams())).thenThrow(new CloudRuntimeException("any exception")); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - appliance.createLu(luName); - } - - final static String ZVOL_DOES_NOT_EXISTS_ERROR = "Zvol '%s' does not exist"; - - @Test - public void testIsLuShared() { - final String luName = appliance.getVolumeName("volume1"); - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenReturn(null); - assertFalse(appliance.isLuShared(luName)); - - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenReturn(new IntegerNmsResponse(0)); - assertFalse(appliance.isLuShared(luName)); - - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenReturn(new IntegerNmsResponse(1)); - assertTrue(appliance.isLuShared(luName)); - - final String error = String.format(ZVOL_DOES_NOT_EXISTS_ERROR, luName); - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenThrow(new CloudRuntimeException(error)); - assertFalse(appliance.isLuShared(luName)); - } - - @Test - public void testIsLuSharedFails() { - final String luName = appliance.getVolumeName("volume1"); - when(client.execute(IntegerNmsResponse.class, "scsidisk", "lu_shared", luName)).thenThrow(new CloudRuntimeException("any exception")); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - appliance.isLuShared(luName); - } - - final static String ADD_LUN_MAPPING_ENTRY_ERROR = "(rc: 256) Unable to " + - "add view to zvol '%s':\\n add-view: view already exists\\n"; - - @Test - public void testAddLuMappingEntry() { - final String luName = appliance.getVolumeName("volume1"); - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - final MappingEntry mappingEntry = new MappingEntry(targetGroupName, "0"); - appliance.addLuMappingEntry(luName, targetGroupName); - verify(client).execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry); - - String error = String.format(ADD_LUN_MAPPING_ENTRY_ERROR, luName); - when(client.execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry)).thenThrow(new CloudRuntimeException(error)); - appliance.addLuMappingEntry(luName, targetGroupName); - } - - @Test - public void testAddLuMappingEntryTest() { - final String luName = appliance.getVolumeName("volume1"); - final String targetGroupName = NexentaStorAppliance.getTargetGroupName("volume1"); - final MappingEntry mappingEntry = new MappingEntry(targetGroupName, "0"); - when(client.execute(AddMappingEntryNmsResponse.class, "scsidisk", "add_lun_mapping_entry", luName, mappingEntry)).thenThrow(new CloudRuntimeException("any exception")); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - appliance.addLuMappingEntry(luName, targetGroupName); - } - - @Test - public void testCreateIscsiVolume() { - final String volumeName = "volume1"; - final Long volumeSize = Long.valueOf(1); - appliance.createIscsiVolume(volumeName, volumeSize); - } - - @Test - public void testDeleteIscsiVolume() { - final String volumeName = appliance.getVolumeName("volume1"); - appliance.deleteIscsiVolume(volumeName); - verify(client).execute(NmsResponse.class, "zvol", "destroy", volumeName, ""); - - when(client.execute(NmsResponse.class, "zvol", "destroy", volumeName, "")).thenThrow(new CloudRuntimeException(String.format("Zvol '%s' does not exist", volumeName))); - appliance.deleteIscsiVolume(volumeName); - } - - @Test - public void testDeleteIscsiVolumeFails() { - final String volumeName = appliance.getVolumeName("volume1"); - exception.expect(CloudRuntimeException.class); - exception.expectMessage("any exception"); - when(client.execute(NmsResponse.class, "zvol", "destroy", volumeName, "")).thenThrow(new CloudRuntimeException("any exception")); - appliance.deleteIscsiVolume(volumeName); - } -} diff --git a/plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java b/plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java deleted file mode 100644 index 45bffb091077..000000000000 --- a/plugins/storage/volume/nexenta/src/test/java/org/apache/cloudstack/storage/datastore/util/NexentaUtilTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.util; - -import static junit.framework.Assert.assertNull; -import static org.junit.Assert.assertEquals; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import com.cloud.storage.Storage; - -@RunWith(JUnit4.class) -public class NexentaUtilTest { - @Rule - public ExpectedException exception = ExpectedException.none(); - - @Test - public void testParseNmsUrl() { - NexentaNmsUrl c; - - c = NexentaUtil.parseNmsUrl("auto://192.168.1.1/"); - assertEquals(c.toString(), "auto://admin:nexenta@192.168.1.1:2000/rest/nms/"); - assertEquals(c.getSchema(), "http"); - - c = NexentaUtil.parseNmsUrl("http://192.168.1.1/"); - assertEquals(c.toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); - - c = NexentaUtil.parseNmsUrl("http://192.168.1.1:8080"); - assertEquals(c.toString(), "http://admin:nexenta@192.168.1.1:8080/rest/nms/"); - - c = NexentaUtil.parseNmsUrl("https://root@192.168.1.1:8080"); - assertEquals(c.toString(), "https://root:nexenta@192.168.1.1:8080/rest/nms/"); - - c = NexentaUtil.parseNmsUrl("https://root:password@192.168.1.1:8080"); - assertEquals(c.toString(), "https://root:password@192.168.1.1:8080/rest/nms/"); - } - - @Test - public void testGetStorageType() { - assertEquals(NexentaUtil.getStorageType("iscsi"), Storage.StoragePoolType.Iscsi); - assertEquals(NexentaUtil.getStorageType("nfs"), Storage.StoragePoolType.NetworkFilesystem); - assertEquals(NexentaUtil.getStorageType("any"), Storage.StoragePoolType.Iscsi); - } - - @Test - public void testParseNexentaPluginUrl() { - String url = "nmsUrl=http://admin:nexenta@192.168.1.1:2000;"; - - NexentaUtil.NexentaPluginParameters parameters; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.getNmsUrl().toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); - assertNull(parameters.getVolume()); - assertEquals(parameters.getStorageType(), Storage.StoragePoolType.Iscsi); - assertEquals(parameters.getStorageHost(), "192.168.1.1"); - assertEquals((int) parameters.getStoragePort(), NexentaUtil.DEFAULT_ISCSI_TARGET_PORTAL_PORT); - assertNull(parameters.getStoragePath()); - assertEquals((boolean) parameters.isSparseVolumes(), false); - assertEquals(parameters.getVolumeBlockSize(), "8K"); - - url += "volume=cloudstack"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.getNmsUrl().toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); - assertEquals(parameters.getVolume(), "cloudstack"); - - url += "/;"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.getVolume(), "cloudstack"); - - url += "storageType="; - parameters = NexentaUtil.parseNexentaPluginUrl(url + "nfs"); - assertEquals(parameters.getStorageType(), Storage.StoragePoolType.NetworkFilesystem); - assertEquals((int) parameters.getStoragePort(), NexentaUtil.DEFAULT_NFS_PORT); - - parameters = NexentaUtil.parseNexentaPluginUrl(url + "iscsi"); - assertEquals(parameters.getStorageType(), Storage.StoragePoolType.Iscsi); - assertEquals((int) parameters.getStoragePort(), NexentaUtil.DEFAULT_ISCSI_TARGET_PORTAL_PORT); - - url += "nfs;storageHost=192.168.1.2;"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.getStorageHost(), "192.168.1.2"); - - url += "storagePort=3000;"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals((int) parameters.getStoragePort(), 3000); - - url += "storagePath=/volumes/cloudstack;"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.getStoragePath(), "/volumes/cloudstack"); - - url += "sparseVolumes=true;"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.isSparseVolumes(), Boolean.TRUE); - - url += "volumeBlockSize=128K;"; - parameters = NexentaUtil.parseNexentaPluginUrl(url); - assertEquals(parameters.getVolumeBlockSize(), "128K"); - - url += "unknownParameter=value;"; // NOTE: exception should not be raised - parameters = NexentaUtil.parseNexentaPluginUrl(url); - - assertEquals(parameters.getNmsUrl().toString(), "http://admin:nexenta@192.168.1.1:2000/rest/nms/"); - assertEquals(parameters.getVolume(), "cloudstack"); - assertEquals(parameters.getStorageType(), Storage.StoragePoolType.NetworkFilesystem); - assertEquals(parameters.getStorageHost(), "192.168.1.2"); - assertEquals((int) parameters.getStoragePort(), 3000); - assertEquals(parameters.getStoragePath(), "/volumes/cloudstack"); - assertEquals(parameters.isSparseVolumes(), Boolean.TRUE); - assertEquals(parameters.getVolumeBlockSize(), "128K"); - - exception.expect(RuntimeException.class); - exception.expectMessage("Invalid URL format"); - - NexentaUtil.parseNexentaPluginUrl(url + "invalidParameter"); - } -} diff --git a/plugins/storage/volume/solidfire/pom.xml b/plugins/storage/volume/solidfire/pom.xml deleted file mode 100644 index 65ba90b0c386..000000000000 --- a/plugins/storage/volume/solidfire/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - cloud-plugin-storage-volume-solidfire - Apache CloudStack Plugin - Storage Volume SolidFire Provider - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../../pom.xml - - - - com.solidfire - solidfire-sdk-java - 1.2.0.29 - - - org.apache.cloudstack - cloud-plugin-storage-volume-default - ${project.version} - - - org.apache.cloudstack - cloud-engine-storage-volume - ${project.version} - - - com.google.code.gson - gson - - - org.aspectj - aspectjtools - test - - - - - - maven-surefire-plugin - - true - - - - integration-test - - test - - - - - - - diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java deleted file mode 100644 index 1e927e20168e..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java +++ /dev/null @@ -1,1683 +0,0 @@ -// 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 org.apache.cloudstack.storage.datastore.driver; - -import java.text.NumberFormat; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.cloudstack.engine.subsystem.api.storage.ChapInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; -import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult; -import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreCapabilities; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; -import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; -import org.apache.cloudstack.framework.async.AsyncCompletionCallback; -import org.apache.cloudstack.storage.command.CommandResult; -import org.apache.cloudstack.storage.command.CreateObjectAnswer; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; -import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.to.DataObjectType; -import com.cloud.agent.api.to.DataStoreTO; -import com.cloud.agent.api.to.DataTO; -import com.cloud.agent.api.to.DiskTO; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.ResizeVolumePayload; -import com.cloud.storage.Snapshot.State; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StoragePool; -import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeDetailVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; -import com.cloud.storage.dao.VMTemplatePoolDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.storage.dao.VolumeDetailsDao; -import com.cloud.user.AccountDetailVO; -import com.cloud.user.AccountDetailsDao; -import com.cloud.user.AccountVO; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.Pair; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.dao.VMInstanceDao; -import com.cloud.vm.VirtualMachine; -import com.google.common.base.Preconditions; - -public class SolidFirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { - protected Logger logger = LogManager.getLogger(getClass()); - private static final int LOWEST_HYPERVISOR_SNAPSHOT_RESERVE = 10; - private static final long MIN_IOPS_FOR_TEMPLATE_VOLUME = 100L; - private static final long MAX_IOPS_FOR_TEMPLATE_VOLUME = 20000L; - private static final long MIN_IOPS_FOR_TEMP_VOLUME = 100L; - private static final long MAX_IOPS_FOR_TEMP_VOLUME = 20000L; - private static final long MAX_IOPS_FOR_MIGRATING_VOLUME = 20000L; - private static final long MIN_IOPS_FOR_SNAPSHOT_VOLUME = 100L; - private static final long MAX_IOPS_FOR_SNAPSHOT_VOLUME = 20000L; - - private static final String BASIC_SF_ID = "basicSfId"; - - @Inject private AccountDao accountDao; - @Inject private AccountDetailsDao accountDetailsDao; - @Inject private ClusterDao clusterDao; - @Inject private DataStoreManager dataStoreMgr; - @Inject private HostDao hostDao; - @Inject private SnapshotDao snapshotDao; - @Inject private SnapshotDetailsDao snapshotDetailsDao; - @Inject private SnapshotDataStoreDao snapshotDataStoreDao; - @Inject private PrimaryDataStoreDao storagePoolDao; - @Inject private StoragePoolDetailsDao storagePoolDetailsDao; - @Inject private VMTemplatePoolDao vmTemplatePoolDao; - @Inject private VMInstanceDao vmDao; - @Inject private VolumeDao volumeDao; - @Inject private VolumeDetailsDao volumeDetailsDao; - @Inject private VolumeDataFactory volumeFactory; - - @Override - public Map getCapabilities() { - Map mapCapabilities = new HashMap<>(); - - mapCapabilities.put(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString(), Boolean.TRUE.toString()); - mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_SNAPSHOT.toString(), Boolean.TRUE.toString()); - mapCapabilities.put(DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_VOLUME.toString(), Boolean.TRUE.toString()); - mapCapabilities.put(DataStoreCapabilities.CAN_REVERT_VOLUME_TO_SNAPSHOT.toString(), Boolean.TRUE.toString()); - - return mapCapabilities; - } - - @Override - public DataTO getTO(DataObject data) { - return null; - } - - @Override - public DataStoreTO getStoreTO(DataStore store) { - return null; - } - - private SolidFireUtil.SolidFireAccount createSolidFireAccount(SolidFireUtil.SolidFireConnection sfConnection, String sfAccountName) { - long accountNumber = SolidFireUtil.createAccount(sfConnection, sfAccountName); - - return SolidFireUtil.getAccountById(sfConnection, accountNumber); - } - - @Override - public ChapInfo getChapInfo(DataObject dataObject) { - return null; - } - - @Override - public boolean grantAccess(DataObject dataObject, Host host, DataStore dataStore) { - Preconditions.checkArgument(dataObject != null, "'dataObject' should not be 'null'"); - Preconditions.checkArgument(host != null, "'host' should not be 'null'"); - Preconditions.checkArgument(dataStore != null, "'dataStore' should not be 'null'"); - - long sfVolumeId = getSolidFireVolumeId(dataObject, true); - long clusterId = host.getClusterId(); - long storagePoolId = dataStore.getId(); - - ClusterVO cluster = clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(SolidFireUtil.LOCK_TIME_IN_SECONDS)) { - String errMsg = "Couldn't lock the DB (in grantAccess) on the following string: " + cluster.getUuid(); - - logger.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - try { - List hosts = hostDao.findByClusterId(clusterId); - - String clusterUuId = clusterDao.findById(clusterId).getUuid(); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - SolidFireUtil.placeVolumeInVolumeAccessGroups(sfConnection, sfVolumeId, hosts, clusterUuId); - - return true; - } - finally { - lock.unlock(); - lock.releaseRef(); - } - } - - private boolean isRevokeAccessNotNeeded(DataObject dataObject) { - // Workaround: don't unplug iscsi lun when volume is attached to a VM - // This is regression workaround from upper layers which are calling - // a releaseVmResources() method that calls the revoke on an attached disk - if (dataObject.getType() == DataObjectType.VOLUME) { - Volume volume = volumeDao.findById(dataObject.getId()); - if (volume.getInstanceId() != null) { - VirtualMachine vm = vmDao.findById(volume.getInstanceId()); - if (vm != null && !Arrays.asList(VirtualMachine.State.Destroyed, VirtualMachine.State.Expunging, VirtualMachine.State.Error).contains(vm.getState())) { - return true; - } - } - } - return false; - } - - @Override - public void revokeAccess(DataObject dataObject, Host host, DataStore dataStore) { - if (dataObject == null || host == null || dataStore == null) { - return; - } - - if (isRevokeAccessNotNeeded(dataObject)) { - logger.debug("Skipping revoke access for Solidfire data object type: {} id: {} uuid: {}", - dataObject.getType(), dataObject.getId(), dataObject.getUuid()); - return; - } - - long sfVolumeId = getSolidFireVolumeId(dataObject, false); - long clusterId = host.getClusterId(); - long storagePoolId = dataStore.getId(); - - ClusterVO cluster = clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(SolidFireUtil.LOCK_TIME_IN_SECONDS)) { - String errMsg = "Couldn't lock the DB (in revokeAccess) on the following string: " + cluster.getUuid(); - - logger.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - logger.debug("Revoking access for Solidfire data object type: {} id: {} uuid: {}", - dataObject.getType(), dataObject.getId(), dataObject.getUuid()); - - try { - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - List sfVags = SolidFireUtil.getAllVags(sfConnection); - - for (SolidFireUtil.SolidFireVag sfVag : sfVags) { - if (SolidFireUtil.sfVagContains(sfVag, sfVolumeId, clusterId, hostDao)) { - SolidFireUtil.removeVolumeIdsFromSolidFireVag(sfConnection, sfVag.getId(), new Long[] { sfVolumeId }); - } - } - } - finally { - lock.unlock(); - lock.releaseRef(); - } - } - - private long getSolidFireVolumeId(DataObject dataObject, boolean grantAccess) { - if (dataObject.getType() == DataObjectType.VOLUME) { - final VolumeInfo volumeInfo = (VolumeInfo)dataObject; - final long volumeId = volumeInfo.getId(); - - if (grantAccess && isBasicGrantAccess(volumeId)) { - volumeDetailsDao.removeDetail(volumeInfo.getId(), BASIC_GRANT_ACCESS); - - final Long sfVolumeId = getBasicSfVolumeId(volumeId); - - Preconditions.checkNotNull(sfVolumeId, "'sfVolumeId' should not be 'null' (basic grant access)."); - - return sfVolumeId; - } - else if (!grantAccess && isBasicRevokeAccess(volumeId)) { - volumeDetailsDao.removeDetail(volumeInfo.getId(), BASIC_REVOKE_ACCESS); - - final Long sfVolumeId = getBasicSfVolumeId(volumeId); - - Preconditions.checkNotNull(sfVolumeId, "'sfVolumeId' should not be 'null' (basic revoke access)."); - - return sfVolumeId; - } - - return Long.parseLong(volumeInfo.getFolder()); - } - - if (dataObject.getType() == DataObjectType.SNAPSHOT) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(dataObject.getId(), SolidFireUtil.VOLUME_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException("Unable to locate the volume ID associated with the following Snapshot ID: " + dataObject.getId()); - } - - return Long.parseLong(snapshotDetails.getValue()); - } - - if (dataObject.getType() == DataObjectType.TEMPLATE) { - return getVolumeIdFrom_iScsiPath(((TemplateInfo)dataObject).getInstallPath()); - } - - throw new CloudRuntimeException("Invalid DataObjectType (" + dataObject.getType() + ") passed to getSolidFireVolumeId(DataObject, boolean)"); - } - - private long getVolumeIdFrom_iScsiPath(String iScsiPath) { - String[] splits = iScsiPath.split("/"); - String iqn = splits[1]; - - String sequenceToSearchFor = "."; - int lastIndexOf = iqn.lastIndexOf(sequenceToSearchFor); - String volumeIdAsString = iqn.substring(lastIndexOf + sequenceToSearchFor.length()); - - return Long.parseLong(volumeIdAsString); - } - - private long getDefaultMinIops(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS); - - String clusterDefaultMinIops = storagePoolDetail.getValue(); - - return Long.parseLong(clusterDefaultMinIops); - } - - private long getDefaultMaxIops(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS); - - String clusterDefaultMaxIops = storagePoolDetail.getValue(); - - return Long.parseLong(clusterDefaultMaxIops); - } - - private long getDefaultBurstIops(long storagePoolId, long maxIops) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS); - - String clusterDefaultBurstIopsPercentOfMaxIops = storagePoolDetail.getValue(); - - float fClusterDefaultBurstIopsPercentOfMaxIops = Float.parseFloat(clusterDefaultBurstIopsPercentOfMaxIops); - - return Math.min((long)(maxIops * fClusterDefaultBurstIopsPercentOfMaxIops), SolidFireUtil.MAX_IOPS_PER_VOLUME); - } - - private SolidFireUtil.SolidFireVolume createSolidFireVolume(SolidFireUtil.SolidFireConnection sfConnection, - DataObject dataObject, long storagePoolId, long sfAccountId) { - final Long minIops; - final Long maxIops; - final Long volumeSize; - final String volumeName; - - final Map mapAttributes; - - if (dataObject.getType() == DataObjectType.VOLUME) { - VolumeInfo volumeInfo = (VolumeInfo)dataObject; - - minIops = volumeInfo.getMinIops(); - maxIops = volumeInfo.getMaxIops(); - volumeSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, storagePoolDao.findById(storagePoolId)); - volumeName = volumeInfo.getName(); - - mapAttributes = getVolumeAttributes(volumeInfo); - } else if (dataObject.getType() == DataObjectType.TEMPLATE) { - TemplateInfo templateInfo = (TemplateInfo)dataObject; - - minIops = MIN_IOPS_FOR_TEMPLATE_VOLUME; - maxIops = MAX_IOPS_FOR_TEMPLATE_VOLUME; - volumeSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, storagePoolDao.findById(storagePoolId)); - volumeName = templateInfo.getUniqueName(); - - mapAttributes = getTemplateAttributes(templateInfo); - } - else { - throw new CloudRuntimeException("Invalid type passed to createSolidFireVolume: " + dataObject.getType()); - } - - final Iops iops = getIops(minIops, maxIops, storagePoolId); - - long sfVolumeId = SolidFireUtil.createVolume(sfConnection, SolidFireUtil.getSolidFireVolumeName(volumeName), sfAccountId, - volumeSize, true, mapAttributes, iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); - - return SolidFireUtil.getVolume(sfConnection, sfVolumeId); - } - - private Iops getIops(Long minIops, Long maxIops, long storagePoolId) { - if (minIops == null || minIops <= 0 || maxIops == null || maxIops <= 0) { - long defaultMaxIops = getDefaultMaxIops(storagePoolId); - - return new Iops(getDefaultMinIops(storagePoolId), defaultMaxIops, getDefaultBurstIops(storagePoolId, defaultMaxIops)); - } - - return new Iops(minIops, maxIops, getDefaultBurstIops(storagePoolId, maxIops)); - } - - @Override - public long getUsedBytes(StoragePool storagePool) { - return getUsedBytes(storagePool, Long.MIN_VALUE); - } - - private long getUsedBytes(StoragePool storagePool, long volumeIdToIgnore) { - long usedSpace = 0; - - List lstVolumes = volumeDao.findByPoolIdAndState(storagePool.getId(), Volume.State.Ready); - - if (lstVolumes != null) { - for (VolumeVO volume : lstVolumes) { - if (volume.getId() == volumeIdToIgnore) { - continue; - } - - usedSpace += getVolumeSizeIncludingHypervisorSnapshotReserve(volume.getSize(),volume.getHypervisorSnapshotReserve()); - - } - } - - List snapshotDataStoreVOList = snapshotDataStoreDao.listByStoreIdAndState(storagePool.getId(), ObjectInDataStoreStateMachine.State.Ready); - - if (snapshotDataStoreVOList != null) { - for (SnapshotDataStoreVO snapshot : snapshotDataStoreVOList) { - - usedSpace += snapshot.getPhysicalSize(); - - } - } - - List vmTemplateStoragePoolVOList = vmTemplatePoolDao.listByPoolIdAndState(storagePool.getId(), ObjectInDataStoreStateMachine.State.Ready); - - if (vmTemplateStoragePoolVOList != null) { - for (VMTemplateStoragePoolVO template : vmTemplateStoragePoolVOList) { - usedSpace += template.getTemplateSize(); - } - } - - return usedSpace; - } - - @Override - public long getUsedIops(StoragePool storagePool) { - long usedIops = 0; - - List volumes = volumeDao.findNonDestroyedVolumesByPoolId(storagePool.getId(), null); - - if (volumes != null) { - for (VolumeVO volume : volumes) { - if (!Volume.State.Creating.equals(volume.getState())) { - usedIops += volume.getMinIops() != null ? volume.getMinIops() : 0; - } - } - } - - return usedIops; - } - - @Override - public long getDataObjectSizeIncludingHypervisorSnapshotReserve(DataObject dataObject, StoragePool pool) { - long volumeSize = 0; - - if (dataObject.getType() == DataObjectType.VOLUME) { - VolumeInfo volume = (VolumeInfo)dataObject; - - volumeSize = getVolumeSizeIncludingHypervisorSnapshotReserve(volume.getSize(), volume.getHypervisorSnapshotReserve()); - } else if (dataObject.getType() == DataObjectType.TEMPLATE) { - TemplateInfo templateInfo = (TemplateInfo)dataObject; - - // TemplateInfo sometimes has a size equal to null. - long templateSize = templateInfo.getSize() != null ? templateInfo.getSize() : 0; - - if (templateInfo.getHypervisorType() == Hypervisor.HypervisorType.KVM) { - volumeSize = templateSize; - } - else { - volumeSize = (long)(templateSize + templateSize * (LOWEST_HYPERVISOR_SNAPSHOT_RESERVE / 100f)); - } - } - - return Math.max(volumeSize, SolidFireUtil.MIN_VOLUME_SIZE); - } - - private long getVolumeSizeIncludingHypervisorSnapshotReserve(long volumeSize, Integer hypervisorSnapshotReserve) { - if (hypervisorSnapshotReserve != null) { - hypervisorSnapshotReserve = Math.max(hypervisorSnapshotReserve, LOWEST_HYPERVISOR_SNAPSHOT_RESERVE); - - volumeSize += volumeSize * (hypervisorSnapshotReserve / 100f); - } - - return Math.max(volumeSize, SolidFireUtil.MIN_VOLUME_SIZE); - } - - /** - * This method is only relevant when storagePool is being used with a compute cluster that supports UUID resigning. - */ - @Override - public long getBytesRequiredForTemplate(TemplateInfo templateInfo, StoragePool storagePool) { - List lstTemplatePoolRefs = vmTemplatePoolDao.listByPoolId(storagePool.getId()); - - if (lstTemplatePoolRefs != null) { - for (VMTemplateStoragePoolVO templatePoolRef : lstTemplatePoolRefs) { - if (templatePoolRef.getTemplateId() == templateInfo.getId()) { - // This indicates that we already have this template stored on this primary storage, so - // we do not require additional space. - return 0; - } - } - } - - // This indicates that we do not have a copy of this template on this primary storage, so - // we need to take it into consideration from a space standpoint (ex. when a new VM is spun - // up and wants to use this particular template for its root disk). - return getDataObjectSizeIncludingHypervisorSnapshotReserve(templateInfo, storagePool); - } - - private static class Iops { - private final long _minIops; - private final long _maxIops; - private final long _burstIops; - - Iops(long minIops, long maxIops, long burstIops) throws IllegalArgumentException { - if (minIops <= 0 || maxIops <= 0) { - throw new IllegalArgumentException("The 'Min IOPS' and 'Max IOPS' values must be greater than 0."); - } - - if (minIops > maxIops) { - throw new IllegalArgumentException("The 'Min IOPS' value cannot exceed the 'Max IOPS' value."); - } - - if (maxIops > burstIops) { - throw new IllegalArgumentException("The 'Max IOPS' value cannot exceed the 'Burst IOPS' value."); - } - - _minIops = minIops; - _maxIops = maxIops; - _burstIops = burstIops; - } - - long getMinIops() { - return _minIops; - } - - long getMaxIops() { - return _maxIops; - } - - long getBurstIops() { - return _burstIops; - } - } - - private void deleteSolidFireVolume(SolidFireUtil.SolidFireConnection sfConnection, VolumeInfo volumeInfo) - { - Long storagePoolId = volumeInfo.getPoolId(); - - if (storagePoolId == null) { - return; // this volume was never assigned to a storage pool, so no SAN volume should exist for it - } - - long sfVolumeId = Long.parseLong(volumeInfo.getFolder()); - - deleteSolidFireVolume(sfConnection, volumeInfo.getId(), sfVolumeId); - } - - @Override - public void createAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { - String iqn = null; - String errMsg = null; - - try { - if (dataObject.getType() == DataObjectType.VOLUME) { - iqn = createVolume((VolumeInfo)dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.SNAPSHOT) { - createTempVolume((SnapshotInfo)dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.TEMPLATE) { - iqn = createTemplateVolume((TemplateInfo)dataObject, dataStore.getId()); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to createAsync"; - - logger.error(errMsg); - } - } - catch (Exception ex) { - errMsg = ex.getMessage(); - - logger.error(errMsg); - - if (callback == null) { - throw ex; - } - } - - if (callback != null) { - // path = iqn - // size is pulled from DataObject instance, if errMsg is null - CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errMsg == null, errMsg)); - - result.setResult(errMsg); - - callback.complete(result); - } - else { - if (errMsg != null) { - throw new CloudRuntimeException(errMsg); - } - } - } - - private long getCreateSolidFireAccountId(SolidFireUtil.SolidFireConnection sfConnection, long csAccountId, long storagePoolId) { - AccountDetailVO accountDetail = SolidFireUtil.getAccountDetail(csAccountId, storagePoolId, accountDetailsDao); - - if (accountDetail == null || accountDetail.getValue() == null) { - AccountVO account = accountDao.findById(csAccountId); - String sfAccountName = SolidFireUtil.getSolidFireAccountName(account.getUuid(), account.getAccountId()); - SolidFireUtil.SolidFireAccount sfAccount = SolidFireUtil.getAccount(sfConnection, sfAccountName); - - if (sfAccount == null) { - sfAccount = createSolidFireAccount(sfConnection, sfAccountName); - } - - SolidFireUtil.updateCsDbWithSolidFireAccountInfo(account.getId(), sfAccount, storagePoolId, accountDetailsDao); - - accountDetail = SolidFireUtil.getAccountDetail(csAccountId, storagePoolId, accountDetailsDao); - } - - return Long.parseLong(accountDetail.getValue()); - } - - private void handleSnapshotDetails(long csSnapshotId, String name, String value) { - snapshotDetailsDao.removeDetail(csSnapshotId, name); - - SnapshotDetailsVO snapshotDetails = new SnapshotDetailsVO(csSnapshotId, name, value, false); - - snapshotDetailsDao.persist(snapshotDetails); - } - - private void addTempVolumeId(long csSnapshotId, String tempVolumeId) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.VOLUME_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException("'addTempVolumeId' should not be invoked unless " + SolidFireUtil.VOLUME_ID + " exists."); - } - - String originalVolumeId = snapshotDetails.getValue(); - - handleSnapshotDetails(csSnapshotId, SolidFireUtil.TEMP_VOLUME_ID, originalVolumeId); - handleSnapshotDetails(csSnapshotId, SolidFireUtil.VOLUME_ID, tempVolumeId); - } - - private void removeTempVolumeId(long csSnapshotId) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.TEMP_VOLUME_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException("'removeTempVolumeId' should not be invoked unless " + SolidFireUtil.TEMP_VOLUME_ID + " exists."); - } - - String originalVolumeId = snapshotDetails.getValue(); - - handleSnapshotDetails(csSnapshotId, SolidFireUtil.VOLUME_ID, originalVolumeId); - - snapshotDetailsDao.remove(snapshotDetails.getId()); - } - - private Long getBasicSfVolumeId(long volumeId) { - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volumeId, BASIC_SF_ID); - - if (volumeDetail != null && volumeDetail.getValue() != null) { - return new Long(volumeDetail.getValue()); - } - - return null; - } - - private String getBasicIqn(long volumeId) { - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volumeId, BASIC_IQN); - - if (volumeDetail != null && volumeDetail.getValue() != null) { - return volumeDetail.getValue(); - } - - return null; - } - - // If isBasicCreate returns true, this means the calling code simply wants us to create a SolidFire volume with specified - // characteristics. We do not update the cloud.volumes table with this info. - private boolean isBasicCreate(long volumeId) { - return getBooleanValueFromVolumeDetails(volumeId, BASIC_CREATE); - } - - private boolean isBasicDelete(long volumeId) { - return getBooleanValueFromVolumeDetails(volumeId, BASIC_DELETE); - } - - private boolean isBasicDeleteFailure(long volumeId) { - return getBooleanValueFromVolumeDetails(volumeId, BASIC_DELETE_FAILURE); - } - - private boolean isBasicDeleteByFolder(long volumeId) { - return getBooleanValueFromVolumeDetails(volumeId, PrimaryDataStoreDriver.BASIC_DELETE_BY_FOLDER); - } - - private boolean isBasicGrantAccess(long volumeId) { - return getBooleanValueFromVolumeDetails(volumeId, BASIC_GRANT_ACCESS); - } - - private boolean isBasicRevokeAccess(long volumeId) { - return getBooleanValueFromVolumeDetails(volumeId, BASIC_REVOKE_ACCESS); - } - - private boolean getBooleanValueFromVolumeDetails(long volumeId, String name) { - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volumeId, name); - - return volumeDetail != null && volumeDetail.getValue() != null && Boolean.parseBoolean(volumeDetail.getValue()); - } - - private long getCsIdForCloning(long volumeId, String cloneOf) { - VolumeDetailVO volumeDetail = volumeDetailsDao.findDetail(volumeId, cloneOf); - - if (volumeDetail != null && volumeDetail.getValue() != null) { - return new Long(volumeDetail.getValue()); - } - - return Long.MIN_VALUE; - } - - private boolean shouldTakeSnapshot(long snapshotId) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(snapshotId, "takeSnapshot"); - - return snapshotDetails != null && snapshotDetails.getValue() != null && Boolean.parseBoolean(snapshotDetails.getValue()); - } - - private SolidFireUtil.SolidFireVolume createClone(SolidFireUtil.SolidFireConnection sfConnection, long dataObjectId, VolumeInfo volumeInfo, long sfAccountId, - long storagePoolId, DataObjectType dataObjectType) { - String sfNewVolumeName = volumeInfo.getName(); - - long sfVolumeId = Long.MIN_VALUE; - long sfSnapshotId = Long.MIN_VALUE; - - if (dataObjectType == DataObjectType.SNAPSHOT) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(dataObjectId, SolidFireUtil.SNAPSHOT_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - sfSnapshotId = Long.parseLong(snapshotDetails.getValue()); - } - - snapshotDetails = snapshotDetailsDao.findDetail(dataObjectId, SolidFireUtil.VOLUME_ID); - - sfVolumeId = Long.parseLong(snapshotDetails.getValue()); - } else if (dataObjectType == DataObjectType.TEMPLATE) { - // get the cached template on this storage - VMTemplateStoragePoolVO templatePoolRef = vmTemplatePoolDao.findByPoolTemplate(storagePoolId, dataObjectId, null); - - if (templatePoolRef != null) { - sfVolumeId = Long.parseLong(templatePoolRef.getLocalDownloadPath()); - } - } - - if (sfVolumeId <= 0) { - throw new CloudRuntimeException("Unable to find SolidFire volume for the following data-object ID: " + dataObjectId + - " and data-object type: " + dataObjectType); - } - - final long newSfVolumeId = SolidFireUtil.createClone(sfConnection, sfVolumeId, sfSnapshotId, sfAccountId, - SolidFireUtil.getSolidFireVolumeName(sfNewVolumeName), getVolumeAttributes(volumeInfo)); - - final Iops iops = getIops(volumeInfo.getMinIops(), volumeInfo.getMaxIops(), storagePoolId); - - SolidFireUtil.modifyVolume(sfConnection, newSfVolumeId, null, null, iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); - - return SolidFireUtil.getVolume(sfConnection, newSfVolumeId); - } - - private Map getVolumeAttributes(VolumeInfo volumeInfo) { - Map mapAttributes = new HashMap<>(); - - mapAttributes.put(SolidFireUtil.CloudStackVolumeId, String.valueOf(volumeInfo.getId())); - mapAttributes.put(SolidFireUtil.CloudStackVolumeSize, NumberFormat.getInstance().format(volumeInfo.getSize())); - - return mapAttributes; - } - - private Map getSnapshotAttributes(SnapshotInfo snapshotInfo) { - Map mapAttributes = new HashMap<>(); - - mapAttributes.put(SolidFireUtil.CloudStackSnapshotId, String.valueOf(snapshotInfo.getId())); - mapAttributes.put(SolidFireUtil.CloudStackSnapshotSize, NumberFormat.getInstance().format(snapshotInfo.getSize())); - - return mapAttributes; - } - - private Map getTemplateAttributes(TemplateInfo templateInfo) { - Map mapAttributes = new HashMap<>(); - - mapAttributes.put(SolidFireUtil.CloudStackTemplateId, String.valueOf(templateInfo.getId())); - mapAttributes.put(SolidFireUtil.CloudStackTemplateSize, NumberFormat.getInstance().format(templateInfo.getSize())); - - return mapAttributes; - } - - private SolidFireUtil.SolidFireVolume createCloneFromSnapshot(SolidFireUtil.SolidFireConnection sfConnection, long csSnapshotId, long sfAccountId) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.VOLUME_ID); - - long sfVolumeId = Long.parseLong(snapshotDetails.getValue()); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.SNAPSHOT_ID); - - long sfSnapshotId = Long.parseLong(snapshotDetails.getValue()); - - SolidFireUtil.SolidFireSnapshot sfSnapshot = SolidFireUtil.getSnapshot(sfConnection, sfVolumeId, sfSnapshotId); - - long newSfVolumeId = SolidFireUtil.createClone(sfConnection, sfVolumeId, sfSnapshotId, sfAccountId, SolidFireUtil.getSolidFireVolumeName(sfSnapshot.getName()), null); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.STORAGE_POOL_ID); - - long storagePoolId = Long.parseLong(snapshotDetails.getValue()); - - final Iops iops = getIops(MIN_IOPS_FOR_TEMP_VOLUME, MAX_IOPS_FOR_TEMP_VOLUME, storagePoolId); - - SolidFireUtil.modifyVolume(sfConnection, newSfVolumeId, null, null, iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); - - return SolidFireUtil.getVolume(sfConnection, newSfVolumeId); - } - - private void updateVolumeDetails(long volumeId, long sfVolumeSize, String scsiNaaDeviceId) { - volumeDetailsDao.removeDetail(volumeId, SolidFireUtil.VOLUME_SIZE); - volumeDetailsDao.removeDetail(volumeId, DiskTO.SCSI_NAA_DEVICE_ID); - - VolumeDetailVO volumeDetailVo = new VolumeDetailVO(volumeId, SolidFireUtil.VOLUME_SIZE, String.valueOf(sfVolumeSize), false); - - volumeDetailsDao.persist(volumeDetailVo); - - volumeDetailVo = new VolumeDetailVO(volumeId, DiskTO.SCSI_NAA_DEVICE_ID, scsiNaaDeviceId, false); - - volumeDetailsDao.persist(volumeDetailVo); - } - - @Override - public void deleteAsync(DataStore dataStore, DataObject dataObject, AsyncCompletionCallback callback) { - String errMsg = null; - - try { - if (dataObject.getType() == DataObjectType.VOLUME) { - deleteVolume((VolumeInfo)dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.SNAPSHOT) { - deleteSnapshot((SnapshotInfo)dataObject, dataStore.getId()); - } else if (dataObject.getType() == DataObjectType.TEMPLATE) { - deleteTemplate((TemplateInfo)dataObject, dataStore.getId()); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to deleteAsync"; - } - } - catch (Exception ex) { - errMsg = ex.getMessage(); - - logger.error(errMsg); - } - - if (callback != null) { - CommandResult result = new CommandResult(); - - result.setResult(errMsg); - - callback.complete(result); - } - } - - @Override - public void copyAsync(DataObject srcData, DataObject destData, AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public void copyAsync(DataObject srcData, DataObject destData, Host destHost, AsyncCompletionCallback callback) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean canCopy(DataObject srcData, DataObject destData) { - return false; - } - - @Override - public void takeSnapshot(SnapshotInfo snapshotInfo, AsyncCompletionCallback callback) { - CreateCmdResult result; - - try { - VolumeInfo volumeInfo = snapshotInfo.getBaseVolume(); - VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); - - long sfVolumeId = Long.parseLong(volumeVO.getFolder()); - long storagePoolId = volumeVO.getPoolId(); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - SolidFireUtil.SolidFireVolume sfVolume = SolidFireUtil.getVolume(sfConnection, sfVolumeId); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - // getUsedBytes(StoragePool) will not include the bytes of the proposed new volume or snapshot because - // updateSnapshotDetails has not yet been called for this new volume or snapshot - long usedBytes = getUsedBytes(storagePool); - long sfVolumeSize = sfVolume.getTotalSize(); - - usedBytes += sfVolumeSize; - - // For creating a volume or a snapshot, we need to check to make sure a sufficient amount of space remains in the primary storage. - // For the purpose of "charging" these bytes against storage_pool.capacity_bytes, we take the full size of the SolidFire volume - // that is serving as the volume the snapshot is of (either a new SolidFire volume or a SolidFire snapshot). - if (usedBytes > capacityBytes) { - throw new CloudRuntimeException("Insufficient amount of space remains in this primary storage to take a Snapshot"); - } - - storagePool.setUsedBytes(usedBytes); - - SnapshotObjectTO snapshotObjectTo = (SnapshotObjectTO)snapshotInfo.getTO(); - - if (shouldTakeSnapshot(snapshotInfo.getId())) { - // We are supposed to take a SolidFire snapshot to serve as the back-end for our CloudStack volume snapshot. - - String sfNewSnapshotName = volumeInfo.getName() + "-" + snapshotInfo.getUuid(); - - int maxSnapshotNameLength = 64; - int trimRequired = sfNewSnapshotName.length() - maxSnapshotNameLength; - - if (trimRequired > 0) { - sfNewSnapshotName = StringUtils.left(volumeInfo.getName(), (volumeInfo.getName().length() - trimRequired)) + "-" + snapshotInfo.getUuid(); - } - - long sfNewSnapshotId = SolidFireUtil.createSnapshot(sfConnection, sfVolumeId, SolidFireUtil.getSolidFireVolumeName(sfNewSnapshotName), - getSnapshotAttributes(snapshotInfo)); - - updateSnapshotDetails(snapshotInfo.getId(), volumeInfo.getId(), sfVolumeId, sfNewSnapshotId, storagePoolId, sfVolumeSize); - - snapshotObjectTo.setPath("SfSnapshotId=" + sfNewSnapshotId); - } - else { - // We are supposed to create a new SolidFire volume to serve as the back-end for our CloudStack volume snapshot. - - String sfNewVolumeName = volumeInfo.getName() + "-" + snapshotInfo.getUuid(); - - final Iops iops = getIops(MIN_IOPS_FOR_SNAPSHOT_VOLUME, MAX_IOPS_FOR_SNAPSHOT_VOLUME, storagePoolId); - - long sfNewVolumeId = SolidFireUtil.createVolume(sfConnection, SolidFireUtil.getSolidFireVolumeName(sfNewVolumeName), sfVolume.getAccountId(), - sfVolumeSize, sfVolume.isEnable512e(), getSnapshotAttributes(snapshotInfo), iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); - - SolidFireUtil.SolidFireVolume sfNewVolume = SolidFireUtil.getVolume(sfConnection, sfNewVolumeId); - - updateSnapshotDetails(snapshotInfo.getId(), sfNewVolumeId, storagePoolId, sfVolumeSize, sfNewVolume.getIqn()); - - snapshotObjectTo.setPath("SfVolumeId=" + sfNewVolumeId); - } - - // Now that we have successfully created a volume or a snapshot, update the space usage in the cloud.storage_pool table - // (even though cloud.storage_pool.used_bytes is likely no longer in use). - storagePoolDao.update(storagePoolId, storagePool); - - CreateObjectAnswer createObjectAnswer = new CreateObjectAnswer(snapshotObjectTo); - - result = new CreateCmdResult(null, createObjectAnswer); - - result.setResult(null); - } - catch (Exception ex) { - logger.debug("{}Failed to take CloudStack Snapshot: {}", SolidFireUtil.LOGGER_PREFIX, snapshotInfo.getSnapshotVO(), ex); - - result = new CreateCmdResult(null, new CreateObjectAnswer(ex.toString())); - - result.setResult(ex.toString()); - } - - callback.complete(result); - } - - private void updateSnapshotDetails(long csSnapshotId, long csVolumeId, long sfVolumeId, long sfNewSnapshotId, long storagePoolId, long sfNewVolumeSize) { - SnapshotDetailsVO snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.ORIG_CS_VOLUME_ID, - String.valueOf(csVolumeId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.VOLUME_ID, - String.valueOf(sfVolumeId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.SNAPSHOT_ID, - String.valueOf(sfNewSnapshotId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.STORAGE_POOL_ID, - String.valueOf(storagePoolId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.VOLUME_SIZE, - String.valueOf(sfNewVolumeSize), - false); - - snapshotDetailsDao.persist(snapshotDetail); - } - - private void updateSnapshotDetails(long csSnapshotId, long sfNewVolumeId, long storagePoolId, long sfNewVolumeSize, String sfNewVolumeIqn) { - SnapshotDetailsVO snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.VOLUME_ID, - String.valueOf(sfNewVolumeId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.STORAGE_POOL_ID, - String.valueOf(storagePoolId), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - SolidFireUtil.VOLUME_SIZE, - String.valueOf(sfNewVolumeSize), - false); - - snapshotDetailsDao.persist(snapshotDetail); - - snapshotDetail = new SnapshotDetailsVO(csSnapshotId, - DiskTO.IQN, - sfNewVolumeIqn, - false); - - snapshotDetailsDao.persist(snapshotDetail); - } - - private void addBasicCreateInfoToVolumeDetails(long volumeId, SolidFireUtil.SolidFireVolume sfVolume) { - VolumeDetailVO volumeDetailVo = new VolumeDetailVO(volumeId, BASIC_SF_ID, String.valueOf(sfVolume.getId()), false); - - volumeDetailsDao.persist(volumeDetailVo); - - volumeDetailVo = new VolumeDetailVO(volumeId, BASIC_IQN, sfVolume.getIqn(), false); - - volumeDetailsDao.persist(volumeDetailVo); - } - - private String createVolume(VolumeInfo volumeInfo, long storagePoolId) { - boolean isBasicCreate = isBasicCreate(volumeInfo.getId()); - - if (!isBasicCreate) { - verifySufficientBytesForStoragePool(volumeInfo, storagePoolId); - verifySufficientIopsForStoragePool(volumeInfo.getMinIops() != null ? volumeInfo.getMinIops() : getDefaultMinIops(storagePoolId), storagePoolId); - } - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - long sfAccountId = getCreateSolidFireAccountId(sfConnection, volumeInfo.getAccountId(), storagePoolId); - - SolidFireUtil.SolidFireVolume sfVolume; - - if (isBasicCreate) { - sfVolume = createSolidFireVolume(sfConnection, volumeInfo, storagePoolId, sfAccountId); - - volumeDetailsDao.removeDetail(volumeInfo.getId(), BASIC_CREATE); - - addBasicCreateInfoToVolumeDetails(volumeInfo.getId(), sfVolume); - - return sfVolume.getIqn(); - } - - long csSnapshotId = getCsIdForCloning(volumeInfo.getId(), "cloneOfSnapshot"); - long csTemplateId = getCsIdForCloning(volumeInfo.getId(), "cloneOfTemplate"); - - if (csSnapshotId > 0) { - // We are supposed to create a clone of the underlying volume or snapshot that supports the CloudStack snapshot. - sfVolume = createClone(sfConnection, csSnapshotId, volumeInfo, sfAccountId, storagePoolId, DataObjectType.SNAPSHOT); - } else if (csTemplateId > 0) { - // Clone from template. - sfVolume = createClone(sfConnection, csTemplateId, volumeInfo, sfAccountId, storagePoolId, DataObjectType.TEMPLATE); - - long volumeSize = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, storagePoolDao.findById(storagePoolId)); - - if (volumeSize > sfVolume.getTotalSize()) { - // Expand the volume to include HSR. - SolidFireUtil.modifyVolume(sfConnection, sfVolume.getId(), volumeSize, getVolumeAttributes(volumeInfo), - sfVolume.getMinIops(), sfVolume.getMaxIops(), sfVolume.getBurstIops()); - - // Get the SolidFire volume from the SAN again because we just updated its size. - sfVolume = SolidFireUtil.getVolume(sfConnection, sfVolume.getId()); - } - } - else { - sfVolume = createSolidFireVolume(sfConnection, volumeInfo, storagePoolId, sfAccountId); - } - - String iqn = sfVolume.getIqn(); - - VolumeVO volume = volumeDao.findById(volumeInfo.getId()); - - volume.set_iScsiName(iqn); - volume.setFolder(String.valueOf(sfVolume.getId())); - volume.setPoolType(StoragePoolType.IscsiLUN); - volume.setPoolId(storagePoolId); - - volumeDao.update(volume.getId(), volume); - - updateVolumeDetails(volume.getId(), sfVolume.getTotalSize(), sfVolume.getScsiNaaDeviceId()); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - // getUsedBytes(StoragePool) will include the bytes of the newly created volume because - // updateVolumeDetails(long, long) has already been called for this volume - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - - return iqn; - } - - private void createTempVolume(SnapshotInfo snapshotInfo, long storagePoolId) { - long csSnapshotId = snapshotInfo.getId(); - - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.SNAPSHOT_ID); - - if (snapshotDetails == null || snapshotDetails.getValue() == null) { - throw new CloudRuntimeException("'createTempVolume(SnapshotInfo, long)' should not be invoked unless " + SolidFireUtil.SNAPSHOT_ID + " exists."); - } - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, "tempVolume"); - - if (snapshotDetails != null && snapshotDetails.getValue() != null && snapshotDetails.getValue().equalsIgnoreCase("create")) { - long sfAccountId = getCreateSolidFireAccountId(sfConnection, snapshotInfo.getAccountId(), storagePoolId); - - SolidFireUtil.SolidFireVolume sfVolume = createCloneFromSnapshot(sfConnection, csSnapshotId, sfAccountId); - - addTempVolumeId(csSnapshotId, String.valueOf(sfVolume.getId())); - - handleSnapshotDetails(csSnapshotId, DiskTO.IQN, sfVolume.getIqn()); - handleSnapshotDetails(csSnapshotId, DiskTO.SCSI_NAA_DEVICE_ID, sfVolume.getScsiNaaDeviceId()); - } - else if (snapshotDetails != null && snapshotDetails.getValue() != null && snapshotDetails.getValue().equalsIgnoreCase("delete")) { - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.VOLUME_ID); - - SolidFireUtil.deleteVolume(sfConnection, Long.parseLong(snapshotDetails.getValue())); - - removeTempVolumeId(csSnapshotId); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DiskTO.IQN); - - snapshotDetailsDao.remove(snapshotDetails.getId()); - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, DiskTO.SCSI_NAA_DEVICE_ID); - - snapshotDetailsDao.remove(snapshotDetails.getId()); - } - else { - throw new CloudRuntimeException("Invalid state in 'createTempVolume(SnapshotInfo, long)'"); - } - } - - private String createTemplateVolume(TemplateInfo templateInfo, long storagePoolId) { - verifySufficientBytesForStoragePool(templateInfo, storagePoolId); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - long sfAccountId = getCreateSolidFireAccountId(sfConnection, templateInfo.getAccountId(), storagePoolId); - - SolidFireUtil.SolidFireVolume sfVolume = createSolidFireVolume(sfConnection, templateInfo, storagePoolId, sfAccountId); - - String iqn = sfVolume.getIqn(); - - VMTemplateStoragePoolVO templatePoolRef = vmTemplatePoolDao.findByPoolTemplate(storagePoolId, templateInfo.getId(), null); - - templatePoolRef.setInstallPath(iqn); - templatePoolRef.setLocalDownloadPath(Long.toString(sfVolume.getId())); - templatePoolRef.setTemplateSize(sfVolume.getTotalSize()); - - vmTemplatePoolDao.update(templatePoolRef.getId(), templatePoolRef); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - // getUsedBytes(StoragePool) will include the bytes of the newly created template volume because - // _tmpltPoolDao.update(Long, VMTemplateStoragePoolVO) has already been invoked - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - - return iqn; - } - - private void performBasicDelete(SolidFireUtil.SolidFireConnection sfConnection, long volumeId) { - Long sfVolumeId = getBasicSfVolumeId(volumeId); - - Preconditions.checkNotNull(sfVolumeId, "'sfVolumeId' should not be 'null'."); - - String iqn = getBasicIqn(volumeId); - - Preconditions.checkNotNull(iqn, "'iqn' should not be 'null'."); - - VolumeVO volumeVO = volumeDao.findById(volumeId); - - deleteSolidFireVolume(sfConnection, volumeId, Long.parseLong(volumeVO.getFolder())); - - volumeVO.setFolder(String.valueOf(sfVolumeId)); - volumeVO.set_iScsiName(iqn); - - volumeDao.update(volumeId, volumeVO); - - volumeDetailsDao.removeDetail(volumeId, BASIC_SF_ID); - volumeDetailsDao.removeDetail(volumeId, BASIC_IQN); - volumeDetailsDao.removeDetail(volumeId, BASIC_DELETE); - } - - private void performBasicDeleteFailure(SolidFireUtil.SolidFireConnection sfConnection, long volumeId) { - Long sfVolumeId = getBasicSfVolumeId(volumeId); - - Preconditions.checkNotNull(sfVolumeId, "'sfVolumeId' should not be 'null'."); - - SolidFireUtil.deleteVolume(sfConnection, sfVolumeId); - - volumeDetailsDao.removeDetail(volumeId, BASIC_SF_ID); - volumeDetailsDao.removeDetail(volumeId, BASIC_IQN); - volumeDetailsDao.removeDetail(volumeId, BASIC_DELETE_FAILURE); - } - - private void performBasicDeleteByFolder(SolidFireUtil.SolidFireConnection sfConnection, long volumeId) { - VolumeVO volumeVO = volumeDao.findById(volumeId); - - Preconditions.checkNotNull(volumeVO, "'volumeVO' should not be 'null'."); - - String folder = volumeVO.getFolder(); - - Preconditions.checkNotNull(folder, "'folder' should not be 'null'."); - - long sfVolumeId = Long.parseLong(folder); - - SolidFireUtil.deleteVolume(sfConnection, sfVolumeId); - } - - private void deleteVolume(VolumeInfo volumeInfo, long storagePoolId) { - try { - long volumeId = volumeInfo.getId(); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - if (isBasicDeleteByFolder(volumeId)) { - performBasicDeleteByFolder(sfConnection, volumeId); - } - else if (isBasicDelete(volumeId)) { - performBasicDelete(sfConnection, volumeId); - } - else if (isBasicDeleteFailure(volumeId)) { - performBasicDeleteFailure(sfConnection, volumeId); - } - else { - deleteSolidFireVolume(sfConnection, volumeInfo); - - volumeDetailsDao.removeDetails(volumeId); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long usedBytes = getUsedBytes(storagePool, volumeId); - - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - } - } - catch (Exception ex) { - logger.debug("{}Failed to delete SolidFire volume. CloudStack volume {}", SolidFireUtil.LOGGER_PREFIX, volumeInfo.getVolume(), ex); - - throw ex; - } - } - - private void deleteSnapshot(SnapshotInfo snapshotInfo, long storagePoolId) { - long csSnapshotId = snapshotInfo.getId(); - - try { - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.SNAPSHOT_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - // A SolidFire snapshot is being used to support the CloudStack volume snapshot. - - long sfSnapshotId = Long.parseLong(snapshotDetails.getValue()); - - deleteSolidFireSnapshot(sfConnection, csSnapshotId, sfSnapshotId); - } - else { - // A SolidFire volume is being used to support the CloudStack volume snapshot. - - snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.VOLUME_ID); - - long sfVolumeId = Long.parseLong(snapshotDetails.getValue()); - - SolidFireUtil.deleteVolume(sfConnection, sfVolumeId); - } - - snapshotDetailsDao.removeDetails(csSnapshotId); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - // getUsedBytes(StoragePool) will not include the snapshot to delete because it has already been deleted by this point - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - } - catch (Exception ex) { - logger.debug("{}Issue in 'deleteSnapshot(SnapshotInfo, long)'. CloudStack Snapshot: {}", SolidFireUtil.LOGGER_PREFIX, snapshotInfo.getSnapshotVO(), ex); - - throw ex; - } - } - - private void deleteTemplate(TemplateInfo template, long storagePoolId) { - try { - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - long sfTemplateVolumeId = getVolumeIdFrom_iScsiPath(template.getInstallPath()); - - SolidFireUtil.deleteVolume(sfConnection, sfTemplateVolumeId); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - // getUsedBytes(StoragePool) will not include the template to delete because the "template_spool_ref" table has already been updated by this point - long usedBytes = getUsedBytes(storagePool); - - storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); - - storagePoolDao.update(storagePoolId, storagePool); - } - catch (Exception ex) { - logger.debug("{}Failed to delete SolidFire template volume. CloudStack template: {}", SolidFireUtil.LOGGER_PREFIX, template, ex); - - throw ex; - } - } - - @Override - public void revertSnapshot(SnapshotInfo snapshot, SnapshotInfo snapshot2, AsyncCompletionCallback callback) { - VolumeInfo volumeInfo = snapshot.getBaseVolume(); - - VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); - - if (volumeVO == null || volumeVO.getRemoved() != null) { - String errMsg = "The volume that the snapshot belongs to no longer exists."; - - CommandResult commandResult = new CommandResult(); - - commandResult.setResult(errMsg); - - callback.complete(commandResult); - - return; - } - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(volumeVO.getPoolId(), storagePoolDetailsDao); - - long sfVolumeId = Long.parseLong(volumeInfo.getFolder()); - - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(snapshot.getId(), SolidFireUtil.SNAPSHOT_ID); - - long sfSnapshotId = Long.parseLong(snapshotDetails.getValue()); - - SolidFireUtil.rollBackVolumeToSnapshot(sfConnection, sfVolumeId, sfSnapshotId); - - SolidFireUtil.SolidFireVolume sfVolume = SolidFireUtil.getVolume(sfConnection, sfVolumeId); - - updateVolumeDetails(volumeVO.getId(), sfVolume.getTotalSize(), sfVolume.getScsiNaaDeviceId()); - - CommandResult commandResult = new CommandResult(); - - callback.complete(commandResult); - } - - @Override - public void resize(DataObject dataObject, AsyncCompletionCallback callback) { - String iqn = null; - String errMsg = null; - - try { - if (dataObject.getType() == DataObjectType.VOLUME) { - VolumeInfo volumeInfo = (VolumeInfo)dataObject; - - iqn = volumeInfo.get_iScsiName(); - - long storagePoolId = volumeInfo.getPoolId(); - long sfVolumeId = Long.parseLong(volumeInfo.getFolder()); - - ResizeVolumePayload payload = (ResizeVolumePayload)volumeInfo.getpayload(); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - SolidFireUtil.SolidFireVolume sfVolume = SolidFireUtil.getVolume(sfConnection, sfVolumeId); - - long newMinIops = payload.newMinIops != null ? payload.newMinIops : sfVolume.getMinIops(); - - verifySufficientIopsForStoragePool(storagePoolId, sfVolume, newMinIops); - - long newSize = payload.newSize != null ? payload.newSize : volumeInfo.getSize(); - - verifySufficientBytesForStoragePool(storagePoolId, volumeInfo.getId(), newSize, payload.newHypervisorSnapshotReserve); - - long sfNewVolumeSize = sfVolume.getTotalSize(); - - Integer hsr = volumeInfo.getHypervisorSnapshotReserve(); - - if (payload.newSize != null || payload.newHypervisorSnapshotReserve != null) { - if (payload.newHypervisorSnapshotReserve != null) { - if (hsr != null) { - if (payload.newHypervisorSnapshotReserve > hsr) { - hsr = payload.newHypervisorSnapshotReserve; - } - } else { - hsr = payload.newHypervisorSnapshotReserve; - } - } - - sfNewVolumeSize = getVolumeSizeIncludingHypervisorSnapshotReserve(newSize, hsr); - } - - Map mapAttributes = new HashMap<>(); - - mapAttributes.put(SolidFireUtil.CloudStackVolumeId, String.valueOf(volumeInfo.getId())); - mapAttributes.put(SolidFireUtil.CloudStackVolumeSize, NumberFormat.getInstance().format(payload.newSize)); - - long newMaxIops = payload.newMaxIops != null ? payload.newMaxIops : sfVolume.getMaxIops(); - - SolidFireUtil.modifyVolume(sfConnection, sfVolumeId, sfNewVolumeSize, mapAttributes, - newMinIops, newMaxIops, getDefaultBurstIops(storagePoolId, newMaxIops)); - - VolumeVO volume = volumeDao.findById(volumeInfo.getId()); - - volume.setMinIops(newMinIops); - volume.setMaxIops(newMaxIops); - volume.setHypervisorSnapshotReserve(hsr); - - volumeDao.update(volume.getId(), volume); - - // SolidFireUtil.VOLUME_SIZE was introduced in 4.5. - updateVolumeDetails(volume.getId(), sfNewVolumeSize, sfVolume.getScsiNaaDeviceId()); - } else { - errMsg = "Invalid DataObjectType (" + dataObject.getType() + ") passed to resize"; - } - } - catch (Exception ex) { - errMsg = ex.getMessage(); - } - finally { - CreateCmdResult result = new CreateCmdResult(iqn, new Answer(null, errMsg == null, errMsg)); - - result.setResult(errMsg); - - callback.complete(result); - } - } - - @Override - public void handleQualityOfServiceForVolumeMigration(VolumeInfo volumeInfo, QualityOfServiceState qualityOfServiceState) { - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(volumeInfo.getPoolId(), storagePoolDetailsDao); - - Iops iops; - - if (QualityOfServiceState.MIGRATION.equals(qualityOfServiceState)) { - iops = getIops(volumeInfo.getMinIops(), MAX_IOPS_FOR_MIGRATING_VOLUME, volumeInfo.getPoolId()); - } else { - iops = getIops(volumeInfo.getMinIops(), volumeInfo.getMaxIops(), volumeInfo.getPoolId()); - } - - SolidFireUtil.modifyVolumeQoS(sfConnection, Long.parseLong(volumeInfo.getFolder()), iops.getMinIops(), iops.getMaxIops(), iops.getBurstIops()); - } - - private void verifySufficientBytesForStoragePool(long requestedBytes, long storagePoolId) { - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long capacityBytes = storagePool.getCapacityBytes(); - long usedBytes = getUsedBytes(storagePool); - - usedBytes += requestedBytes; - - if (usedBytes > capacityBytes) { - throw new CloudRuntimeException("Insufficient amount of space remains in this primary storage"); - } - } - - private void verifySufficientBytesForStoragePool(DataObject dataObject, long storagePoolId) { - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long requestedBytes = getDataObjectSizeIncludingHypervisorSnapshotReserve(dataObject, storagePool); - - verifySufficientBytesForStoragePool(requestedBytes, storagePoolId); - } - - private void verifySufficientBytesForStoragePool(long storagePoolId, long volumeId, long newSize, Integer newHypervisorSnapshotReserve) { - DataStore primaryDataStore = dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - VolumeInfo volumeInfo = volumeFactory.getVolume(volumeId, primaryDataStore); - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - long currentSizeWithHsr = getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, storagePool); - - newHypervisorSnapshotReserve = newHypervisorSnapshotReserve == null ? LOWEST_HYPERVISOR_SNAPSHOT_RESERVE : - Math.max(newHypervisorSnapshotReserve, LOWEST_HYPERVISOR_SNAPSHOT_RESERVE); - - long newSizeWithHsr = (long)(newSize + newSize * (newHypervisorSnapshotReserve / 100f)); - - if (newSizeWithHsr < currentSizeWithHsr) { - throw new CloudRuntimeException(String.format("Storage pool %s does not support shrinking a volume.", storagePool)); - } - - long availableBytes = storagePool.getCapacityBytes() - getUsedBytes(storagePool); - - if ((newSizeWithHsr - currentSizeWithHsr) > availableBytes) { - throw new CloudRuntimeException(String.format("Storage pool %s does not have enough space to expand the volume.", storagePool)); - } - } - - private void verifySufficientIopsForStoragePool(long requestedIops, long storagePoolId) { - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - long usedIops = getUsedIops(storagePool); - long capacityIops = storagePool.getCapacityIops(); - - if (usedIops + requestedIops > capacityIops) { - throw new CloudRuntimeException("Insufficient number of IOPS available in this storage pool"); - } - } - - private void verifySufficientIopsForStoragePool(long storagePoolId, SolidFireUtil.SolidFireVolume sfVolume, long newMinIops) { - long currentMinIops = sfVolume.getMinIops(); - long diffInMinIops = newMinIops - currentMinIops; - - // if the desire is for more IOPS - if (diffInMinIops > 0) { - verifySufficientIopsForStoragePool(diffInMinIops, storagePoolId); - } - } - - private void deleteSolidFireVolume(SolidFireUtil.SolidFireConnection sfConnection, long csVolumeId, long sfVolumeId) { - List lstSnapshots = getNonDestroyedSnapshots(csVolumeId); - - boolean deleteVolume = true; - - for (SnapshotVO snapshot : lstSnapshots) { - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(snapshot.getId(), SolidFireUtil.SNAPSHOT_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - deleteVolume = false; - - break; - } - } - - if (deleteVolume) { - SolidFireUtil.deleteVolume(sfConnection, sfVolumeId); - } - } - - private void deleteSolidFireSnapshot(SolidFireUtil.SolidFireConnection sfConnection, long csSnapshotId, long sfSnapshotId) { - SolidFireUtil.deleteSnapshot(sfConnection, sfSnapshotId); - - final long volumeId; - final VolumeVO volume; - - SnapshotVO snapshot = snapshotDao.findById(csSnapshotId); - SnapshotDetailsVO snapshotDetails = snapshotDetailsDao.findDetail(csSnapshotId, SolidFireUtil.ORIG_CS_VOLUME_ID); - - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - volumeId = Long.valueOf(snapshotDetails.getValue()); - } - else { - volumeId = snapshot.getVolumeId(); - } - - volume = volumeDao.findById(volumeId); - - if (volume == null) { // if the CloudStack volume has been deleted - List lstSnapshots = getNonDestroyedSnapshots(snapshot.getVolumeId()); - - List lstSnapshots2 = new ArrayList<>(); - - for (SnapshotVO snapshotVo : lstSnapshots) { - // The CloudStack volume snapshot has not yet been set to the DESTROYED state, so check to make - // sure snapshotVo.getId() != csSnapshotId when determining if any volume snapshots remain for the given CloudStack volume. - if (snapshotVo.getId() != csSnapshotId) { - snapshotDetails = snapshotDetailsDao.findDetail(snapshotVo.getId(), SolidFireUtil.SNAPSHOT_ID); - - // We are only interested here in volume snapshots that make use of SolidFire snapshots (as opposed to ones - // that make use of SolidFire volumes). - if (snapshotDetails != null && snapshotDetails.getValue() != null) { - lstSnapshots2.add(snapshotVo); - } - } - } - - if (lstSnapshots2.isEmpty()) { - VolumeVO volumeToDelete = volumeDao.findByIdIncludingRemoved(volumeId); - - SolidFireUtil.deleteVolume(sfConnection, Long.parseLong(volumeToDelete.getFolder())); - } - } - } - - private List getNonDestroyedSnapshots(long csVolumeId) { - List lstSnapshots = snapshotDao.listByVolumeId(csVolumeId); - - if (lstSnapshots == null) { - lstSnapshots = new ArrayList<>(); - } - - List lstSnapshots2 = new ArrayList<>(); - - for (SnapshotVO snapshot : lstSnapshots) { - if (!State.Destroyed.equals(snapshot.getState())) { - lstSnapshots2.add(snapshot); - } - } - - return lstSnapshots2; - } - - @Override - public boolean canProvideStorageStats() { - return false; - } - - @Override - public Pair getStorageStats(StoragePool storagePool) { - return null; - } - - @Override - public boolean canProvideVolumeStats() { - return false; - } - - @Override - public Pair getVolumeStats(StoragePool storagePool, String volumeId) { - return null; - } - - @Override - public boolean canHostAccessStoragePool(Host host, StoragePool pool) { - return true; - } - - @Override - public boolean isVmInfoNeeded() { - return false; - } - - @Override - public void provideVmInfo(long vmId, long volumeId) { - } - - @Override - public boolean isVmTagsNeeded(String tagKey) { - return false; - } - - @Override - public void provideVmTags(long vmId, long volumeId, String tagValue) { - } - - @Override - public boolean isStorageSupportHA(StoragePoolType type) { - return false; - } - - @Override - public void detachVolumeFromAllStorageNodes(Volume volume) { - } - - @Override - public boolean volumesRequireGrantAccessWhenUsed() { - return true; - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFireSharedPrimaryDataStoreDriver.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFireSharedPrimaryDataStoreDriver.java deleted file mode 100644 index 365533c450e8..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFireSharedPrimaryDataStoreDriver.java +++ /dev/null @@ -1,20 +0,0 @@ -// 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 org.apache.cloudstack.storage.datastore.driver; - -public class SolidFireSharedPrimaryDataStoreDriver extends CloudStackPrimaryDataStoreDriverImpl { -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java deleted file mode 100644 index a16f294917e3..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java +++ /dev/null @@ -1,395 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.lifecycle; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.inject.Inject; - -import com.cloud.storage.dao.StoragePoolAndAccessGroupMapDao; -import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; -import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; - -import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.capacity.CapacityManager; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.dao.SnapshotDao; -import com.cloud.storage.dao.SnapshotDetailsDao; -import com.cloud.storage.dao.SnapshotDetailsVO; -import com.cloud.storage.dao.VMTemplatePoolDao; -import com.cloud.storage.SnapshotVO; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePoolAutomation; -import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.utils.exception.CloudRuntimeException; - -import com.google.common.base.Preconditions; - -public class SolidFirePrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { - @Inject private CapacityManager _capacityMgr; - @Inject private ClusterDao _clusterDao; - @Inject private DataCenterDao _zoneDao; - @Inject private PrimaryDataStoreDao _storagePoolDao; - @Inject private PrimaryDataStoreHelper _dataStoreHelper; - @Inject private ResourceManager _resourceMgr; - @Inject private SnapshotDao _snapshotDao; - @Inject private SnapshotDetailsDao _snapshotDetailsDao; - @Inject private StorageManager _storageMgr; - @Inject private StoragePoolAutomation _storagePoolAutomation; - @Inject private StoragePoolDetailsDao _storagePoolDetailsDao; - @Inject private VMTemplatePoolDao _tmpltPoolDao; - @Inject - private StoragePoolAndAccessGroupMapDao storagePoolAndAccessGroupMapDao; - - // invoked to add primary storage that is based on the SolidFire plug-in - @Override - public DataStore initialize(Map dsInfos) { - String url = (String)dsInfos.get("url"); - Long zoneId = (Long)dsInfos.get("zoneId"); - Long podId = (Long)dsInfos.get("podId"); - Long clusterId = (Long)dsInfos.get("clusterId"); - String storagePoolName = (String)dsInfos.get("name"); - String providerName = (String)dsInfos.get("providerName"); - Long capacityBytes = (Long)dsInfos.get("capacityBytes"); - Long capacityIops = (Long)dsInfos.get("capacityIops"); - String tags = (String)dsInfos.get("tags"); - Boolean isTagARule = (Boolean) dsInfos.get("isTagARule"); - @SuppressWarnings("unchecked") - Map details = (Map)dsInfos.get("details"); - - if (podId != null && clusterId == null) { - throw new CloudRuntimeException("If the Pod ID is specified, the Cluster ID must also be specified."); - } - - if (podId == null && clusterId != null) { - throw new CloudRuntimeException("If the Pod ID is not specified, the Cluster ID must also not be specified."); - } - - String storageVip = SolidFireUtil.getStorageVip(url); - int storagePort = SolidFireUtil.getStoragePort(url); - - if (capacityBytes == null || capacityBytes <= 0) { - throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0."); - } - - if (capacityIops == null || capacityIops <= 0) { - throw new IllegalArgumentException("'capacityIops' must be present and greater than 0."); - } - - PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); - - parameters.setHost(storageVip); - parameters.setPort(storagePort); - parameters.setPath(SolidFireUtil.getModifiedUrl(url)); - parameters.setType(StoragePoolType.Iscsi); - parameters.setUuid(UUID.randomUUID().toString()); - parameters.setZoneId(zoneId); - parameters.setPodId(podId); - parameters.setClusterId(clusterId); - parameters.setName(storagePoolName); - parameters.setProviderName(providerName); - parameters.setManaged(true); - parameters.setCapacityBytes(capacityBytes); - parameters.setUsedBytes(0); - parameters.setCapacityIops(capacityIops); - - if (clusterId != null) { - ClusterVO clusterVO = _clusterDao.findById(clusterId); - - Preconditions.checkNotNull(clusterVO, "Unable to locate the specified cluster"); - - parameters.setHypervisorType(clusterVO.getHypervisorType()); - } - else { - parameters.setHypervisorType(HypervisorType.Any); - } - - parameters.setTags(tags); - parameters.setIsTagARule(isTagARule); - parameters.setDetails(details); - - String managementVip = SolidFireUtil.getManagementVip(url); - int managementPort = SolidFireUtil.getManagementPort(url); - - details.put(SolidFireUtil.MANAGEMENT_VIP, managementVip); - details.put(SolidFireUtil.MANAGEMENT_PORT, String.valueOf(managementPort)); - - String clusterAdminUsername = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_ADMIN_USERNAME, url); - String clusterAdminPassword = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_ADMIN_PASSWORD, url); - - details.put(SolidFireUtil.CLUSTER_ADMIN_USERNAME, clusterAdminUsername); - details.put(SolidFireUtil.CLUSTER_ADMIN_PASSWORD, clusterAdminPassword); - - long lClusterDefaultMinIops = 100; - long lClusterDefaultMaxIops = 15000; - float fClusterDefaultBurstIopsPercentOfMaxIops = 1.5f; - - try { - String clusterDefaultMinIops = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS, url); - - if (clusterDefaultMinIops != null && clusterDefaultMinIops.trim().length() > 0) { - lClusterDefaultMinIops = Long.parseLong(clusterDefaultMinIops); - } - } catch (NumberFormatException ex) { - logger.warn("Cannot parse the setting " + SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS + - ", using default value: " + lClusterDefaultMinIops + - ". Exception: " + ex); - } - - try { - String clusterDefaultMaxIops = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS, url); - - if (clusterDefaultMaxIops != null && clusterDefaultMaxIops.trim().length() > 0) { - lClusterDefaultMaxIops = Long.parseLong(clusterDefaultMaxIops); - } - } catch (NumberFormatException ex) { - logger.warn("Cannot parse the setting " + SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS + - ", using default value: " + lClusterDefaultMaxIops + - ". Exception: " + ex); - } - - try { - String clusterDefaultBurstIopsPercentOfMaxIops = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS, url); - - if (clusterDefaultBurstIopsPercentOfMaxIops != null && clusterDefaultBurstIopsPercentOfMaxIops.trim().length() > 0) { - fClusterDefaultBurstIopsPercentOfMaxIops = Float.parseFloat(clusterDefaultBurstIopsPercentOfMaxIops); - } - } catch (NumberFormatException ex) { - logger.warn("Cannot parse the setting " + SolidFireUtil.CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS + - ", using default value: " + fClusterDefaultBurstIopsPercentOfMaxIops + - ". Exception: " + ex); - } - - if (lClusterDefaultMinIops < SolidFireUtil.MIN_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS + "' must be greater than or equal to " + - SolidFireUtil.MIN_IOPS_PER_VOLUME + "."); - } - - if (lClusterDefaultMinIops > SolidFireUtil.MAX_MIN_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS + "' must be less than or equal to " + - SolidFireUtil.MAX_MIN_IOPS_PER_VOLUME + "."); - } - - if (lClusterDefaultMinIops > lClusterDefaultMaxIops) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS + "' must be less than or equal to the parameter '" + - SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS + "'."); - } - - if (lClusterDefaultMaxIops > SolidFireUtil.MAX_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS + "' must be less than or equal to " + - SolidFireUtil.MAX_IOPS_PER_VOLUME + "."); - } - - if (Float.compare(fClusterDefaultBurstIopsPercentOfMaxIops, 1.0f) < 0) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS + "' must be greater than or equal to 1."); - } - - details.put(SolidFireUtil.CLUSTER_DEFAULT_MIN_IOPS, String.valueOf(lClusterDefaultMinIops)); - details.put(SolidFireUtil.CLUSTER_DEFAULT_MAX_IOPS, String.valueOf(lClusterDefaultMaxIops)); - details.put(SolidFireUtil.CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS, String.valueOf(fClusterDefaultBurstIopsPercentOfMaxIops)); - - // this adds a row in the cloud.storage_pool table for this SolidFire cluster - return _dataStoreHelper.createPrimaryDataStore(parameters); - } - - // do not implement this method for SolidFire's plug-in - @Override - public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { - return true; - } - - @Override - public boolean attachCluster(DataStore dataStore, ClusterScope scope) { - PrimaryDataStoreInfo primarystore = (PrimaryDataStoreInfo)dataStore; - List hostsToConnect = _resourceMgr.getEligibleUpAndEnabledHostsInClusterForStorageConnection(primarystore); - - logger.debug(String.format("Attaching the pool to each of the hosts %s in the cluster: %s", hostsToConnect, primarystore.getClusterId())); - for (HostVO host : hostsToConnect) { - try { - _storageMgr.connectHostToSharedPool(host, dataStore.getId()); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); - } - } - - _dataStoreHelper.attachCluster(dataStore); - - return true; - } - - @Override - public boolean attachZone(DataStore dataStore, ZoneScope scope, HypervisorType hypervisorType) { - List hostsToConnect = new ArrayList<>(); - HypervisorType[] hypervisorTypes = {HypervisorType.XenServer, HypervisorType.VMware, HypervisorType.KVM}; - - for (HypervisorType type : hypervisorTypes) { - hostsToConnect.addAll(_resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, scope.getScopeId(), type)); - } - - logger.debug(String.format("In createPool. Attaching the pool to each of the hosts in %s.", hostsToConnect)); - for (HostVO host : hostsToConnect) { - try { - _storageMgr.connectHostToSharedPool(host, dataStore.getId()); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + dataStore, e); - } - } - - _dataStoreHelper.attachZone(dataStore); - - return true; - } - - @Override - public boolean maintain(DataStore dataStore) { - _storagePoolAutomation.maintain(dataStore); - _dataStoreHelper.maintain(dataStore); - - return true; - } - - @Override - public boolean cancelMaintain(DataStore store) { - _dataStoreHelper.cancelMaintain(store); - _storagePoolAutomation.cancelMaintain(store); - - return true; - } - - // invoked to delete primary storage that is based on the SolidFire plug-in - @Override - public boolean deleteDataStore(DataStore dataStore) { - long storagePoolId = dataStore.getId(); - - List lstSnapshots = _snapshotDao.listAll(); - - if (lstSnapshots != null) { - for (SnapshotVO snapshot : lstSnapshots) { - SnapshotDetailsVO snapshotDetails = _snapshotDetailsDao.findDetail(snapshot.getId(), SolidFireUtil.STORAGE_POOL_ID); - - // if this snapshot belongs to the storagePool that was passed in - if (snapshotDetails != null && snapshotDetails.getValue() != null && Long.parseLong(snapshotDetails.getValue()) == storagePoolId) { - throw new CloudRuntimeException("This primary storage cannot be deleted because it currently contains one or more Snapshots."); - } - } - } - - List lstTemplatePoolRefs = _tmpltPoolDao.listByPoolId(storagePoolId); - - if (lstTemplatePoolRefs != null) { - for (VMTemplateStoragePoolVO templatePoolRef : lstTemplatePoolRefs) { - try { - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, _storagePoolDetailsDao); - long sfTemplateVolumeId = Long.parseLong(templatePoolRef.getLocalDownloadPath()); - - SolidFireUtil.deleteVolume(sfConnection, sfTemplateVolumeId); - } - catch (Exception ex) { - logger.error(ex.getMessage() != null ? ex.getMessage() : "Error deleting SolidFire Template volume"); - } - - _tmpltPoolDao.remove(templatePoolRef.getId()); - } - } - - StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolId); - - storagePool.setUsedBytes(0); - - _storagePoolDao.update(storagePoolId, storagePool); - - _storagePoolDetailsDao.removeDetails(storagePoolId); - - return _dataStoreHelper.deletePrimaryDataStore(dataStore); - } - - /* (non-Javadoc) - * @see org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle#migrateToObjectStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) - */ - @Override - public boolean migrateToObjectStore(DataStore store) { - return false; - } - - @Override - public void updateStoragePool(StoragePool storagePool, Map details) { - StoragePoolVO storagePoolVo = _storagePoolDao.findById(storagePool.getId()); - - String strCapacityBytes = details.get(PrimaryDataStoreLifeCycle.CAPACITY_BYTES); - Long capacityBytes = strCapacityBytes != null ? Long.parseLong(strCapacityBytes) : null; - - if (capacityBytes != null) { - long usedBytes = _capacityMgr.getUsedBytes(storagePoolVo); - - if (capacityBytes < usedBytes) { - throw new CloudRuntimeException("Cannot reduce the number of bytes for this storage pool as it would lead to an insufficient number of bytes"); - } - } - - String strCapacityIops = details.get(PrimaryDataStoreLifeCycle.CAPACITY_IOPS); - Long capacityIops = strCapacityIops != null ? Long.parseLong(strCapacityIops) : null; - - if (capacityIops != null) { - long usedIops = _capacityMgr.getUsedIops(storagePoolVo); - - if (capacityIops < usedIops) { - throw new CloudRuntimeException("Cannot reduce the number of IOPS for this storage pool as it would lead to an insufficient number of IOPS"); - } - } - } - - @Override - public void enableStoragePool(DataStore dataStore) { - _dataStoreHelper.enable(dataStore); - } - - @Override - public void disableStoragePool(DataStore dataStore) { - _dataStoreHelper.disable(dataStore); - } - - @Override - public void changeStoragePoolScopeToZone(DataStore store, ClusterScope clusterScope, HypervisorType hypervisorType) { - /* - * We need to attach all VMware, Xenserver and KVM hosts in the zone. - * So pass hypervisorType as null. - */ - super.changeStoragePoolScopeToZone(store, clusterScope, null); - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java deleted file mode 100644 index b05046cf4969..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java +++ /dev/null @@ -1,763 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.lifecycle; - -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import com.cloud.host.Host; -import com.cloud.storage.dao.StoragePoolAndAccessGroupMapDao; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; -import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters; -import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; -import org.apache.cloudstack.storage.volume.datastore.PrimaryDataStoreHelper; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.CreateStoragePoolCommand; -import com.cloud.agent.api.DeleteStoragePoolCommand; -import com.cloud.agent.api.ModifyTargetsCommand; -import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.resource.ResourceManager; -import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.StorageManager; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolAutomation; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.VMTemplateStoragePoolVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.template.TemplateManager; -import com.cloud.user.Account; -import com.cloud.user.AccountDetailsDao; -import com.cloud.user.AccountVO; -import com.cloud.user.dao.AccountDao; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; - -public class SolidFireSharedPrimaryDataStoreLifeCycle extends BasePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLifeCycle { - @Inject private AccountDao accountDao; - @Inject private AccountDetailsDao accountDetailsDao; - @Inject private AgentManager agentMgr; - @Inject private ClusterDao clusterDao; - @Inject private DataCenterDao zoneDao; - @Inject private HostDao hostDao; - @Inject private PrimaryDataStoreDao primaryDataStoreDao; - @Inject private PrimaryDataStoreHelper primaryDataStoreHelper; - @Inject private ResourceManager resourceMgr; - @Inject private StorageManager storageMgr; - @Inject private StoragePoolAutomation storagePoolAutomation; - @Inject private StoragePoolDetailsDao storagePoolDetailsDao; - @Inject private StoragePoolHostDao storagePoolHostDao; - @Inject private TemplateManager tmpltMgr; - @Inject - private StoragePoolAndAccessGroupMapDao storagePoolAndAccessGroupMapDao; - - // invoked to add primary storage that is based on the SolidFire plug-in - @Override - public DataStore initialize(Map dsInfos) { - final String CAPACITY_IOPS = "capacityIops"; - - String url = (String)dsInfos.get("url"); - Long zoneId = (Long)dsInfos.get("zoneId"); - Long podId = (Long)dsInfos.get("podId"); - Long clusterId = (Long)dsInfos.get("clusterId"); - String storagePoolName = (String)dsInfos.get("name"); - String providerName = (String)dsInfos.get("providerName"); - Long capacityBytes = (Long)dsInfos.get("capacityBytes"); - Long capacityIops = (Long)dsInfos.get(CAPACITY_IOPS); - String tags = (String)dsInfos.get("tags"); - Boolean isTagARule = (Boolean) dsInfos.get("isTagARule"); - @SuppressWarnings("unchecked") - Map details = (Map)dsInfos.get("details"); - - if (podId == null) { - throw new CloudRuntimeException("The Pod ID must be specified."); - } - - if (clusterId == null) { - throw new CloudRuntimeException("The Cluster ID must be specified."); - } - - String storageVip = SolidFireUtil.getStorageVip(url); - int storagePort = SolidFireUtil.getStoragePort(url); - - if (capacityBytes == null || capacityBytes <= 0) { - throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0."); - } - - if (capacityIops == null || capacityIops <= 0) { - throw new IllegalArgumentException("'capacityIops' must be present and greater than 0."); - } - - HypervisorType hypervisorType = getHypervisorTypeForCluster(clusterId); - - if (!isSupportedHypervisorType(hypervisorType)) { - throw new CloudRuntimeException(hypervisorType + " is not a supported hypervisor type."); - } - - String datacenter = SolidFireUtil.getValue(SolidFireUtil.DATACENTER, url, false); - - if (HypervisorType.VMware.equals(hypervisorType) && datacenter == null) { - throw new CloudRuntimeException("'Datacenter' must be set for hypervisor type of " + HypervisorType.VMware); - } - - PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters(); - - parameters.setType(getStorageType(hypervisorType)); - parameters.setZoneId(zoneId); - parameters.setPodId(podId); - parameters.setClusterId(clusterId); - parameters.setName(storagePoolName); - parameters.setProviderName(providerName); - parameters.setManaged(false); - parameters.setCapacityBytes(capacityBytes); - parameters.setUsedBytes(0); - parameters.setCapacityIops(capacityIops); - parameters.setHypervisorType(hypervisorType); - parameters.setTags(tags); - parameters.setIsTagARule(isTagARule); - parameters.setDetails(details); - - String managementVip = SolidFireUtil.getManagementVip(url); - int managementPort = SolidFireUtil.getManagementPort(url); - - details.put(SolidFireUtil.MANAGEMENT_VIP, managementVip); - details.put(SolidFireUtil.MANAGEMENT_PORT, String.valueOf(managementPort)); - - String clusterAdminUsername = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_ADMIN_USERNAME, url); - String clusterAdminPassword = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_ADMIN_PASSWORD, url); - - details.put(SolidFireUtil.CLUSTER_ADMIN_USERNAME, clusterAdminUsername); - details.put(SolidFireUtil.CLUSTER_ADMIN_PASSWORD, clusterAdminPassword); - - if (capacityBytes < SolidFireUtil.MIN_VOLUME_SIZE) { - capacityBytes = SolidFireUtil.MIN_VOLUME_SIZE; - } - - long lMinIops = 100; - long lMaxIops = 15000; - long lBurstIops = 15000; - - try { - String minIops = SolidFireUtil.getValue(SolidFireUtil.MIN_IOPS, url); - - if (minIops != null && minIops.trim().length() > 0) { - lMinIops = Long.parseLong(minIops); - } - } catch (Exception ex) { - logger.info("[ignored] error getting Min IOPS: " + ex.getLocalizedMessage()); - } - - try { - String maxIops = SolidFireUtil.getValue(SolidFireUtil.MAX_IOPS, url); - - if (maxIops != null && maxIops.trim().length() > 0) { - lMaxIops = Long.parseLong(maxIops); - } - } catch (Exception ex) { - logger.info("[ignored] error getting Max IOPS: " + ex.getLocalizedMessage()); - } - - try { - String burstIops = SolidFireUtil.getValue(SolidFireUtil.BURST_IOPS, url); - - if (burstIops != null && burstIops.trim().length() > 0) { - lBurstIops = Long.parseLong(burstIops); - } - } catch (Exception ex) { - logger.info("[ignored] error getting Burst IOPS: " + ex.getLocalizedMessage()); - } - - if (lMinIops > lMaxIops) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.MIN_IOPS + "' must be less than or equal to the parameter '" + SolidFireUtil.MAX_IOPS + "'."); - } - - if (lMaxIops > lBurstIops) { - throw new CloudRuntimeException("The parameter '" + SolidFireUtil.MAX_IOPS + "' must be less than or equal to the parameter '" + SolidFireUtil.BURST_IOPS + "'."); - } - - if (lMinIops != capacityIops) { - throw new CloudRuntimeException("The parameter '" + CAPACITY_IOPS + "' must be equal to the parameter '" + SolidFireUtil.MIN_IOPS + "'."); - } - - if (lMinIops > SolidFireUtil.MAX_MIN_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("This volume's Min IOPS cannot exceed " + NumberFormat.getInstance().format(SolidFireUtil.MAX_MIN_IOPS_PER_VOLUME) + " IOPS."); - } - - if (lMaxIops > SolidFireUtil.MAX_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("This volume's Max IOPS cannot exceed " + NumberFormat.getInstance().format(SolidFireUtil.MAX_IOPS_PER_VOLUME) + " IOPS."); - } - - if (lBurstIops > SolidFireUtil.MAX_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("This volume's Burst IOPS cannot exceed " + NumberFormat.getInstance().format(SolidFireUtil.MAX_IOPS_PER_VOLUME) + " IOPS."); - } - - details.put(SolidFireUtil.MIN_IOPS, String.valueOf(lMinIops)); - details.put(SolidFireUtil.MAX_IOPS, String.valueOf(lMaxIops)); - details.put(SolidFireUtil.BURST_IOPS, String.valueOf(lBurstIops)); - - SolidFireUtil.SolidFireConnection sfConnection = new SolidFireUtil.SolidFireConnection(managementVip, managementPort, clusterAdminUsername, clusterAdminPassword); - - SolidFireCreateVolume sfCreateVolume = createSolidFireVolume(sfConnection, storagePoolName, capacityBytes, lMinIops, lMaxIops, lBurstIops); - - SolidFireUtil.SolidFireVolume sfVolume = sfCreateVolume.getVolume(); - - String iqn = sfVolume.getIqn(); - - details.put(SolidFireUtil.VOLUME_ID, String.valueOf(sfVolume.getId())); - - parameters.setUuid(iqn); - - if (HypervisorType.VMware.equals(hypervisorType)) { - String datastore = iqn.replace("/", "_"); - String path = "/" + datacenter + "/" + datastore; - - parameters.setHost("VMFS datastore: " + path); - parameters.setPort(0); - parameters.setPath(path); - - details.put(SolidFireUtil.DATASTORE_NAME, datastore); - details.put(SolidFireUtil.IQN, iqn); - details.put(SolidFireUtil.STORAGE_VIP, storageVip); - details.put(SolidFireUtil.STORAGE_PORT, String.valueOf(storagePort)); - } - else { - parameters.setHost(storageVip); - parameters.setPort(storagePort); - parameters.setPath(iqn); - } - - ClusterVO cluster = clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(SolidFireUtil.LOCK_TIME_IN_SECONDS)) { - String errMsg = "Couldn't lock the DB on the following string: " + cluster.getUuid(); - - logger.debug(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - DataStore dataStore = null; - - try { - // this adds a row in the cloud.storage_pool table for this SolidFire volume - dataStore = primaryDataStoreHelper.createPrimaryDataStore(parameters); - - // now that we have a DataStore (we need the id from the DataStore instance), we can create a Volume Access Group, if need be, and - // place the newly created volume in the Volume Access Group - List hosts = hostDao.findByClusterId(clusterId); - - String clusterUuId = clusterDao.findById(clusterId).getUuid(); - - SolidFireUtil.placeVolumeInVolumeAccessGroups(sfConnection, sfVolume.getId(), hosts, clusterUuId); - - SolidFireUtil.SolidFireAccount sfAccount = sfCreateVolume.getAccount(); - Account csAccount = CallContext.current().getCallingAccount(); - - SolidFireUtil.updateCsDbWithSolidFireAccountInfo(csAccount.getId(), sfAccount, dataStore.getId(), accountDetailsDao); - } catch (Exception ex) { - if (dataStore != null) { - primaryDataStoreDao.expunge(dataStore.getId()); - } - - throw new CloudRuntimeException(ex.getMessage()); - } - finally { - lock.unlock(); - lock.releaseRef(); - } - - return dataStore; - } - - private HypervisorType getHypervisorTypeForCluster(long clusterId) { - ClusterVO cluster = clusterDao.findById(clusterId); - - if (cluster == null) { - throw new CloudRuntimeException("Cluster ID '" + clusterId + "' was not found in the database."); - } - - return cluster.getHypervisorType(); - } - - private StoragePoolType getStorageType(HypervisorType hypervisorType) { - if (HypervisorType.XenServer.equals(hypervisorType)) { - return StoragePoolType.IscsiLUN; - } - - if (HypervisorType.VMware.equals(hypervisorType)) { - return StoragePoolType.VMFS; - } - - throw new CloudRuntimeException("The 'hypervisor' parameter must be '" + HypervisorType.XenServer + "' or '" + HypervisorType.VMware + "'."); - } - - private class SolidFireCreateVolume { - private final SolidFireUtil.SolidFireVolume _sfVolume; - private final SolidFireUtil.SolidFireAccount _sfAccount; - - SolidFireCreateVolume(SolidFireUtil.SolidFireVolume sfVolume, SolidFireUtil.SolidFireAccount sfAccount) { - _sfVolume = sfVolume; - _sfAccount = sfAccount; - } - - public SolidFireUtil.SolidFireVolume getVolume() { - return _sfVolume; - } - - public SolidFireUtil.SolidFireAccount getAccount() { - return _sfAccount; - } - } - - private SolidFireCreateVolume createSolidFireVolume(SolidFireUtil.SolidFireConnection sfConnection, - String volumeName, long volumeSize, long minIops, long maxIops, long burstIops) { - try { - Account csAccount = CallContext.current().getCallingAccount(); - long csAccountId = csAccount.getId(); - AccountVO accountVo = accountDao.findById(csAccountId); - - String sfAccountName = SolidFireUtil.getSolidFireAccountName(accountVo.getUuid(), csAccountId); - - SolidFireUtil.SolidFireAccount sfAccount = SolidFireUtil.getAccount(sfConnection, sfAccountName); - - if (sfAccount == null) { - long sfAccountNumber = SolidFireUtil.createAccount(sfConnection, sfAccountName); - - sfAccount = SolidFireUtil.getAccountById(sfConnection, sfAccountNumber); - } - - long sfVolumeId = SolidFireUtil.createVolume(sfConnection, SolidFireUtil.getSolidFireVolumeName(volumeName), sfAccount.getId(), volumeSize, - true, null, minIops, maxIops, burstIops); - SolidFireUtil.SolidFireVolume sfVolume = SolidFireUtil.getVolume(sfConnection, sfVolumeId); - - return new SolidFireCreateVolume(sfVolume, sfAccount); - } catch (Throwable e) { - throw new CloudRuntimeException("Failed to create a SolidFire volume: " + e.toString()); - } - } - - @Override - public boolean attachHost(DataStore store, HostScope scope, StoragePoolInfo existingInfo) { - return true; - } - - @Override - public boolean attachCluster(DataStore store, ClusterScope scope) { - PrimaryDataStoreInfo primaryDataStoreInfo = (PrimaryDataStoreInfo)store; - - List hostsToConnect = resourceMgr.getEligibleUpHostsInClusterForStorageConnection(primaryDataStoreInfo); - - boolean success = false; - logger.debug(String.format("Attaching the pool to each of the hosts %s in the cluster: %s", hostsToConnect, clusterDao.findById(primaryDataStoreInfo.getClusterId()))); - - for (HostVO host : hostsToConnect) { - success = createStoragePool(host, primaryDataStoreInfo); - - if (success) { - break; - } - } - - if (!success) { - throw new CloudRuntimeException("Unable to create storage in cluster " + clusterDao.findById(primaryDataStoreInfo.getClusterId())); - } - - List poolHosts = new ArrayList<>(); - - for (HostVO host : hostsToConnect) { - try { - storageMgr.connectHostToSharedPool(host, primaryDataStoreInfo.getId()); - - poolHosts.add(host); - } catch (Exception e) { - logger.warn("Unable to establish a connection between " + host + " and " + primaryDataStoreInfo, e); - } - } - - if (poolHosts.isEmpty()) { - logger.warn("No host can access storage pool '{}' on cluster '{}'.", primaryDataStoreInfo, clusterDao.findById(primaryDataStoreInfo.getClusterId())); - - primaryDataStoreDao.expunge(primaryDataStoreInfo.getId()); - - throw new CloudRuntimeException("Failed to access storage pool"); - } - - primaryDataStoreHelper.attachCluster(store); - - return true; - } - - private boolean createStoragePool(HostVO host, StoragePool storagePool) { - long hostId = host.getId(); - HypervisorType hypervisorType = host.getHypervisorType(); - CreateStoragePoolCommand cmd = new CreateStoragePoolCommand(true, storagePool); - - if (HypervisorType.VMware.equals(hypervisorType)) { - cmd.setCreateDatastore(true); - - Map details = new HashMap<>(); - - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.DATASTORE_NAME); - - details.put(CreateStoragePoolCommand.DATASTORE_NAME, storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.IQN); - - details.put(CreateStoragePoolCommand.IQN, storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.STORAGE_VIP); - - details.put(CreateStoragePoolCommand.STORAGE_HOST, storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.STORAGE_PORT); - - details.put(CreateStoragePoolCommand.STORAGE_PORT, storagePoolDetail.getValue()); - - cmd.setDetails(details); - } - - Answer answer = agentMgr.easySend(hostId, cmd); - - if (answer != null && answer.getResult()) { - return true; - } else { - primaryDataStoreDao.expunge(storagePool.getId()); - - final String msg; - - if (answer != null) { - msg = String.format("Cannot create storage pool through host '%s' due to the following: %s", host, answer.getDetails()); - } else { - msg = String.format("Cannot create storage pool through host '%s' due to CreateStoragePoolCommand returns null", host); - } - - logger.warn(msg); - - throw new CloudRuntimeException(msg); - } - } - - @Override - public boolean attachZone(DataStore dataStore, ZoneScope scope, HypervisorType hypervisorType) { - return true; - } - - @Override - public boolean maintain(DataStore dataStore) { - storagePoolAutomation.maintain(dataStore); - primaryDataStoreHelper.maintain(dataStore); - - return true; - } - - @Override - public boolean cancelMaintain(DataStore store) { - primaryDataStoreHelper.cancelMaintain(store); - storagePoolAutomation.cancelMaintain(store); - - return true; - } - - // invoked to delete primary storage that is based on the SolidFire plug-in - @Override - public boolean deleteDataStore(DataStore dataStore) { - List hostPoolRecords = storagePoolHostDao.listByPoolId(dataStore.getId()); - - HypervisorType hypervisorType = null; - - if (hostPoolRecords.size() > 0 ) { - hypervisorType = getHypervisorType(hostPoolRecords.get(0).getHostId()); - } - - if (!isSupportedHypervisorType(hypervisorType)) { - throw new CloudRuntimeException(hypervisorType + " is not a supported hypervisor type."); - } - - StoragePool storagePool = (StoragePool)dataStore; - StoragePoolVO storagePoolVO = primaryDataStoreDao.findById(storagePool.getId()); - List unusedTemplatesInPool = tmpltMgr.getUnusedTemplatesInPool(storagePoolVO); - - for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) { - tmpltMgr.evictTemplateFromStoragePool(templatePoolVO); - } - - Long clusterId = null; - Long hostId = null; - - for (StoragePoolHostVO host : hostPoolRecords) { - DeleteStoragePoolCommand deleteCmd = new DeleteStoragePoolCommand(storagePool); - - if (HypervisorType.VMware.equals(hypervisorType)) { - deleteCmd.setRemoveDatastore(true); - - Map details = new HashMap<>(); - - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.DATASTORE_NAME); - - details.put(DeleteStoragePoolCommand.DATASTORE_NAME, storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.IQN); - - details.put(DeleteStoragePoolCommand.IQN, storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.STORAGE_VIP); - - details.put(DeleteStoragePoolCommand.STORAGE_HOST, storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePool.getId(), SolidFireUtil.STORAGE_PORT); - - details.put(DeleteStoragePoolCommand.STORAGE_PORT, storagePoolDetail.getValue()); - - deleteCmd.setDetails(details); - } - - final Answer answer = agentMgr.easySend(host.getHostId(), deleteCmd); - - if (answer != null && answer.getResult()) { - HostVO hostVO = hostDao.findById(host.getHostId()); - if (hostVO != null) { - clusterId = hostVO.getClusterId(); - hostId = hostVO.getId(); - } - logger.info("Successfully deleted storage pool using Host {} with ID {}", hostVO, host.getHostId()); - break; - } - else { - HostVO hostVO = hostDao.findById(host.getHostId()); - if (answer != null) { - logger.error("Failed to delete storage pool using Host {} with ID: {}: {}", hostVO, host.getHostId(), answer.getResult()); - } - else { - logger.error("Failed to delete storage pool using Host {} with ID: {}", hostVO, host.getHostId()); - } - } - } - - if (clusterId != null) { - ClusterVO cluster = clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(SolidFireUtil.LOCK_TIME_IN_SECONDS)) { - String errMsg = "Couldn't lock the DB on the following string: " + cluster.getUuid(); - - logger.debug(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - try { - long sfVolumeId = getVolumeId(storagePool.getId()); - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePool.getId(), storagePoolDetailsDao); - - List sfVags = SolidFireUtil.getAllVags(sfConnection); - - for (SolidFireUtil.SolidFireVag sfVag : sfVags) { - if (SolidFireUtil.sfVagContains(sfVag, sfVolumeId, clusterId, hostDao)) { - SolidFireUtil.removeVolumeIdsFromSolidFireVag(sfConnection, sfVag.getId(), new Long[] { sfVolumeId }); - } - } - } - finally { - lock.unlock(); - lock.releaseRef(); - } - } - - if (hostId != null) { - handleTargetsForVMware(hostId, storagePool.getId()); - } - - deleteSolidFireVolume(storagePool.getId()); - - return primaryDataStoreHelper.deletePrimaryDataStore(dataStore); - } - - private void handleTargetsForVMware(long hostId, long storagePoolId) { - HostVO host = hostDao.findById(hostId); - - if (host.getHypervisorType() == HypervisorType.VMware) { - String storageAddress = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.STORAGE_VIP).getValue(); - int storagePort = Integer.parseInt(storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.STORAGE_PORT).getValue()); - String iqn = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.IQN).getValue(); - - ModifyTargetsCommand cmd = new ModifyTargetsCommand(); - - List> targets = new ArrayList<>(); - - Map target = new HashMap<>(); - - target.put(ModifyTargetsCommand.STORAGE_HOST, storageAddress); - target.put(ModifyTargetsCommand.STORAGE_PORT, String.valueOf(storagePort)); - target.put(ModifyTargetsCommand.IQN, iqn); - - targets.add(target); - - cmd.setTargets(targets); - cmd.setApplyToAllHostsInCluster(true); - cmd.setAdd(false); - cmd.setTargetTypeToRemove(ModifyTargetsCommand.TargetTypeToRemove.DYNAMIC); - cmd.setRemoveAsync(true); - - sendModifyTargetsCommand(cmd, host); - } - } - - private void sendModifyTargetsCommand(ModifyTargetsCommand cmd, Host host) { - Answer answer = agentMgr.easySend(host.getId(), cmd); - - if (answer == null) { - String msg = "Unable to get an answer to the modify targets command"; - - logger.warn(msg); - } - else if (!answer.getResult()) { - String msg = String.format("Unable to modify target on the following host: %s", host); - - logger.warn(msg); - } - } - - private void deleteSolidFireVolume(long storagePoolId) { - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); - - long sfVolumeId = getVolumeId(storagePoolId); - - SolidFireUtil.deleteVolume(sfConnection, sfVolumeId); - } - - private long getVolumeId(long storagePoolId) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.VOLUME_ID); - - String volumeId = storagePoolDetail.getValue(); - - return Long.parseLong(volumeId); - } - - private long getIopsValue(long storagePoolId, String iopsKey) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, iopsKey); - - String iops = storagePoolDetail.getValue(); - - return Long.parseLong(iops); - } - - private static boolean isSupportedHypervisorType(HypervisorType hypervisorType) { - return HypervisorType.XenServer.equals(hypervisorType) || HypervisorType.VMware.equals(hypervisorType); - } - - private HypervisorType getHypervisorType(long hostId) { - HostVO host = hostDao.findById(hostId); - - if (host != null) { - return host.getHypervisorType(); - } - - return HypervisorType.None; - } - - /* (non-Javadoc) - * @see org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle#migrateToObjectStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) - */ - @Override - public boolean migrateToObjectStore(DataStore store) { - return false; - } - - @Override - public void updateStoragePool(StoragePool storagePool, Map details) { - String strCapacityBytes = details.get(PrimaryDataStoreLifeCycle.CAPACITY_BYTES); - String strCapacityIops = details.get(PrimaryDataStoreLifeCycle.CAPACITY_IOPS); - - Long capacityBytes = strCapacityBytes != null ? Long.parseLong(strCapacityBytes) : null; - Long capacityIops = strCapacityIops != null ? Long.parseLong(strCapacityIops) : null; - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePool.getId(), storagePoolDetailsDao); - - long size = capacityBytes != null ? capacityBytes : storagePool.getCapacityBytes(); - - long currentMinIops = getIopsValue(storagePool.getId(), SolidFireUtil.MIN_IOPS); - long currentMaxIops = getIopsValue(storagePool.getId(), SolidFireUtil.MAX_IOPS); - long currentBurstIops = getIopsValue(storagePool.getId(), SolidFireUtil.BURST_IOPS); - - long minIops = currentMinIops; - long maxIops = currentMaxIops; - long burstIops = currentBurstIops; - - if (capacityIops != null) { - if (capacityIops > SolidFireUtil.MAX_MIN_IOPS_PER_VOLUME) { - throw new CloudRuntimeException("This volume cannot exceed " + NumberFormat.getInstance().format(SolidFireUtil.MAX_MIN_IOPS_PER_VOLUME) + " IOPS."); - } - - float maxPercentOfMin = currentMaxIops / (float)currentMinIops; - float burstPercentOfMax = currentBurstIops / (float)currentMaxIops; - - minIops = capacityIops; - maxIops = (long)(minIops * maxPercentOfMin); - burstIops = (long)(maxIops * burstPercentOfMax); - - if (maxIops > SolidFireUtil.MAX_IOPS_PER_VOLUME) { - maxIops = SolidFireUtil.MAX_IOPS_PER_VOLUME; - } - - if (burstIops > SolidFireUtil.MAX_IOPS_PER_VOLUME) { - burstIops = SolidFireUtil.MAX_IOPS_PER_VOLUME; - } - } - - SolidFireUtil.modifyVolume(sfConnection, getVolumeId(storagePool.getId()), size, null, minIops, maxIops, burstIops); - - SolidFireUtil.updateCsDbWithSolidFireIopsInfo(storagePool.getId(), primaryDataStoreDao, storagePoolDetailsDao, minIops, maxIops, burstIops); - } - - @Override - public void enableStoragePool(DataStore dataStore) { - primaryDataStoreHelper.enable(dataStore); - } - - @Override - public void disableStoragePool(DataStore dataStore) { - primaryDataStoreHelper.disable(dataStore); - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java deleted file mode 100644 index c961c9267395..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireHostListener.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import com.cloud.host.Host; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ModifyStoragePoolAnswer; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.agent.api.ModifyTargetsCommand; -import com.cloud.alert.AlertManager; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.VolumeVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.storage.dao.VolumeDao; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.dao.VMInstanceDao; - -public class SolidFireHostListener implements HypervisorHostListener { - protected Logger logger = LogManager.getLogger(getClass()); - - @Inject private AgentManager agentMgr; - @Inject private AlertManager alertMgr; - @Inject private ClusterDao clusterDao; - @Inject private DataStoreManager dataStoreMgr; - @Inject private HostDao hostDao; - @Inject private PrimaryDataStoreDao storagePoolDao; - @Inject private StoragePoolDetailsDao storagePoolDetailsDao; - @Inject private StoragePoolHostDao storagePoolHostDao; - @Inject private VMInstanceDao vmDao; - @Inject private VolumeDao volumeDao; - - @Override - public boolean hostAdded(long hostId) { - HostVO host = hostDao.findById(hostId); - - if (host == null) { - logger.error(String.format("Failed to add host by SolidFireHostListener as host was not found with id = %s ", hostId)); - - return false; - } - - if (host.getClusterId() == null) { - logger.error("Failed to add host by SolidFireHostListener as host has no associated cluster id"); - return false; - } - - SolidFireUtil.hostAddedToCluster(hostId, host.getClusterId(), SolidFireUtil.PROVIDER_NAME, - clusterDao, hostDao, storagePoolDao, storagePoolDetailsDao); - - handleVMware(host, true, ModifyTargetsCommand.TargetTypeToRemove.NEITHER); - - return true; - } - - @Override - public boolean hostConnect(long hostId, long storagePoolId) { - HostVO host = hostDao.findById(hostId); - - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(storagePoolId, hostId); - - if (storagePoolHost == null) { - storagePoolHost = new StoragePoolHostVO(storagePoolId, hostId, ""); - - storagePoolHostDao.persist(storagePoolHost); - } - - if (host.getHypervisorType().equals(HypervisorType.XenServer)) { - handleXenServer(host.getClusterId(), host, storagePoolId); - } - else if (host.getHypervisorType().equals(HypervisorType.KVM)) { - handleKVM(host, storagePoolId); - } - - return true; - } - - @Override - public boolean hostDisconnected(long hostId, long storagePoolId) { - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(storagePoolId, hostId); - - if (storagePoolHost != null) { - storagePoolHostDao.deleteStoragePoolHostDetails(hostId, storagePoolId); - } - - return true; - } - - @Override - public boolean hostAboutToBeRemoved(long hostId) { - HostVO host = hostDao.findById(hostId); - - SolidFireUtil.hostRemovedFromCluster(hostId, host.getClusterId(), SolidFireUtil.PROVIDER_NAME, - clusterDao, hostDao, storagePoolDao, storagePoolDetailsDao); - - handleVMware(host, false, ModifyTargetsCommand.TargetTypeToRemove.BOTH); - - return true; - } - - @Override - public boolean hostRemoved(long hostId, long clusterId) { - return true; - } - - @Override - public boolean hostEnabled(long hostId) { - return true; - } - - private void handleXenServer(long clusterId, Host host, long storagePoolId) { - List storagePaths = getStoragePaths(clusterId, storagePoolId); - - StoragePool storagePool = (StoragePool)dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - - for (String storagePath : storagePaths) { - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, storagePool); - - cmd.setStoragePath(storagePath); - - sendModifyStoragePoolCommand(cmd, storagePool, host); - } - } - - private void handleVMware(HostVO host, boolean add, ModifyTargetsCommand.TargetTypeToRemove targetTypeToRemove) { - if (host != null && HypervisorType.VMware.equals(host.getHypervisorType())) { - List storagePools = storagePoolDao.findPoolsByProvider(SolidFireUtil.PROVIDER_NAME); - - if (storagePools != null && storagePools.size() > 0) { - List> targets = new ArrayList<>(); - - for (StoragePoolVO storagePool : storagePools) { - List> targetsForClusterAndStoragePool = getTargets(host.getClusterId(), storagePool.getId()); - - targets.addAll(targetsForClusterAndStoragePool); - } - - ModifyTargetsCommand cmd = new ModifyTargetsCommand(); - - cmd.setTargets(targets); - cmd.setAdd(add); - cmd.setTargetTypeToRemove(targetTypeToRemove); - cmd.setRemoveAsync(true); - - sendModifyTargetsCommand(cmd, host); - } - } - } - - private void handleKVM(Host host, long storagePoolId) { - StoragePool storagePool = (StoragePool)dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, storagePool); - - sendModifyStoragePoolCommand(cmd, storagePool, host); - } - - private List getStoragePaths(long clusterId, long storagePoolId) { - List storagePaths = new ArrayList<>(); - - // If you do not pass in null for the second parameter, you only get back applicable ROOT disks. - List volumes = volumeDao.findNonDestroyedVolumesByPoolId(storagePoolId, null); - - if (volumes != null) { - for (VolumeVO volume : volumes) { - Long instanceId = volume.getInstanceId(); - - if (instanceId != null) { - VMInstanceVO vmInstance = vmDao.findById(instanceId); - - Long hostIdForVm = vmInstance.getHostId() != null ? vmInstance.getHostId() : vmInstance.getLastHostId(); - - if (hostIdForVm != null) { - HostVO hostForVm = hostDao.findById(hostIdForVm); - - if (hostForVm != null && hostForVm.getClusterId().equals(clusterId)) { - storagePaths.add(volume.get_iScsiName()); - } - } - } - } - } - - return storagePaths; - } - - private List> getTargets(long clusterId, long storagePoolId) { - List> targets = new ArrayList<>(); - - StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); - - // If you do not pass in null for the second parameter, you only get back applicable ROOT disks. - List volumes = volumeDao.findNonDestroyedVolumesByPoolId(storagePoolId, null); - - if (volumes != null) { - for (VolumeVO volume : volumes) { - Long instanceId = volume.getInstanceId(); - - if (instanceId != null) { - VMInstanceVO vmInstance = vmDao.findById(instanceId); - - Long hostIdForVm = vmInstance.getHostId() != null ? vmInstance.getHostId() : vmInstance.getLastHostId(); - - if (hostIdForVm != null) { - HostVO hostForVm = hostDao.findById(hostIdForVm); - - if (hostForVm.getClusterId().equals(clusterId)) { - Map details = new HashMap<>(); - - details.put(ModifyTargetsCommand.IQN, volume.get_iScsiName()); - details.put(ModifyTargetsCommand.STORAGE_HOST, storagePool.getHostAddress()); - details.put(ModifyTargetsCommand.STORAGE_PORT, String.valueOf(storagePool.getPort())); - - targets.add(details); - } - } - } - } - } - - return targets; - } - - private void sendModifyTargetsCommand(ModifyTargetsCommand cmd, Host host) { - Answer answer = agentMgr.easySend(host.getId(), cmd); - - if (answer == null) { - throw new CloudRuntimeException("Unable to get an answer to the modify targets command"); - } - - if (!answer.getResult()) { - String msg = String.format("Unable to modify targets on the following host: %s", host); - - alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), msg, msg); - - throw new CloudRuntimeException(msg); - } - } - - private void sendModifyStoragePoolCommand(ModifyStoragePoolCommand cmd, StoragePool storagePool, Host host) { - Answer answer = agentMgr.easySend(host.getId(), cmd); - - if (answer == null) { - throw new CloudRuntimeException(String.format("Unable to get an answer to the modify storage pool command (%s)", storagePool)); - } - - if (!answer.getResult()) { - String msg = String.format("Unable to attach storage pool %s to host %s", storagePool, host); - - alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, storagePool.getDataCenterId(), storagePool.getPodId(), msg, msg); - - throw new CloudRuntimeException(String.format("Unable to establish a connection from agent to storage pool %s due to %s", storagePool, answer.getDetails())); - } - - assert (answer instanceof ModifyStoragePoolAnswer) : String.format("ModifyStoragePoolAnswer expected ; Pool = %s Host = %s", storagePool, host); - - logger.info("Connection established between storage pool {} and host {}", storagePool, host); - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFirePrimaryDataStoreProvider.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFirePrimaryDataStoreProvider.java deleted file mode 100644 index 56e794f27f6e..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFirePrimaryDataStoreProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; -import org.apache.cloudstack.storage.datastore.driver.SolidFirePrimaryDataStoreDriver; -import org.apache.cloudstack.storage.datastore.lifecycle.SolidFirePrimaryDataStoreLifeCycle; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; - -import com.cloud.utils.component.ComponentContext; - -@Component -public class SolidFirePrimaryDataStoreProvider implements PrimaryDataStoreProvider { - private DataStoreLifeCycle lifecycle; - private PrimaryDataStoreDriver driver; - private HypervisorHostListener listener; - - SolidFirePrimaryDataStoreProvider() { - } - - @Override - public String getName() { - return SolidFireUtil.PROVIDER_NAME; - } - - @Override - public DataStoreLifeCycle getDataStoreLifeCycle() { - return lifecycle; - } - - @Override - public PrimaryDataStoreDriver getDataStoreDriver() { - return driver; - } - - @Override - public HypervisorHostListener getHostListener() { - return listener; - } - - @Override - public boolean configure(Map params) { - lifecycle = ComponentContext.inject(SolidFirePrimaryDataStoreLifeCycle.class); - driver = ComponentContext.inject(SolidFirePrimaryDataStoreDriver.class); - listener = ComponentContext.inject(SolidFireHostListener.class); - - return true; - } - - @Override - public Set getTypes() { - Set types = new HashSet(); - - types.add(DataStoreProviderType.PRIMARY); - - return types; - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedHostListener.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedHostListener.java deleted file mode 100644 index f746390085b8..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedHostListener.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import com.cloud.host.Host; -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.ModifyStoragePoolAnswer; -import com.cloud.agent.api.ModifyStoragePoolCommand; -import com.cloud.agent.api.ModifyTargetsCommand; -import com.cloud.alert.AlertManager; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.storage.DataStoreRole; -import com.cloud.storage.StoragePool; -import com.cloud.storage.StoragePoolHostVO; -import com.cloud.storage.dao.StoragePoolHostDao; -import com.cloud.utils.exception.CloudRuntimeException; - -public class SolidFireSharedHostListener implements HypervisorHostListener { - protected Logger logger = LogManager.getLogger(getClass()); - - @Inject private AgentManager agentMgr; - @Inject private AlertManager alertMgr; - @Inject private ClusterDao clusterDao; - @Inject private DataStoreManager dataStoreMgr; - @Inject private HostDao hostDao; - @Inject private PrimaryDataStoreDao storagePoolDao; - @Inject private StoragePoolHostDao storagePoolHostDao; - @Inject private StoragePoolDetailsDao storagePoolDetailsDao; - - @Override - public boolean hostAdded(long hostId) { - HostVO host = hostDao.findById(hostId); - - if (host == null) { - logger.error(String.format("Failed to add host by SolidFireSharedHostListener as host was not found with id = %s ", hostId)); - - return false; - } - - if (host.getClusterId() == null) { - logger.error("Failed to add host by SolidFireSharedHostListener as host has no associated cluster id"); - return false; - } - - SolidFireUtil.hostAddedToCluster(hostId, host.getClusterId(), SolidFireUtil.SHARED_PROVIDER_NAME, - clusterDao, hostDao, storagePoolDao, storagePoolDetailsDao); - - handleVMware(host, true, ModifyTargetsCommand.TargetTypeToRemove.NEITHER); - - return true; - } - - @Override - public boolean hostConnect(long hostId, long storagePoolId) { - StoragePool storagePool = (StoragePool) dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); - ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, storagePool); - - ModifyStoragePoolAnswer answer = sendModifyStoragePoolCommand(cmd, storagePool, hostId); - - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(storagePoolId, hostId); - - if (storagePoolHost != null) { - storagePoolHost.setLocalPath(answer.getPoolInfo().getLocalPath().replaceAll("//", "/")); - } else { - storagePoolHost = new StoragePoolHostVO(storagePoolId, hostId, answer.getPoolInfo().getLocalPath().replaceAll("//", "/")); - - storagePoolHostDao.persist(storagePoolHost); - } - - StoragePoolVO storagePoolVO = storagePoolDao.findById(storagePoolId); - - storagePoolVO.setCapacityBytes(answer.getPoolInfo().getCapacityBytes()); - storagePoolVO.setUsedBytes(answer.getPoolInfo().getCapacityBytes() - answer.getPoolInfo().getAvailableBytes()); - - storagePoolDao.update(storagePoolId, storagePoolVO); - - return true; - } - - @Override - public boolean hostDisconnected(long hostId, long storagePoolId) { - StoragePoolHostVO storagePoolHost = storagePoolHostDao.findByPoolHost(storagePoolId, hostId); - - if (storagePoolHost != null) { - storagePoolHostDao.deleteStoragePoolHostDetails(hostId, storagePoolId); - } - - return true; - } - - @Override - public boolean hostAboutToBeRemoved(long hostId) { - HostVO host = hostDao.findById(hostId); - - SolidFireUtil.hostRemovedFromCluster(hostId, host.getClusterId(), SolidFireUtil.SHARED_PROVIDER_NAME, - clusterDao, hostDao, storagePoolDao, storagePoolDetailsDao); - - handleVMware(host, false, ModifyTargetsCommand.TargetTypeToRemove.BOTH); - - return true; - } - - @Override - public boolean hostRemoved(long hostId, long clusterId) { - return true; - } - - @Override - public boolean hostEnabled(long hostId) { - return true; - } - - private void handleVMware(HostVO host, boolean add, ModifyTargetsCommand.TargetTypeToRemove targetTypeToRemove) { - if (HypervisorType.VMware.equals(host.getHypervisorType())) { - List storagePools = storagePoolDao.findPoolsByProvider(SolidFireUtil.SHARED_PROVIDER_NAME); - - if (storagePools != null && storagePools.size() > 0) { - List> targets = new ArrayList<>(); - - for (StoragePoolVO storagePool : storagePools) { - if (storagePool.getClusterId().equals(host.getClusterId())) { - long storagePoolId = storagePool.getId(); - - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.IQN); - - String iqn = storagePoolDetail.getValue(); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.STORAGE_VIP); - - String sVip = storagePoolDetail.getValue(); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.STORAGE_PORT); - - String sPort = storagePoolDetail.getValue(); - - Map details = new HashMap<>(); - - details.put(ModifyTargetsCommand.IQN, iqn); - details.put(ModifyTargetsCommand.STORAGE_HOST, sVip); - details.put(ModifyTargetsCommand.STORAGE_PORT, sPort); - - targets.add(details); - } - } - - if (targets.size() > 0) { - ModifyTargetsCommand cmd = new ModifyTargetsCommand(); - - cmd.setTargets(targets); - cmd.setAdd(add); - cmd.setTargetTypeToRemove(targetTypeToRemove); - cmd.setRemoveAsync(true); - - sendModifyTargetsCommand(cmd, host); - } - } - } - } - - private void sendModifyTargetsCommand(ModifyTargetsCommand cmd, Host host) { - Answer answer = agentMgr.easySend(host.getId(), cmd); - - if (answer == null) { - throw new CloudRuntimeException("Unable to get an answer to the modify targets command"); - } - - if (!answer.getResult()) { - String msg = String.format("Unable to modify targets on the following host: %s", host); - - alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), msg, msg); - - throw new CloudRuntimeException(msg); - } - } - - private ModifyStoragePoolAnswer sendModifyStoragePoolCommand(ModifyStoragePoolCommand cmd, StoragePool storagePool, long hostId) { - Answer answer = agentMgr.easySend(hostId, cmd); - - if (answer == null) { - throw new CloudRuntimeException(String.format("Unable to get an answer to the modify storage pool command for storage pool: %s", storagePool)); - } - - HostVO host = hostDao.findById(hostId); - if (!answer.getResult()) { - String msg = String.format("Unable to attach storage pool %s to the host %s", storagePool, host); - - alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, storagePool.getDataCenterId(), storagePool.getPodId(), msg, msg); - - throw new CloudRuntimeException(msg); - } - - assert (answer instanceof ModifyStoragePoolAnswer) : - String.format("ModifyStoragePoolAnswer not returned from ModifyStoragePoolCommand; Storage pool = %s; Host = %s", storagePool, host); - - logger.info("Connection established between storage pool {} and host {}", storagePool, host); - - return (ModifyStoragePoolAnswer)answer; - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedPrimaryDataStoreProvider.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedPrimaryDataStoreProvider.java deleted file mode 100644 index d5b82a16a0cb..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/provider/SolidFireSharedPrimaryDataStoreProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 org.apache.cloudstack.storage.datastore.provider; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle; -import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreProvider; -import org.apache.cloudstack.storage.datastore.driver.SolidFireSharedPrimaryDataStoreDriver; -import org.apache.cloudstack.storage.datastore.lifecycle.SolidFireSharedPrimaryDataStoreLifeCycle; -import org.apache.cloudstack.storage.datastore.util.SolidFireUtil; - -import com.cloud.utils.component.ComponentContext; - -@Component -public class SolidFireSharedPrimaryDataStoreProvider implements PrimaryDataStoreProvider { - private DataStoreLifeCycle lifecycle; - private PrimaryDataStoreDriver driver; - private HypervisorHostListener listener; - - SolidFireSharedPrimaryDataStoreProvider() { - } - - @Override - public String getName() { - return SolidFireUtil.SHARED_PROVIDER_NAME; - } - - @Override - public DataStoreLifeCycle getDataStoreLifeCycle() { - return lifecycle; - } - - @Override - public PrimaryDataStoreDriver getDataStoreDriver() { - return driver; - } - - @Override - public HypervisorHostListener getHostListener() { - return listener; - } - - @Override - public boolean configure(Map params) { - lifecycle = ComponentContext.inject(SolidFireSharedPrimaryDataStoreLifeCycle.class); - driver = ComponentContext.inject(SolidFireSharedPrimaryDataStoreDriver.class); - listener = ComponentContext.inject(SolidFireSharedHostListener.class); - - return true; - } - - @Override - public Set getTypes() { - Set types = new HashSet(); - - types.add(DataStoreProviderType.PRIMARY); - - return types; - } -} diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java deleted file mode 100644 index 3759cb844537..000000000000 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/util/SolidFireUtil.java +++ /dev/null @@ -1,1414 +0,0 @@ -// 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 org.apache.cloudstack.storage.datastore.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.UUID; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; - -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO; -import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; - -import com.cloud.dc.ClusterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.user.AccountDetailVO; -import com.cloud.user.AccountDetailsDao; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.exception.CloudRuntimeException; - -import com.google.common.base.Preconditions; -import com.google.common.primitives.Longs; - -import com.solidfire.client.ElementFactory; -import com.solidfire.element.api.Account; -import com.solidfire.element.api.AddAccountRequest; -import com.solidfire.element.api.AddInitiatorsToVolumeAccessGroupRequest; -import com.solidfire.element.api.AddVolumesToVolumeAccessGroupRequest; -import com.solidfire.element.api.CloneVolumeRequest; -import com.solidfire.element.api.CloneVolumeResult; -import com.solidfire.element.api.CreateSnapshotRequest; -import com.solidfire.element.api.CreateVolumeAccessGroupRequest; -import com.solidfire.element.api.CreateVolumeRequest; -import com.solidfire.element.api.DeleteSnapshotRequest; -import com.solidfire.element.api.DeleteVolumeRequest; -import com.solidfire.element.api.GetAccountByIDRequest; -import com.solidfire.element.api.GetAccountByNameRequest; -import com.solidfire.element.api.GetAsyncResultRequest; -import com.solidfire.element.api.ListSnapshotsRequest; -import com.solidfire.element.api.ListVolumeAccessGroupsRequest; -import com.solidfire.element.api.ListVolumesRequest; -import com.solidfire.element.api.ModifyVolumeRequest; -import com.solidfire.element.api.QoS; -import com.solidfire.element.api.RemoveInitiatorsFromVolumeAccessGroupRequest; -import com.solidfire.element.api.RemoveVolumesFromVolumeAccessGroupRequest; -import com.solidfire.element.api.RollbackToSnapshotRequest; -import com.solidfire.element.api.Snapshot; -import com.solidfire.element.api.SolidFireElement; -import com.solidfire.element.api.Volume; -import com.solidfire.element.api.VolumeAccessGroup; -import com.solidfire.jsvcgen.javautil.Optional; - -import static org.apache.commons.lang.ArrayUtils.toPrimitive; - -public class SolidFireUtil { - protected static Logger LOGGER = LogManager.getLogger(SolidFireUtil.class); - - public static final String PROVIDER_NAME = "SolidFire"; - public static final String SHARED_PROVIDER_NAME = "SolidFireShared"; - - private static final Random RANDOM = new Random(System.nanoTime()); - public static final int LOCK_TIME_IN_SECONDS = 300; - - public static final String LOGGER_PREFIX = "SolidFire: "; - - public static final String MANAGEMENT_VIP = "mVip"; - public static final String STORAGE_VIP = "sVip"; - - public static final String MANAGEMENT_PORT = "mPort"; - public static final String STORAGE_PORT = "sPort"; - - public static final String CLUSTER_ADMIN_USERNAME = "clusterAdminUsername"; - public static final String CLUSTER_ADMIN_PASSWORD = "clusterAdminPassword"; - - // these three variables should only be used for the SolidFire plug-in with the name SolidFireUtil.PROVIDER_NAME - public static final String CLUSTER_DEFAULT_MIN_IOPS = "clusterDefaultMinIops"; - public static final String CLUSTER_DEFAULT_MAX_IOPS = "clusterDefaultMaxIops"; - public static final String CLUSTER_DEFAULT_BURST_IOPS_PERCENT_OF_MAX_IOPS = "clusterDefaultBurstIopsPercentOfMaxIops"; - - // these three variables should only be used for the SolidFire plug-in with the name SolidFireUtil.SHARED_PROVIDER_NAME - public static final String MIN_IOPS = "minIops"; - public static final String MAX_IOPS = "maxIops"; - public static final String BURST_IOPS = "burstIops"; - - private static final String ACCOUNT_ID = "accountId"; - - public static final String VOLUME_ID = "volumeId"; - public static final String TEMP_VOLUME_ID = "tempVolumeId"; - public static final String SNAPSHOT_ID = "snapshotId"; - - public static final String CloudStackVolumeId = "CloudStackVolumeId"; - public static final String CloudStackVolumeSize = "CloudStackVolumeSize"; - public static final String CloudStackSnapshotId = "CloudStackSnapshotId"; - public static final String CloudStackSnapshotSize = "CloudStackSnapshotSize"; - public static final String CloudStackTemplateId = "CloudStackTemplateId"; - public static final String CloudStackTemplateSize = "CloudStackTemplateSize"; - - public static final String ORIG_CS_VOLUME_ID = "originalCloudStackVolumeId"; - - public static final String VOLUME_SIZE = "sfVolumeSize"; - - public static final String STORAGE_POOL_ID = "sfStoragePoolId"; - - public static final String DATACENTER = "datacenter"; - - public static final String DATASTORE_NAME = "datastoreName"; - public static final String IQN = "iqn"; - - private static final String SF_CS_ACCOUNT_PREFIX = "CloudStack_"; - - public static final long MIN_VOLUME_SIZE = 1000000000; - - public static final long MIN_IOPS_PER_VOLUME = 100; - public static final long MAX_MIN_IOPS_PER_VOLUME = 15000; - public static final long MAX_IOPS_PER_VOLUME = 100000; - - private static final int DEFAULT_MANAGEMENT_PORT = 443; - private static final int DEFAULT_STORAGE_PORT = 3260; - - private static final int MAX_NUM_VAGS_PER_VOLUME = 4; - private static final int MAX_NUM_INITIATORS_PER_VAG = 64; - - public static class SolidFireConnection { - private final String _managementVip; - private final int _managementPort; - private final String _clusterAdminUsername; - private final String _clusterAdminPassword; - - public SolidFireConnection(String managementVip, int managementPort, String clusterAdminUsername, String clusterAdminPassword) { - if (managementVip == null) { - throw new CloudRuntimeException("The management VIP cannot be 'null'."); - } - - if (managementPort <= 0) { - throw new CloudRuntimeException("The management port must be a positive integer."); - } - - if (clusterAdminUsername == null) { - throw new CloudRuntimeException("The cluster admin username cannot be 'null'."); - } - - if (clusterAdminPassword == null) { - throw new CloudRuntimeException("The cluster admin password cannot be 'null'."); - } - - _managementVip = managementVip; - _managementPort = managementPort; - _clusterAdminUsername = clusterAdminUsername; - _clusterAdminPassword = clusterAdminPassword; - } - - String getManagementVip() { - return _managementVip; - } - - int getManagementPort() { - return _managementPort; - } - - String getClusterAdminUsername() { - return _clusterAdminUsername; - } - - private String getClusterAdminPassword() { - return _clusterAdminPassword; - } - - @Override - public int hashCode() { - return _managementVip.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SolidFireConnection)) { - return false; - } - - SolidFireConnection sfConnection = (SolidFireConnection)obj; - - return _managementVip.equals(sfConnection.getManagementVip()); - } - } - - public static SolidFireConnection getSolidFireConnection(long storagePoolId, StoragePoolDetailsDao storagePoolDetailsDao) { - StoragePoolDetailVO storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.MANAGEMENT_VIP); - - String mVip = storagePoolDetail.getValue(); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.MANAGEMENT_PORT); - - int mPort = Integer.parseInt(storagePoolDetail.getValue()); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.CLUSTER_ADMIN_USERNAME); - - String clusterAdminUsername = storagePoolDetail.getValue(); - - storagePoolDetail = storagePoolDetailsDao.findDetail(storagePoolId, SolidFireUtil.CLUSTER_ADMIN_PASSWORD); - - String clusterAdminPassword = storagePoolDetail.getValue(); - - return new SolidFireConnection(mVip, mPort, clusterAdminUsername, clusterAdminPassword); - } - - private static SolidFireElement getSolidFireElement(SolidFireConnection sfConnection) { - return ElementFactory.create(sfConnection.getManagementVip(), sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword()); - } - - // used to parse the "url" parameter when creating primary storage that's based on the SolidFire plug-in with the - // name SolidFireUtil.PROVIDER_NAME (as opposed to the SolidFire plug-in with the name SolidFireUtil.SHARED_PROVIDER_NAME) - // return a String instance that contains at most the MVIP and SVIP info - public static String getModifiedUrl(String originalUrl) { - StringBuilder sb = new StringBuilder(); - - String delimiter = ";"; - - StringTokenizer st = new StringTokenizer(originalUrl, delimiter); - - while (st.hasMoreElements()) { - String token = st.nextElement().toString().toUpperCase(); - - if (token.startsWith(SolidFireUtil.MANAGEMENT_VIP.toUpperCase()) || token.startsWith(SolidFireUtil.STORAGE_VIP.toUpperCase())) { - sb.append(token).append(delimiter); - } - } - - String modifiedUrl = sb.toString(); - int lastIndexOf = modifiedUrl.lastIndexOf(delimiter); - - if (lastIndexOf == (modifiedUrl.length() - delimiter.length())) { - return modifiedUrl.substring(0, lastIndexOf); - } - - return modifiedUrl; - } - - public static String getManagementVip(String url) { - return getVip(SolidFireUtil.MANAGEMENT_VIP, url); - } - - public static String getStorageVip(String url) { - return getVip(SolidFireUtil.STORAGE_VIP, url); - } - - public static int getManagementPort(String url) { - return getPort(SolidFireUtil.MANAGEMENT_VIP, url, DEFAULT_MANAGEMENT_PORT); - } - - public static int getStoragePort(String url) { - return getPort(SolidFireUtil.STORAGE_VIP, url, DEFAULT_STORAGE_PORT); - } - - public static String getValue(String keyToMatch, String url) { - return getValue(keyToMatch, url, true); - } - - public static String getValue(String keyToMatch, String url, boolean throwExceptionIfNotFound) { - String delimiter1 = ";"; - String delimiter2 = "="; - - StringTokenizer st = new StringTokenizer(url, delimiter1); - - while (st.hasMoreElements()) { - String token = st.nextElement().toString(); - - int index = token.indexOf(delimiter2); - - if (index == -1) { - throw new RuntimeException("Invalid URL format"); - } - - String key = token.substring(0, index); - - if (key.equalsIgnoreCase(keyToMatch)) { - return token.substring(index + delimiter2.length()); - } - } - - if (throwExceptionIfNotFound) { - throw new RuntimeException("Key not found in URL"); - } - - return null; - } - - public static String getSolidFireAccountName(String csAccountUuid, long csAccountId) { - return SF_CS_ACCOUNT_PREFIX + csAccountUuid + "_" + csAccountId; - } - - public static void updateCsDbWithSolidFireIopsInfo(long storagePoolId, PrimaryDataStoreDao primaryDataStoreDao, - StoragePoolDetailsDao storagePoolDetailsDao, long minIops, long maxIops, long burstIops) { - Map existingDetails = storagePoolDetailsDao.listDetailsKeyPairs(storagePoolId); - Set existingKeys = existingDetails.keySet(); - - Map existingDetailsToKeep = new HashMap<>(); - - for (String existingKey : existingKeys) { - String existingValue = existingDetails.get(existingKey); - - if (!SolidFireUtil.MIN_IOPS.equalsIgnoreCase(existingValue) && - !SolidFireUtil.MAX_IOPS.equalsIgnoreCase(existingValue) && - !SolidFireUtil.BURST_IOPS.equalsIgnoreCase(existingValue)) { - existingDetailsToKeep.put(existingKey, existingValue); - } - } - - existingDetailsToKeep.put(SolidFireUtil.MIN_IOPS, String.valueOf(minIops)); - existingDetailsToKeep.put(SolidFireUtil.MAX_IOPS, String.valueOf(maxIops)); - existingDetailsToKeep.put(SolidFireUtil.BURST_IOPS, String.valueOf(burstIops)); - - primaryDataStoreDao.updateDetails(storagePoolId, existingDetailsToKeep); - } - - public static void updateCsDbWithSolidFireAccountInfo(long csAccountId, SolidFireUtil.SolidFireAccount sfAccount, - long storagePoolId, AccountDetailsDao accountDetailsDao) { - AccountDetailVO accountDetail = new AccountDetailVO(csAccountId, - SolidFireUtil.getAccountKey(storagePoolId), - String.valueOf(sfAccount.getId())); - - accountDetailsDao.persist(accountDetail); - } - - public static SolidFireAccount getAccount(SolidFireConnection sfConnection, String sfAccountName) { - try { - return getAccountByName(sfConnection, sfAccountName); - } catch (Exception ex) { - return null; - } - } - - private static boolean isCloudStackOnlyVag(SolidFireConnection sfConnection, SolidFireVag sfVag) { - long[] volumeIds = sfVag.getVolumeIds(); - - if (ArrayUtils.isEmpty(volumeIds)) { - // We count this situation as being "CloudStack only" because the reason we call this method is to determine - // if we can remove a host from a VAG (we only want to allow the host to be removed from the VAG if there are - // no non-CloudStack volumes in it). - return true; - } - - List knownSfAccountsForCs = new ArrayList<>(); - - for (long volumeId : volumeIds) { - SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); - long sfAccountId = sfVolume.getAccountId(); - - if (!knownSfAccountsForCs.contains(sfAccountId)) { - SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); - - if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { - knownSfAccountsForCs.add(sfAccountId); - } - else { - return false; - } - } - } - - return true; - } - - private static boolean isStorageApplicableToZoneOrCluster(StoragePoolVO storagePoolVO, long clusterId, ClusterDao clusterDao) { - if (storagePoolVO.getClusterId() != null) { - if (storagePoolVO.getClusterId() == clusterId) { - return true; - } - } - else { - List clustersInZone = clusterDao.listClustersByDcId(storagePoolVO.getDataCenterId()); - - if (clustersInZone != null) { - for (ClusterVO clusterInZone : clustersInZone) { - if (clusterInZone.getId() == clusterId) { - return true; - } - } - } - } - - return false; - } - - public static void hostRemovedFromCluster(long hostId, long clusterId, String storageProvider, ClusterDao clusterDao, HostDao hostDao, - PrimaryDataStoreDao storagePoolDao, StoragePoolDetailsDao storagePoolDetailsDao) { - HostVO hostVO = hostDao.findByIdIncludingRemoved(hostId); - - Preconditions.checkArgument(hostVO != null, "Could not locate host for ID: " + hostId); - - ClusterVO cluster = clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(LOCK_TIME_IN_SECONDS)) { - String errMsg = "Couldn't lock the DB on the following string: " + cluster.getUuid(); - - LOGGER.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - try { - List storagePools = storagePoolDao.findPoolsByProvider(storageProvider); - - if (storagePools != null && storagePools.size() > 0) { - List sfConnections = new ArrayList<>(); - - for (StoragePoolVO storagePool : storagePools) { - if (!isStorageApplicableToZoneOrCluster(storagePool, clusterId, clusterDao)) { - continue; - } - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePool.getId(), storagePoolDetailsDao); - - if (!sfConnections.contains(sfConnection)) { - sfConnections.add(sfConnection); - - List sfVags = SolidFireUtil.getAllVags(sfConnection); - SolidFireVag sfVag = getVolumeAccessGroup(hostVO.getStorageUrl(), sfVags); - - if (sfVag != null && isCloudStackOnlyVag(sfConnection, sfVag)) { - removeInitiatorsFromSolidFireVag(sfConnection, sfVag.getId(), new String[] { hostVO.getStorageUrl() }); - } - } - } - } - } - finally { - lock.unlock(); - lock.releaseRef(); - } - } - - public static void hostAddedToCluster(long hostId, long clusterId, String storageProvider, ClusterDao clusterDao, HostDao hostDao, - PrimaryDataStoreDao storagePoolDao, StoragePoolDetailsDao storagePoolDetailsDao) { - HostVO hostVO = hostDao.findById(hostId); - - Preconditions.checkArgument(hostVO != null, "Could not locate host for ID: " + hostId); - - ClusterVO cluster = clusterDao.findById(clusterId); - - GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid()); - - if (!lock.lock(LOCK_TIME_IN_SECONDS)) { - String errMsg = "Couldn't lock the DB on the following string: " + cluster.getUuid(); - - LOGGER.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - try { - List storagePools = storagePoolDao.findPoolsByProvider(storageProvider); - - if (storagePools != null && storagePools.size() > 0) { - List sfConnections = new ArrayList<>(); - - for (StoragePoolVO storagePool : storagePools) { - if (!isStorageApplicableToZoneOrCluster(storagePool, clusterId, clusterDao)) { - continue; - } - - SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePool.getId(), storagePoolDetailsDao); - - if (!sfConnections.contains(sfConnection)) { - sfConnections.add(sfConnection); - - List sfVags = SolidFireUtil.getAllVags(sfConnection); - SolidFireVag sfVag = getVolumeAccessGroup(hostVO.getStorageUrl(), sfVags); - - if (sfVag != null) { - placeVolumeIdsInVag(sfConnection, sfVags, sfVag, hostVO, hostDao); - } else { - handleVagForHost(sfConnection, sfVags, hostVO, hostDao, clusterDao); - } - } - } - } - } - finally { - lock.unlock(); - lock.releaseRef(); - } - } - - // Put the host in an existing VAG or create a new one (only create a new one if all existing VAGs are full (i.e. 64 hosts max per VAG) and if - // creating a new VAG won't exceed 4 VAGs for the computer cluster). - // If none of the hosts in the cluster are in a VAG, then leave this host out of a VAG. - // Place applicable volume IDs in VAG, if need be (account of volume starts with SF_CS_ACCOUNT_PREFIX). - private static void handleVagForHost(SolidFireUtil.SolidFireConnection sfConnection, List sfVags, Host host, HostDao hostDao, ClusterDao clusterDao) { - List hostVOs = hostDao.findByClusterId(host.getClusterId()); - - if (hostVOs != null) { - int numVags = 0; - - addInitiatorsToExistingVag(clusterDao, host, sfVags, sfConnection); - - Collections.shuffle(hostVOs, RANDOM); - - for (HostVO hostVO : hostVOs) { - if (hostVO.getId() != host.getId()) { - SolidFireVag sfVag = getVolumeAccessGroup(hostVO.getStorageUrl(), sfVags); - - if (sfVag != null) { - numVags++; - - // A volume should be visible to all hosts that are in the same compute cluster. That being the case, you - // can use MAX_NUM_VAGS_PER_VOLUME here. This is to limit the number of VAGs being used in a compute cluster - // to MAX_NUM_VAGS_PER_VOLUME. - if (numVags > MAX_NUM_VAGS_PER_VOLUME) { - throw new CloudRuntimeException("Can support at most four volume access groups per compute cluster (>)"); - } - - if (sfVag.getInitiators().length < MAX_NUM_INITIATORS_PER_VAG) { - if (!hostSupports_iScsi(host)) { - String errMsg = String.format("Host %s does not support iSCSI.", host); - - LOGGER.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - if(!isInitiatorInSfVag(host.getStorageUrl(),sfVag)) { - addInitiatorsToSolidFireVag(sfConnection, sfVag.getId(), new String[]{host.getStorageUrl()}); - } - return; - } - } - } - } - - if (numVags == MAX_NUM_VAGS_PER_VOLUME) { - throw new CloudRuntimeException("Can support at most four volume access groups per compute cluster (==)"); - } - - if (numVags > 0) { - if (!hostSupports_iScsi(host)) { - String errMsg = String.format("Host %s does not support iSCSI.", host); - - LOGGER.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - - SolidFireUtil.createVag(sfConnection, "CloudStack-" + UUID.randomUUID().toString(), - new String[]{host.getStorageUrl()}, getVolumeIds(sfConnection, sfVags, host, hostDao)); - } - } - } - - private static void addInitiatorsToExistingVag(ClusterDao clusterDao, Host host, List sfVags, SolidFireUtil.SolidFireConnection sfConnection){ - String clusterUuId = clusterDao.findById(host.getClusterId()).getUuid(); - SolidFireVag sfVagMatchingClusterId = sfVags.stream().filter(vag -> vag.getName().equals("CloudStack-"+clusterUuId)).findFirst().orElse(null); - if (sfVagMatchingClusterId != null && sfVagMatchingClusterId.getInitiators().length < MAX_NUM_INITIATORS_PER_VAG) { - addInitiatorsToSolidFireVag(sfConnection, sfVagMatchingClusterId.getId(), new String[]{host.getStorageUrl()}); - } - } - - /** - * Make use of the volume access group (VAG) of a random host in the cluster. With this VAG, collect all of its volume IDs that are for - * volumes that are in SolidFire accounts that are for CloudStack. - */ - private static long[] getVolumeIds(SolidFireUtil.SolidFireConnection sfConnection, List sfVags, - Host host, HostDao hostDao) { - List volumeIdsToReturn = new ArrayList<>(); - - SolidFireVag sfVagForRandomHostInCluster = getVagForRandomHostInCluster(sfVags, host, hostDao); - - if (sfVagForRandomHostInCluster != null) { - long[] volumeIds = sfVagForRandomHostInCluster.getVolumeIds(); - - if (volumeIds != null) { - List knownSfAccountsForCs = new ArrayList<>(); - List knownSfAccountsNotForCs = new ArrayList<>(); - - for (long volumeId : volumeIds) { - SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); - long sfAccountId = sfVolume.getAccountId(); - - if (knownSfAccountsForCs.contains(sfAccountId)) { - volumeIdsToReturn.add(volumeId); - } - else if (!knownSfAccountsNotForCs.contains(sfAccountId)) { - SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); - - if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { - knownSfAccountsForCs.add(sfAccountId); - - volumeIdsToReturn.add(volumeId); - } - else { - knownSfAccountsNotForCs.add(sfAccountId); - } - } - } - } - } - - return volumeIdsToReturn.stream().mapToLong(l -> l).toArray(); - } - - private static void placeVolumeIdsInVag(SolidFireUtil.SolidFireConnection sfConnection, List sfVags, - SolidFireVag sfVag, Host host, HostDao hostDao) { - SolidFireVag sfVagForRandomHostInCluster = getVagForRandomHostInCluster(sfVags, host, hostDao); - - if (sfVagForRandomHostInCluster != null) { - long[] volumeIds = sfVagForRandomHostInCluster.getVolumeIds(); - - if (volumeIds != null) { - List knownSfAccountsForCs = new ArrayList<>(); - List knownSfAccountsNotForCs = new ArrayList<>(); - - List newVolumeIds = new ArrayList<>(); - - for (long volumeId : volumeIds) { - SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); - long sfAccountId = sfVolume.getAccountId(); - - if (knownSfAccountsForCs.contains(sfAccountId)) { - addVolumeIdToSolidFireVag(volumeId, sfVag, newVolumeIds); - } - else if (!knownSfAccountsNotForCs.contains(sfAccountId)) { - SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); - - if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { - knownSfAccountsForCs.add(sfAccountId); - - addVolumeIdToSolidFireVag(volumeId, sfVag, newVolumeIds); - } - else { - knownSfAccountsNotForCs.add(sfAccountId); - } - } - } - - if (newVolumeIds.size() > 0) { - addVolumeIdsToSolidFireVag(sfConnection, sfVag.getId(), newVolumeIds.toArray(new Long[0])); - } - } - } - } - - private static void addVolumeIdToSolidFireVag(long volumeId, SolidFireVag sfVag, List newVolumeIds) { - List existingVolumeIds = Longs.asList(sfVag.getVolumeIds()); - - if (!existingVolumeIds.contains(volumeId) && !newVolumeIds.contains(volumeId)) { - newVolumeIds.add(volumeId); - } - } - - private static SolidFireVag getVagForRandomHostInCluster(List sfVags, Host host, HostDao hostDao) { - List hostVOs = hostDao.findByClusterId(host.getClusterId()); - - if (hostVOs != null) { - Collections.shuffle(hostVOs, RANDOM); - - for (HostVO hostVO : hostVOs) { - if (hostVO.getId() != host.getId() && hostSupports_iScsi(hostVO)) { - SolidFireVag sfVag = getVolumeAccessGroup(hostVO.getStorageUrl(), sfVags); - - if (sfVag != null) { - return sfVag; - } - } - } - } - - return null; - } - - public static void placeVolumeInVolumeAccessGroups(SolidFireConnection sfConnection, long sfVolumeId, List hosts, String clusterUuId) { - if (!SolidFireUtil.hostsSupport_iScsi(hosts)) { - String errMsg = "Not all hosts in the compute cluster support iSCSI."; - - LOGGER.warn(errMsg); - - throw new CloudRuntimeException(errMsg); - } - List sfVags = SolidFireUtil.getAllVags(sfConnection); - Map> sfVagToIqnsMap = buildVagToIQNMap(hosts, sfVags); - if (sfVagToIqnsMap.size() > MAX_NUM_VAGS_PER_VOLUME) { - throw new CloudRuntimeException("A SolidFire volume can be in at most four volume access groups simultaneously."); - } - if (sfVagToIqnsMap.containsKey(null)) { - sfVagToIqnsMap = updateNullKeyInSfVagToIqnsMap(sfVagToIqnsMap, sfVags, sfConnection, clusterUuId, sfVolumeId); - } - addVolumestoVagIfNotPresent(sfVagToIqnsMap.keySet(), sfVolumeId, sfConnection); - } - - private static Map> updateNullKeyInSfVagToIqnsMap(Map> sfVagToIqnsMap, List sfVags, SolidFireConnection sfConnection, String clusterUuId, long sfVolumeId){ - SolidFireUtil.SolidFireVag sfVagMatchingClusterId = createClusterVagIfDoesntExist(sfVags, sfConnection, clusterUuId, sfVagToIqnsMap, sfVolumeId); - sfVagToIqnsMap.put(sfVagMatchingClusterId, sfVagToIqnsMap.get(null)); - sfVagToIqnsMap.remove(null); - return sfVagToIqnsMap; - } - - private static SolidFireVag createClusterVagIfDoesntExist(List sfVags, SolidFireConnection sfConnection, String clusterUuId, Map> sfVagToIqnsMap, long sfVolumeId) { - SolidFireVag sfVagMatchingClusterId = sfVags.stream().filter(vag -> vag.getName().equals("CloudStack-" + clusterUuId)).findFirst().orElse(null); - if (sfVagMatchingClusterId == null) { - LOGGER.info("Creating volume access group CloudStack-" + clusterUuId); - SolidFireUtil.createVag(sfConnection, "CloudStack-" + clusterUuId, sfVagToIqnsMap.get(null).toArray(new String[0]), new long[]{sfVolumeId}); - sfVags = SolidFireUtil.getAllVags(sfConnection); - return sfVags.stream().filter(vag -> vag.getName().equals("CloudStack-" + clusterUuId)).findFirst().orElse(null); - }else{ - return sfVagMatchingClusterId; - } - } - - private static void addVolumestoVagIfNotPresent(Set sfVagSet, long sfVolumeId, SolidFireConnection sfConnection){ - for (SolidFireUtil.SolidFireVag sfVag : sfVagSet) { - if (sfVag != null) { - if (!SolidFireUtil.isVolumeIdInSfVag(sfVolumeId, sfVag)) { - SolidFireUtil.addVolumeIdsToSolidFireVag(sfConnection, sfVag.getId(), new Long[] { sfVolumeId }); - } - } - } - } - - - private static Map> buildVagToIQNMap(List hosts, List sfVags) { - - Map> sfVagToIqnsMap = new HashMap<>(); - for (HostVO hostVO : hosts) { - String iqn = hostVO.getStorageUrl(); - - SolidFireUtil.SolidFireVag sfVag = getVolumeAccessGroup(iqn, sfVags); - - List iqnsInVag = sfVagToIqnsMap.computeIfAbsent(sfVag, k -> new ArrayList<>()); - - iqnsInVag.add(iqn); - } - return sfVagToIqnsMap; - - } - - public static SolidFireUtil.SolidFireVag getVolumeAccessGroup(String hostIqn, List sfVags) { - if (hostIqn == null) { - return null; - } - - hostIqn = hostIqn.toLowerCase(); - - if (sfVags != null) { - for (SolidFireUtil.SolidFireVag sfVag : sfVags) { - List lstInitiators = getStringArrayAsLowerCaseStringList(sfVag.getInitiators()); - - // lstInitiators should not be returned from getStringArrayAsLowerCaseStringList as null - if (lstInitiators.contains(hostIqn)) { - return sfVag; - } - } - } - - return null; - } - - public static boolean sfVagContains(SolidFireUtil.SolidFireVag sfVag, long sfVolumeId, long clusterId, HostDao hostDao) { - if (isVolumeIdInSfVag(sfVolumeId, sfVag)) { - String[] iqns = sfVag.getInitiators(); - List hosts = hostDao.findByClusterId(clusterId); - - for (String iqn : iqns) { - for (HostVO host : hosts) { - String hostIqn = host.getStorageUrl(); - - if (iqn.equalsIgnoreCase(hostIqn)) { - return true; - } - } - } - } - - return false; - } - - private static boolean isVolumeIdInSfVag(long sfVolumeIdToCheck, SolidFireUtil.SolidFireVag sfVag) { - long[] sfVolumeIds = sfVag.getVolumeIds(); - - for (long sfVolumeId : sfVolumeIds) { - if (sfVolumeId == sfVolumeIdToCheck) { - return true; - } - } - - return false; - } - - private static boolean isInitiatorInSfVag(String initiatorName, SolidFireUtil.SolidFireVag sfVag) { - String[] initiatorsList = sfVag.getInitiators(); - - for (String initiator : initiatorsList) { - if (initiatorName.equals(initiator)) { - return true; - } - } - - return false; - } - - private static boolean hostSupports_iScsi(Host host) { - return host != null && host.getStorageUrl() != null && host.getStorageUrl().trim().length() > 0 && host.getStorageUrl().startsWith("iqn"); - } - - private static boolean hostsSupport_iScsi(List hosts) { - if (hosts == null || hosts.size() == 0) { - return false; - } - - for (Host host : hosts) { - if (!hostSupports_iScsi(host)) { - return false; - } - } - - return true; - } - - public static String getVagKey(long storagePoolId) { - return "sfVolumeAccessGroup_" + storagePoolId; - } - - public static String getAccountKey(long storagePoolId) { - return SolidFireUtil.ACCOUNT_ID + "_" + storagePoolId; - } - - public static AccountDetailVO getAccountDetail(long csAccountId, long storagePoolId, AccountDetailsDao accountDetailsDao) { - AccountDetailVO accountDetail = accountDetailsDao.findDetail(csAccountId, SolidFireUtil.getAccountKey(storagePoolId)); - - if (accountDetail == null || accountDetail.getValue() == null) { - accountDetail = accountDetailsDao.findDetail(csAccountId, SolidFireUtil.ACCOUNT_ID); - } - - return accountDetail; - } - - public static String getSolidFireVolumeName(String strCloudStackVolumeName) { - final String specialChar = "-"; - - StringBuilder strSolidFireVolumeName = new StringBuilder(); - - for (int i = 0; i < strCloudStackVolumeName.length(); i++) { - String strChar = strCloudStackVolumeName.substring(i, i + 1); - - if (StringUtils.isAlphanumeric(strChar)) { - strSolidFireVolumeName.append(strChar); - } else { - strSolidFireVolumeName.append(specialChar); - } - } - - return strSolidFireVolumeName.toString(); - } - - public static long createVolume(SolidFireConnection sfConnection, String volumeName, long accountId, long totalSize, - boolean enable512e, Map mapAttributes, long minIops, long maxIops, long burstIops) { - CreateVolumeRequest request = CreateVolumeRequest.builder() - .name(volumeName) - .accountID(accountId) - .totalSize(totalSize) - .enable512e(enable512e) - .optionalAttributes(convertMap(mapAttributes)) - .optionalQos(new QoS(Optional.of(minIops), Optional.of(maxIops), Optional.of(burstIops), Optional.EMPTY_LONG)) - .build(); - - return getSolidFireElement(sfConnection).createVolume(request).getVolumeID(); - } - - public static void modifyVolume(SolidFireConnection sfConnection, long volumeId, Long totalSize, Map mapAttributes, - long minIops, long maxIops, long burstIops) { - ModifyVolumeRequest request = ModifyVolumeRequest.builder() - .volumeID(volumeId) - .optionalTotalSize(totalSize) - .optionalAttributes(convertMap(mapAttributes)) - .optionalQos(new QoS(Optional.of(minIops), Optional.of(maxIops), Optional.of(burstIops), Optional.EMPTY_LONG)) - .build(); - - getSolidFireElement(sfConnection).modifyVolume(request); - } - - public static void modifyVolumeQoS(SolidFireConnection sfConnection, long volumeId, long minIops, long maxIops, long burstIops) { - ModifyVolumeRequest request = ModifyVolumeRequest.builder() - .volumeID(volumeId) - .optionalQos(new QoS(Optional.of(minIops), Optional.of(maxIops), Optional.of(burstIops), Optional.EMPTY_LONG)) - .build(); - - getSolidFireElement(sfConnection).modifyVolume(request); - } - - public static SolidFireVolume getVolume(SolidFireConnection sfConnection, long volumeId) { - ListVolumesRequest request = ListVolumesRequest.builder() - .optionalStartVolumeID(volumeId) - .optionalLimit(1L) - .build(); - - Volume volume = getSolidFireElement(sfConnection).listVolumes(request).getVolumes()[0]; - - return new SolidFireVolume(volume.getVolumeID(), volume.getName(), volume.getIqn(), volume.getAccountID(), volume.getStatus(), - volume.getEnable512e(), volume.getQos().getMinIOPS(), volume.getQos().getMaxIOPS(), volume.getQos().getBurstIOPS(), - volume.getTotalSize(), volume.getScsiNAADeviceID()); - } - - public static void deleteVolume(SolidFireConnection sfConnection, long volumeId) { - DeleteVolumeRequest request = DeleteVolumeRequest.builder() - .volumeID(volumeId) - .build(); - - getSolidFireElement(sfConnection).deleteVolume(request); - } - - private static final String ACTIVE = "active"; - - public static class SolidFireVolume { - private final long _id; - private final String _name; - private final String _iqn; - private final long _accountId; - private final String _status; - private final boolean _enable512e; - private final long _minIops; - private final long _maxIops; - private final long _burstIops; - private final long _totalSize; - private final String _scsiNaaDeviceId; - - SolidFireVolume(long id, String name, String iqn, long accountId, String status, boolean enable512e, - long minIops, long maxIops, long burstIops, long totalSize, String scsiNaaDeviceId) { - _id = id; - _name = name; - _iqn = "/" + iqn + "/0"; - _accountId = accountId; - _status = status; - _enable512e = enable512e; - _minIops = minIops; - _maxIops = maxIops; - _burstIops = burstIops; - _totalSize = totalSize; - _scsiNaaDeviceId = scsiNaaDeviceId; - } - - public long getId() { - return _id; - } - - public String getName() { - return _name; - } - - public String getIqn() { - return _iqn; - } - - public long getAccountId() { - return _accountId; - } - - public boolean isActive() { - return ACTIVE.equalsIgnoreCase(_status); - } - - public boolean isEnable512e() { - return _enable512e; - } - - public long getMinIops() { - return _minIops; - } - - public long getMaxIops() { - return _maxIops; - } - - public long getBurstIops() { - return _burstIops; - } - - public long getTotalSize() { - return _totalSize; - } - - public String getScsiNaaDeviceId() { - return _scsiNaaDeviceId; - } - - @Override - public int hashCode() { - return _iqn.hashCode(); - } - - @Override - public String toString() { - return _name; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!obj.getClass().equals(SolidFireVolume.class)) { - return false; - } - - SolidFireVolume sfv = (SolidFireVolume)obj; - - return _id == sfv._id && _name.equals(sfv._name) && _iqn.equals(sfv._iqn) && _accountId == sfv._accountId && - isActive() == sfv.isActive() && getTotalSize() == sfv.getTotalSize(); - } - } - - public static long createSnapshot(SolidFireConnection sfConnection, long volumeId, String snapshotName, Map mapAttributes) { - CreateSnapshotRequest request = CreateSnapshotRequest.builder() - .volumeID(volumeId) - .optionalName(snapshotName) - .optionalAttributes(convertMap(mapAttributes)) - .build(); - - return getSolidFireElement(sfConnection).createSnapshot(request).getSnapshotID(); - } - - public static SolidFireSnapshot getSnapshot(SolidFireConnection sfConnection, long volumeId, long snapshotId) { - ListSnapshotsRequest request = ListSnapshotsRequest.builder() - .optionalVolumeID(volumeId) - .build(); - - Snapshot[] snapshots = getSolidFireElement(sfConnection).listSnapshots(request).getSnapshots(); - - String snapshotName = null; - long totalSize = 0; - - if (snapshots != null) { - for (Snapshot snapshot : snapshots) { - if (snapshot.getSnapshotID() == snapshotId) { - snapshotName = snapshot.getName(); - totalSize = snapshot.getTotalSize(); - - break; - } - } - } - - if (snapshotName == null) { - throw new CloudRuntimeException("Could not find SolidFire Snapshot ID: " + snapshotId + " for the following SolidFire volume ID: " + volumeId); - } - - return new SolidFireSnapshot(snapshotId, snapshotName, totalSize); - } - - public static void deleteSnapshot(SolidFireConnection sfConnection, long snapshotId) { - DeleteSnapshotRequest request = DeleteSnapshotRequest.builder() - .snapshotID(snapshotId) - .build(); - - getSolidFireElement(sfConnection).deleteSnapshot(request); - } - - public static void rollBackVolumeToSnapshot(SolidFireConnection sfConnection, long volumeId, long snapshotId) { - RollbackToSnapshotRequest request = RollbackToSnapshotRequest.builder() - .volumeID(volumeId) - .snapshotID(snapshotId) - .build(); - - getSolidFireElement(sfConnection).rollbackToSnapshot(request); - } - - public static class SolidFireSnapshot { - private final long _id; - private final String _name; - private final long _totalSize; - - SolidFireSnapshot(long id, String name, long totalSize) { - _id = id; - _name = name; - _totalSize = totalSize; - } - - public long getId() { - return _id; - } - - public String getName() { - return _name; - } - - public long getTotalSize() { - return _totalSize; - } - } - - public static long createClone(SolidFireConnection sfConnection, long volumeId, long snapshotId, long accountId, - String cloneName, Map mapAttributes) { - CloneVolumeRequest request = CloneVolumeRequest.builder() - .volumeID(volumeId) - .optionalSnapshotID(snapshotId < 1 ? null : snapshotId) - .optionalNewAccountID(accountId) - .name(cloneName) - .optionalAttributes(convertMap(mapAttributes)) - .build(); - - CloneVolumeResult result = getSolidFireElement(sfConnection).cloneVolume(request); - - // Clone is an async operation. Poll until we get data. - - GetAsyncResultRequest asyncResultRequest = GetAsyncResultRequest.builder() - .asyncHandle(result.getAsyncHandle()) - .build(); - - do { - String status = getSolidFireElement(sfConnection).getAsyncResult(asyncResultRequest).getStatus(); - - if (status.equals("complete")) { - break; - } - - try { - Thread.sleep(500); // sleep for 1/2 of a second - } - catch (Exception ex) { - // ignore - } - } - while (true); - - return result.getVolumeID(); - } - - public static long createAccount(SolidFireConnection sfConnection, String accountName) { - AddAccountRequest request = AddAccountRequest.builder() - .username(accountName) - .build(); - - return getSolidFireElement(sfConnection).addAccount(request).getAccountID(); - } - - public static SolidFireAccount getAccountById(SolidFireConnection sfConnection, long accountId) { - GetAccountByIDRequest request = GetAccountByIDRequest.builder() - .accountID(accountId) - .build(); - - Account sfAccount = getSolidFireElement(sfConnection).getAccountByID(request).getAccount(); - - String sfAccountName = sfAccount.getUsername(); - String sfAccountInitiatorSecret = sfAccount.getInitiatorSecret().isPresent() ? sfAccount.getInitiatorSecret().get().toString() : ""; - String sfAccountTargetSecret = sfAccount.getTargetSecret().isPresent() ? sfAccount.getTargetSecret().get().toString() : ""; - - return new SolidFireAccount(accountId, sfAccountName, sfAccountInitiatorSecret, sfAccountTargetSecret); - } - - private static SolidFireAccount getAccountByName(SolidFireConnection sfConnection, String accountName) { - GetAccountByNameRequest request = GetAccountByNameRequest.builder() - .username(accountName) - .build(); - - Account sfAccount = getSolidFireElement(sfConnection).getAccountByName(request).getAccount(); - - long sfAccountId = sfAccount.getAccountID(); - String sfAccountInitiatorSecret = sfAccount.getInitiatorSecret().isPresent() ? sfAccount.getInitiatorSecret().get().toString() : ""; - String sfAccountTargetSecret = sfAccount.getTargetSecret().isPresent() ? sfAccount.getTargetSecret().get().toString() : ""; - - return new SolidFireAccount(sfAccountId, accountName, sfAccountInitiatorSecret, sfAccountTargetSecret); - } - - public static class SolidFireAccount { - private final long _id; - private final String _name; - private final String _initiatorSecret; - private final String _targetSecret; - - SolidFireAccount(long id, String name, String initiatorSecret, String targetSecret) { - _id = id; - _name = name; - _initiatorSecret = initiatorSecret; - _targetSecret = targetSecret; - } - - public long getId() { - return _id; - } - - public String getName() { - return _name; - } - - @Override - public int hashCode() { - return (_id + _name).hashCode(); - } - - @Override - public String toString() { - return _name; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!obj.getClass().equals(SolidFireAccount.class)) { - return false; - } - - SolidFireAccount sfa = (SolidFireAccount)obj; - - return _id == sfa._id && _name.equals(sfa._name) && - _initiatorSecret.equals(sfa._initiatorSecret) && - _targetSecret.equals(sfa._targetSecret); - } - } - - private static long createVag(SolidFireConnection sfConnection, String vagName, String[] iqns, long[] volumeIds) { - CreateVolumeAccessGroupRequest request = CreateVolumeAccessGroupRequest.builder() - .name(vagName) - .optionalInitiators(iqns) - .optionalVolumes(Longs.asList(volumeIds).toArray(new Long[volumeIds.length])) - .build(); - - return getSolidFireElement(sfConnection).createVolumeAccessGroup(request).getVolumeAccessGroupID(); - } - - private static void addInitiatorsToSolidFireVag(SolidFireConnection sfConnection, long vagId, String[] initiators) { - AddInitiatorsToVolumeAccessGroupRequest request = AddInitiatorsToVolumeAccessGroupRequest.builder() - .volumeAccessGroupID(vagId) - .initiators(initiators) - .build(); - - getSolidFireElement(sfConnection).addInitiatorsToVolumeAccessGroup(request); - } - - private static void removeInitiatorsFromSolidFireVag(SolidFireConnection sfConnection, long vagId, String[] initiators) { - RemoveInitiatorsFromVolumeAccessGroupRequest request = RemoveInitiatorsFromVolumeAccessGroupRequest.builder() - .volumeAccessGroupID(vagId) - .initiators(initiators) - .build(); - - getSolidFireElement(sfConnection).removeInitiatorsFromVolumeAccessGroup(request); - } - - private static void addVolumeIdsToSolidFireVag(SolidFireConnection sfConnection, long vagId, Long[] volumeIds) { - AddVolumesToVolumeAccessGroupRequest request = AddVolumesToVolumeAccessGroupRequest.builder() - .volumeAccessGroupID(vagId) - .volumes(volumeIds) - .build(); - - getSolidFireElement(sfConnection).addVolumesToVolumeAccessGroup(request); - } - - public static void removeVolumeIdsFromSolidFireVag(SolidFireConnection sfConnection, long vagId, Long[] volumeIds) { - RemoveVolumesFromVolumeAccessGroupRequest request = RemoveVolumesFromVolumeAccessGroupRequest.builder() - .volumeAccessGroupID(vagId) - .volumes(volumeIds) - .build(); - - getSolidFireElement(sfConnection).removeVolumesFromVolumeAccessGroup(request); - } - - public static List getAllVags(SolidFireConnection sfConnection) - { - ListVolumeAccessGroupsRequest request = ListVolumeAccessGroupsRequest.builder().build(); - - VolumeAccessGroup[] vags = getSolidFireElement(sfConnection).listVolumeAccessGroups(request).getVolumeAccessGroups(); - - List lstSolidFireVags = new ArrayList<>(); - - if (vags != null) { - for (VolumeAccessGroup vag : vags) { - SolidFireVag sfVag = new SolidFireVag(vag.getVolumeAccessGroupID(), vag.getInitiators(), toPrimitive(vag.getVolumes()), vag.getName()); - - lstSolidFireVags.add(sfVag); - } - } - - return lstSolidFireVags; - } - - public static class SolidFireVag { - private final long _id; - private final String[] _initiators; - private final long[] _volumeIds; - private final String _vagName; - - SolidFireVag(long id, String[] initiators, long[] volumeIds, String name) { - _id = id; - _initiators = initiators; - _volumeIds = volumeIds; - _vagName = name; - } - - public long getId() { - return _id; - } - - public String[] getInitiators() { - return _initiators; - } - - public long[] getVolumeIds() { - return _volumeIds; - } - - public String getName() { return _vagName; } - - @Override - public int hashCode() { - return String.valueOf(_id).hashCode(); - } - - @Override - public String toString() { - return String.valueOf(_id); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!obj.getClass().equals(SolidFireVag.class)) { - return false; - } - - SolidFireVag sfVag = (SolidFireVag)obj; - - return _id == sfVag._id; - } - } - - private static String getVip(String keyToMatch, String url) { - String delimiter = ":"; - - String storageVip = getValue(keyToMatch, url); - - int index = storageVip.indexOf(delimiter); - - if (index != -1) { - return storageVip.substring(0, index); - } - - return storageVip; - } - - private static int getPort(String keyToMatch, String url, int defaultPortNumber) { - String delimiter = ":"; - - String storageVip = getValue(keyToMatch, url); - - int index = storageVip.indexOf(delimiter); - - int portNumber = defaultPortNumber; - - if (index != -1) { - String port = storageVip.substring(index + delimiter.length()); - - try { - portNumber = Integer.parseInt(port); - } catch (NumberFormatException ex) { - throw new IllegalArgumentException("Invalid URL format (port is not an integer)"); - } - } - - return portNumber; - } - - private static List getStringArrayAsLowerCaseStringList(String[] aString) { - List lstLowerCaseString = new ArrayList<>(); - - if (aString != null) { - for (String str : aString) { - if (str != null) { - lstLowerCaseString.add(str.toLowerCase()); - } - } - } - - return lstLowerCaseString; - } - - private static Map convertMap(Map map) { - if (map == null) { - return null; - } - - return new HashMap<>(map); - } -} diff --git a/plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/module.properties b/plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/module.properties deleted file mode 100644 index 72b2e03f8989..000000000000 --- a/plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=storage-volume-solidfire -parent=storage diff --git a/plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/spring-storage-volume-solidfire-context.xml b/plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/spring-storage-volume-solidfire-context.xml deleted file mode 100644 index 65fdfe738d66..000000000000 --- a/plugins/storage/volume/solidfire/src/main/resources/META-INF/cloudstack/storage-volume-solidfire/spring-storage-volume-solidfire-context.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - diff --git a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/AopTestAdvice.java b/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/AopTestAdvice.java deleted file mode 100644 index 233b0461150d..000000000000 --- a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/AopTestAdvice.java +++ /dev/null @@ -1,34 +0,0 @@ -// 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 org.apache.cloudstack.storage.test; - -import org.aspectj.lang.ProceedingJoinPoint; - -import com.cloud.utils.db.TransactionLegacy; - -public class AopTestAdvice { - public Object AopTestMethod(ProceedingJoinPoint call) throws Throwable { - TransactionLegacy txn = TransactionLegacy.open(call.getSignature().getName()); - Object ret = null; - try { - ret = call.proceed(); - } finally { - txn.close(); - } - return ret; - } -} diff --git a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/ChildTestConfiguration.java b/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/ChildTestConfiguration.java deleted file mode 100644 index 1d7d60550ee6..000000000000 --- a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/ChildTestConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -// 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 org.apache.cloudstack.storage.test; - -import org.mockito.Mockito; -import org.springframework.context.annotation.Bean; - -import org.apache.cloudstack.storage.image.motion.ImageMotionService; - -import com.cloud.agent.AgentManager; -import com.cloud.host.dao.HostDao; - -public class ChildTestConfiguration extends TestConfiguration { - - @Override - @Bean - public HostDao hostDao() { - HostDao dao = super.hostDao(); - HostDao nDao = Mockito.spy(dao); - return nDao; - } - - @Bean - public AgentManager agentMgr() { - return Mockito.mock(AgentManager.class); - } - - @Bean - public ImageMotionService imageMotion() { - return Mockito.mock(ImageMotionService.class); - } - - /* - * @Override - * - * @Bean public PrimaryDataStoreDao primaryDataStoreDao() { return - * Mockito.mock(PrimaryDataStoreDaoImpl.class); } - */ -} diff --git a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/TestConfiguration.java b/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/TestConfiguration.java deleted file mode 100644 index db1c3ce2008b..000000000000 --- a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/TestConfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -// 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 org.apache.cloudstack.storage.test; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl; - -import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDaoImpl; - -@Configuration -public class TestConfiguration { - @Bean - public HostDao hostDao() { - return new HostDaoImpl(); - } - - @Bean - public PrimaryDataStoreDao primaryDataStoreDao() { - return new PrimaryDataStoreDaoImpl(); - } -} diff --git a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/VolumeTest.java b/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/VolumeTest.java deleted file mode 100644 index d721412b3ec1..000000000000 --- a/plugins/storage/volume/solidfire/src/test/java/org/apache/cloudstack/storage/test/VolumeTest.java +++ /dev/null @@ -1,129 +0,0 @@ -// 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 org.apache.cloudstack.storage.test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.inject.Inject; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.mockito.Mockito; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; - -import com.cloud.agent.AgentManager; -import com.cloud.dc.ClusterVO; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.HostPodVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.host.Host; -import com.cloud.host.HostVO; -import com.cloud.host.dao.HostDao; -import com.cloud.hypervisor.Hypervisor.HypervisorType; -import com.cloud.org.Cluster.ClusterType; -import com.cloud.org.Managed.ManagedState; -import com.cloud.resource.ResourceState; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "classpath:/resource/storageContext.xml") -public class VolumeTest { - @Inject - HostDao hostDao; - @Inject - HostPodDao podDao; - @Inject - ClusterDao clusterDao; - @Inject - DataCenterDao dcDao; - @Inject - PrimaryDataStoreDao primaryStoreDao; - @Inject - AgentManager agentMgr; - Long dcId; - Long clusterId; - - @Before - public void setUp() { - // create data center - DataCenterVO dc = - new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, - true, null, null); - dc = dcDao.persist(dc); - dcId = dc.getId(); - // create pod - - HostPodVO pod = new HostPodVO(UUID.randomUUID().toString(), dc.getId(), "192.168.56.1", "192.168.56.0/24", 8, "test"); - pod = podDao.persist(pod); - // create xen cluster - ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster"); - cluster.setHypervisorType(HypervisorType.XenServer.toString()); - cluster.setClusterType(ClusterType.CloudManaged); - cluster.setManagedState(ManagedState.Managed); - cluster = clusterDao.persist(cluster); - clusterId = cluster.getId(); - // create xen host - - HostVO host = new HostVO(UUID.randomUUID().toString()); - host.setName("devcloud xen host"); - host.setType(Host.Type.Routing); - host.setPrivateIpAddress("192.168.56.2"); - host.setDataCenterId(dc.getId()); - host.setVersion("6.0.1"); - host.setAvailable(true); - host.setSetup(true); - host.setLastPinged(0); - host.setResourceState(ResourceState.Enabled); - host.setClusterId(cluster.getId()); - - host = hostDao.persist(host); - List results = new ArrayList(); - results.add(host); - Mockito.when(hostDao.listAll()).thenReturn(results); - Mockito.when(hostDao.findHypervisorHostInCluster(ArgumentMatchers.anyLong())).thenReturn(results); - } - - private PrimaryDataStoreInfo createPrimaryDataStore() { - try { - Map params = new HashMap(); - params.put("url", "nfs://test/test"); - params.put("dcId", dcId.toString()); - params.put("clusterId", clusterId.toString()); - params.put("name", "my primary data store"); - return null; - } catch (Exception e) { - return null; - } - } - - @Test - public void createPrimaryDataStoreTest() { - createPrimaryDataStore(); - } -} diff --git a/plugins/storage/volume/solidfire/src/test/resource/storageContext.xml b/plugins/storage/volume/solidfire/src/test/resource/storageContext.xml deleted file mode 100644 index df4fb385c2f2..000000000000 --- a/plugins/storage/volume/solidfire/src/test/resource/storageContext.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/user-authenticators/md5/pom.xml b/plugins/user-authenticators/md5/pom.xml deleted file mode 100644 index f0f998c42c16..000000000000 --- a/plugins/user-authenticators/md5/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - cloud-plugin-user-authenticator-md5 - Apache CloudStack Plugin - User Authenticator MD5 - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - diff --git a/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java deleted file mode 100644 index 7286f57d0488..000000000000 --- a/plugins/user-authenticators/md5/src/main/java/org/apache/cloudstack/auth/MD5UserAuthenticator.java +++ /dev/null @@ -1,86 +0,0 @@ -// 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 org.apache.cloudstack.auth; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.commons.lang3.StringUtils; - -import com.cloud.user.UserAccount; -import com.cloud.user.dao.UserAccountDao; -import com.cloud.utils.Pair; -import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.exception.CloudRuntimeException; - -/** - * Simple UserAuthenticator that performs a MD5 hash of the password before - * comparing it against the local database. - * - */ -public class MD5UserAuthenticator extends AdapterBase implements UserAuthenticator { - - @Inject - private UserAccountDao _userAccountDao; - - @Override - public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (logger.isDebugEnabled()) { - logger.debug("Retrieving user: " + username); - } - - if (StringUtils.isAnyEmpty(username, password)) { - logger.debug("Username or Password cannot be empty"); - return new Pair<>(false, null); - } - - UserAccount user = _userAccountDao.getUserAccount(username, domainId); - if (user == null) { - logger.debug("Unable to find user with " + username + " in domain " + domainId); - return new Pair<>(false, null); - } - - if (!user.getPassword().equals(encode(password))) { - logger.debug("Password does not match"); - return new Pair<>(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); - } - return new Pair<>(true, null); - } - - @Override - public String encode(final String password) { - try { - final MessageDigest md5 = MessageDigest.getInstance("MD5"); - md5.reset(); - BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); - String pwStr = pwInt.toString(16); - int padding = 32 - pwStr.length(); - StringBuilder sb = new StringBuilder(32); - for (int i = 0; i < padding; i++) { - sb.append('0'); // make sure the MD5 password is 32 digits long - } - sb.append(pwStr); - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - throw new CloudRuntimeException("Unable to hash password", e); - } - - } -} diff --git a/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/module.properties b/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/module.properties deleted file mode 100644 index c79f1b6ebb31..000000000000 --- a/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=md5 -parent=api diff --git a/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml b/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml deleted file mode 100644 index a447e7317437..000000000000 --- a/plugins/user-authenticators/md5/src/main/resources/META-INF/cloudstack/md5/spring-md5-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java b/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java deleted file mode 100644 index ad86b16f39e8..000000000000 --- a/plugins/user-authenticators/md5/src/test/java/org/apache/cloudstack/auth/MD5UserAuthenticatorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 org.apache.cloudstack.auth; - -import java.lang.reflect.Field; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; - -import com.cloud.user.UserAccountVO; -import com.cloud.user.dao.UserAccountDao; -import com.cloud.utils.Pair; - -@RunWith(MockitoJUnitRunner.class) -public class MD5UserAuthenticatorTest { - @Mock - UserAccountDao dao; - - @Test - public void encode() { - Assert.assertEquals("5f4dcc3b5aa765d61d8327deb882cf99", - new MD5UserAuthenticator().encode("password")); - } - - @Test - public void authenticate() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - MD5UserAuthenticator authenticator = new MD5UserAuthenticator(); - Field daoField = MD5UserAuthenticator.class.getDeclaredField("_userAccountDao"); - daoField.setAccessible(true); - daoField.set(authenticator, dao); - UserAccountVO account = new UserAccountVO(); - account.setPassword("5f4dcc3b5aa765d61d8327deb882cf99"); - Mockito.when(dao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(account); - Pair pair = authenticator.authenticate("admin", "password", 1l, null); - Assert.assertTrue(pair.first()); - } - - @Test - public void authenticateBadPass() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - MD5UserAuthenticator authenticator = new MD5UserAuthenticator(); - Field daoField = MD5UserAuthenticator.class.getDeclaredField("_userAccountDao"); - daoField.setAccessible(true); - daoField.set(authenticator, dao); - UserAccountVO account = new UserAccountVO(); - account.setPassword("surprise"); - Mockito.when(dao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(account); - Pair pair = authenticator.authenticate("admin", "password", 1l, null); - Assert.assertFalse(pair.first()); - } - - @Test - public void authenticateBadUser() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { - MD5UserAuthenticator authenticator = new MD5UserAuthenticator(); - Field daoField = MD5UserAuthenticator.class.getDeclaredField("_userAccountDao"); - daoField.setAccessible(true); - daoField.set(authenticator, dao); - Mockito.when(dao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(null); - Pair pair = authenticator.authenticate("admin", "password", 1l, null); - Assert.assertFalse(pair.first()); - } -} diff --git a/plugins/user-authenticators/plain-text/pom.xml b/plugins/user-authenticators/plain-text/pom.xml deleted file mode 100644 index 54a9650b64ff..000000000000 --- a/plugins/user-authenticators/plain-text/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - cloud-plugin-user-authenticator-plaintext - Apache CloudStack Plugin - User Authenticator Plain Text - - org.apache.cloudstack - cloudstack-plugins - 4.23.0.0-SNAPSHOT - ../../pom.xml - - diff --git a/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java b/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java deleted file mode 100644 index 4e3d402222e7..000000000000 --- a/plugins/user-authenticators/plain-text/src/main/java/org/apache/cloudstack/auth/PlainTextUserAuthenticator.java +++ /dev/null @@ -1,63 +0,0 @@ -// 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 org.apache.cloudstack.auth; - -import java.util.Map; - -import javax.inject.Inject; - -import org.apache.commons.lang3.StringUtils; - -import com.cloud.user.UserAccount; -import com.cloud.user.dao.UserAccountDao; -import com.cloud.utils.Pair; -import com.cloud.utils.component.AdapterBase; - -public class PlainTextUserAuthenticator extends AdapterBase implements UserAuthenticator { - - @Inject - private UserAccountDao _userAccountDao; - - @Override - public Pair authenticate(String username, String password, Long domainId, Map requestParameters) { - if (logger.isDebugEnabled()) { - logger.debug("Retrieving user: " + username); - } - - if (StringUtils.isAnyEmpty(username, password)) { - logger.debug("Username or Password cannot be empty"); - return new Pair<>(false, null); - } - - UserAccount user = _userAccountDao.getUserAccount(username, domainId); - if (user == null) { - logger.debug("Unable to find user with " + username + " in domain " + domainId); - return new Pair<>(false, null); - } - - if (!user.getPassword().equals(password)) { - logger.debug("Password does not match"); - return new Pair<>(false, ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT); - } - return new Pair<>(true, null); - } - - @Override - public String encode(String password) { - // Plaintext so no encoding at all - return password; - } -} diff --git a/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/module.properties b/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/module.properties deleted file mode 100644 index 1ff77da2a36e..000000000000 --- a/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# 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. -name=plaintext -parent=api diff --git a/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml b/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml deleted file mode 100644 index 0b22b010e191..000000000000 --- a/plugins/user-authenticators/plain-text/src/main/resources/META-INF/cloudstack/plaintext/spring-plaintext-context.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - diff --git a/pom.xml b/pom.xml index 17935c526922..880e6d3c7282 100644 --- a/pom.xml +++ b/pom.xml @@ -138,7 +138,6 @@ 9.2.0 3.2.14 2.6.11 - 0.0.27 3.0.2 1.42.3 2.4.17 @@ -312,11 +311,6 @@ ${cs.jackson.version} bundle - - com.globo.globodns - globodns-client - ${cs.globodns-client.version} - com.google.code.gson gson diff --git a/quickcloud/pom.xml b/quickcloud/pom.xml deleted file mode 100644 index cc0bacbd7e77..000000000000 --- a/quickcloud/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - cloud-quickcloud - Apache CloudStack Framework - QuickCloud - - org.apache.cloudstack - cloudstack - 4.23.0.0-SNAPSHOT - ../pom.xml - - diff --git a/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml b/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml deleted file mode 100644 index a434bbe24127..000000000000 --- a/quickcloud/src/main/resources/META-INF/cloudstack/core/spring-quickcloud-core-context-override.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - diff --git a/server/src/main/java/com/cloud/api/ApiResponseHelper.java b/server/src/main/java/com/cloud/api/ApiResponseHelper.java index a8551b4c6693..7593c3cc9647 100644 --- a/server/src/main/java/com/cloud/api/ApiResponseHelper.java +++ b/server/src/main/java/com/cloud/api/ApiResponseHelper.java @@ -3334,7 +3334,6 @@ public TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType response.setKvmLabel(result.getKvmNetworkLabel()); response.setVmwareLabel(result.getVmwareNetworkLabel()); response.setHypervLabel(result.getHypervNetworkLabel()); - response.setOvm3Label(result.getOvm3NetworkLabel()); response.setVlan(result.getVlan()); response.setObjectName("traffictype"); diff --git a/server/src/main/java/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/main/java/com/cloud/api/doc/ApiXmlDocWriter.java index 87d88df79e3b..7d7390688079 100644 --- a/server/src/main/java/com/cloud/api/doc/ApiXmlDocWriter.java +++ b/server/src/main/java/com/cloud/api/doc/ApiXmlDocWriter.java @@ -89,8 +89,8 @@ private static List setAsyncResponses() { public static void main(String[] args) { Set> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, new String[] {"org.apache.cloudstack.api", "com.cloud.api", - "com.cloud.api.commands", "com.globo.globodns.cloudstack.api", "org.apache.cloudstack.network.opendaylight.api", - "org.apache.cloudstack.api.command.admin.zone", "org.apache.cloudstack.network.contrail.api.command"}); + "com.cloud.api.commands", "org.apache.cloudstack.network.opendaylight.api", + "org.apache.cloudstack.api.command.admin.zone"}); for (Class cmdClass : cmdClasses) { if(cmdClass.getAnnotation(APICommand.class)==null){ diff --git a/server/src/main/java/com/cloud/configuration/Config.java b/server/src/main/java/com/cloud/configuration/Config.java index a82ccb33a4a3..ae0d9013b12e 100644 --- a/server/src/main/java/com/cloud/configuration/Config.java +++ b/server/src/main/java/com/cloud/configuration/Config.java @@ -557,7 +557,7 @@ public enum Config { String.class, "hypervisor.list", HypervisorType.KVM + "," + HypervisorType.VMware + "," + HypervisorType.XenServer + "," + HypervisorType.Hyperv + "," + - HypervisorType.BareMetal + "," + HypervisorType.Ovm + "," + HypervisorType.LXC + "," + HypervisorType.Ovm3 + "," + HypervisorType.External, + HypervisorType.BareMetal + "," + HypervisorType.LXC + "," + HypervisorType.External, "The list of hypervisors that this deployment will use.", "hypervisorList", ConfigKey.Kind.CSV, @@ -893,33 +893,6 @@ public enum Config { "5", "Incorrect login attempts allowed before the user is disabled (when value > 0). If value <=0 users are not disabled after failed login attempts", null), - // Ovm - OvmPublicNetwork("Hidden", ManagementServer.class, String.class, "ovm.public.network.device", null, "Specify the public bridge on host for public network", null), - OvmPrivateNetwork("Hidden", ManagementServer.class, String.class, "ovm.private.network.device", null, "Specify the private bridge on host for private network", null), - OvmGuestNetwork("Hidden", ManagementServer.class, String.class, "ovm.guest.network.device", null, "Specify the private bridge on host for private network", null), - - // Ovm3 - Ovm3PublicNetwork("Hidden", ManagementServer.class, String.class, "ovm3.public.network.device", null, "Specify the public bridge on host for public network", null), - Ovm3PrivateNetwork("Hidden", ManagementServer.class, String.class, "ovm3.private.network.device", null, "Specify the private bridge on host for private network", null), - Ovm3GuestNetwork("Hidden", ManagementServer.class, String.class, "ovm3.guest.network.device", null, "Specify the guest bridge on host for guest network", null), - Ovm3StorageNetwork("Hidden", ManagementServer.class, String.class, "ovm3.storage.network.device", null, "Specify the storage bridge on host for storage network", null), - Ovm3HeartBeatTimeout( - "Advanced", - ManagementServer.class, - Integer.class, - "ovm3.heartbeat.timeout", - "120", - "timeout used for primary storage check, upon timeout a panic is triggered.", - null), - Ovm3HeartBeatInterval( - "Advanced", - ManagementServer.class, - Integer.class, - "ovm3.heartbeat.interval", - "1", - "interval used to check primary storage availability.", - null), - // XenServer XenServerPublicNetwork( diff --git a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java index 6da5dda967d0..430a43514089 100644 --- a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java @@ -563,7 +563,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati private static final String DefaultForSystemVmsForPodIpRange = "0"; private static final String DefaultVlanForPodIpRange = Vlan.UNTAGGED; - private static final Set VPC_ONLY_PROVIDERS = Sets.newHashSet(Provider.VPCVirtualRouter, Provider.JuniperContrailVpcRouter, Provider.InternalLbVm); + private static final Set VPC_ONLY_PROVIDERS = Sets.newHashSet(Provider.VPCVirtualRouter, Provider.InternalLbVm); private static final List SUPPORTED_ROUTING_MODE_STRS = Arrays.asList(Static.toString().toLowerCase(), Dynamic.toString().toLowerCase()); private static final long GiB_TO_BYTES = 1024 * 1024 * 1024; @@ -604,8 +604,6 @@ protected void populateConfigValuesForValidationSet() { configValuesForValidation.add("wait"); configValuesForValidation.add("xenserver.heartbeat.interval"); configValuesForValidation.add("xenserver.heartbeat.timeout"); - configValuesForValidation.add("ovm3.heartbeat.interval"); - configValuesForValidation.add("ovm3.heartbeat.timeout"); configValuesForValidation.add("incorrect.login.attempts.allowed"); configValuesForValidation.add("vm.password.length"); configValuesForValidation.add("externaldhcp.vmip.retrieval.interval"); @@ -1700,7 +1698,7 @@ protected String validateRangePrivateIp(String name, String value) { } /** - * Valid values are XenServer, KVM, VMware, Hyperv, VirtualBox, Parralels, BareMetal, Simulator, Ovm, Ovm3, LXC. + * Valid values are XenServer, KVM, VMware, Hyperv, VirtualBox, Parralels, BareMetal, Simulator, LXC. * Inputting "Any" will return the hypervisor type Any, other inputs will result in the hypervisor type none. * Both of these are invalid values and will return an error message. */ @@ -3074,7 +3072,7 @@ public void doInTransactionWithoutResult(final TransactionStatus status) { final PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(), TrafficType.Management); _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(), TrafficType.Storage.toString(), "vlan", mgmtTraffic.getXenNetworkLabel(), mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(), mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan(), - mgmtTraffic.getHypervNetworkLabel(), mgmtTraffic.getOvm3NetworkLabel()); + mgmtTraffic.getHypervNetworkLabel()); logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network {} with same configure of management traffic type", mgmtPhyNetwork); } } catch (final InvalidParameterValueException ex) { @@ -7273,10 +7271,6 @@ public NetworkOffering createNetworkOffering(final NetworkOfferingBaseCmd cmd) { throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr); } - if (provider == Provider.CiscoVnmc) { - firewallProvider = provider; - } - if (provider == Provider.PaloAlto) { firewallProvider = Provider.PaloAlto; } diff --git a/server/src/main/java/com/cloud/network/NetworkModelImpl.java b/server/src/main/java/com/cloud/network/NetworkModelImpl.java index 07305c0e6418..f728e5cf8616 100644 --- a/server/src/main/java/com/cloud/network/NetworkModelImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkModelImpl.java @@ -1338,8 +1338,6 @@ public String getDefaultManagementTrafficLabel(long zoneId, HypervisorType hyper label = mgmtTraffic.getVmwareNetworkLabel(); } else if (hypervisorType.equals(HypervisorType.Hyperv)) { label = mgmtTraffic.getHypervNetworkLabel(); - } else if (hypervisorType.equals(HypervisorType.Ovm3)) { - label = mgmtTraffic.getOvm3NetworkLabel(); } return label; } @@ -1368,8 +1366,6 @@ public String getDefaultStorageTrafficLabel(long zoneId, HypervisorType hypervis label = storageTraffic.getVmwareNetworkLabel(); } else if (hypervisorType.equals(HypervisorType.Hyperv)) { label = storageTraffic.getHypervNetworkLabel(); - } else if (hypervisorType.equals(HypervisorType.Ovm3)) { - label = storageTraffic.getOvm3NetworkLabel(); } return label; } @@ -1898,8 +1894,6 @@ public String getDefaultPublicTrafficLabel(long dcId, HypervisorType hypervisorT label = publicTraffic.getVmwareNetworkLabel(); } else if (hypervisorType.equals(HypervisorType.Hyperv)) { label = publicTraffic.getHypervNetworkLabel(); - } else if (hypervisorType.equals(HypervisorType.Ovm3)) { - label = publicTraffic.getOvm3NetworkLabel(); } return label; } @@ -1928,8 +1922,6 @@ public String getDefaultGuestTrafficLabel(long dcId, HypervisorType hypervisorTy label = guestTraffic.getVmwareNetworkLabel(); } else if (hypervisorType.equals(HypervisorType.Hyperv)) { label = guestTraffic.getHypervNetworkLabel(); - } else if (hypervisorType.equals(HypervisorType.Ovm3)) { - label = guestTraffic.getOvm3NetworkLabel(); } return label; } diff --git a/server/src/main/java/com/cloud/network/NetworkServiceImpl.java b/server/src/main/java/com/cloud/network/NetworkServiceImpl.java index d18fd043f697..cdfe42757c3f 100644 --- a/server/src/main/java/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/main/java/com/cloud/network/NetworkServiceImpl.java @@ -5417,7 +5417,7 @@ private void checkForPhysicalNetworksWithoutTag(PhysicalNetworkVO physicalNetwor @DB @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_CREATE, eventDescription = "Creating Physical Network TrafficType", create = true) public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficTypeStr, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, - String simulatorLabel, String vlan, String hypervLabel, String ovm3Label) { + String simulatorLabel, String vlan, String hypervLabel) { // verify input parameters PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); @@ -5473,7 +5473,7 @@ public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalN xenLabel = getDefaultXenNetworkLabel(trafficType); } PhysicalNetworkTrafficTypeVO pNetworktrafficType = new PhysicalNetworkTrafficTypeVO(physicalNetworkId, trafficType, xenLabel, kvmLabel, vmwareLabel, simulatorLabel, vlan, hypervLabel, - ovm3Label); + null); pNetworktrafficType = _pNTrafficTypeDao.persist(pNetworktrafficType); // For public traffic, get isolation method of physical network and update the public network accordingly @@ -5533,7 +5533,7 @@ public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id) { @Override @ActionEvent(eventType = EventTypes.EVENT_TRAFFIC_TYPE_UPDATE, eventDescription = "Updating physical network TrafficType", async = true) - public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel, String hypervLabel, String ovm3Label) { + public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel, String hypervLabel) { PhysicalNetworkTrafficTypeVO trafficType = _pNTrafficTypeDao.findById(id); @@ -5567,12 +5567,6 @@ public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, Stri trafficType.setHypervNetworkLabel(hypervLabel); } - if (ovm3Label != null) { - if ("".equals(ovm3Label)) { - ovm3Label = null; - } - trafficType.setOvm3NetworkLabel(ovm3Label); - } _pNTrafficTypeDao.update(id, trafficType); return trafficType; } diff --git a/server/src/main/java/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/main/java/com/cloud/network/guru/DirectNetworkGuru.java index 5c0c4eed7fc4..7bd332eccf0a 100644 --- a/server/src/main/java/com/cloud/network/guru/DirectNetworkGuru.java +++ b/server/src/main/java/com/cloud/network/guru/DirectNetworkGuru.java @@ -145,8 +145,7 @@ protected boolean canHandle(NetworkOffering offering, DataCenter dc, PhysicalNet if (dc.getNetworkType() == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) && isMyIsolationMethod(physnet) - && offering.getGuestType() == GuestType.Shared - && !_ntwkOfferingSrvcDao.isProviderForNetworkOffering(offering.getId(), Network.Provider.NiciraNvp)) { + && offering.getGuestType() == GuestType.Shared) { return true; } else if (dc.getNetworkType() == NetworkType.Advanced && offering.getGuestType() == GuestType.Shared @@ -154,7 +153,7 @@ && isMyIsolationMethod(physnet) && physnet.getIsolationMethods().contains("GRE")) { return true; } else { - logger.trace("We only take care of Shared Guest networks without Ovs or NiciraNvp provider"); + logger.trace("We only take care of Shared Guest networks without Ovs provider"); return false; } } diff --git a/server/src/main/java/com/cloud/network/router/NetworkHelperImpl.java b/server/src/main/java/com/cloud/network/router/NetworkHelperImpl.java index 56534a8ee7df..657b4319b4d0 100644 --- a/server/src/main/java/com/cloud/network/router/NetworkHelperImpl.java +++ b/server/src/main/java/com/cloud/network/router/NetworkHelperImpl.java @@ -181,7 +181,7 @@ public class NetworkHelperImpl implements NetworkHelper { VpcManager vpcManager; protected static final List HYPERVISOR_TYPES_NOT_SUPPORTING_DOMAIN_ROUTER = Arrays.asList( - HypervisorType.Ovm, HypervisorType.BareMetal, HypervisorType.External); + HypervisorType.BareMetal, HypervisorType.External); protected final Map> hypervisorsMap = new HashMap<>(); @@ -192,7 +192,6 @@ protected void setupHypervisorsMap() { hypervisorsMap.put(HypervisorType.VMware, VirtualNetworkApplianceManager.RouterTemplateVmware); hypervisorsMap.put(HypervisorType.Hyperv, VirtualNetworkApplianceManager.RouterTemplateHyperV); hypervisorsMap.put(HypervisorType.LXC, VirtualNetworkApplianceManager.RouterTemplateLxc); - hypervisorsMap.put(HypervisorType.Ovm3, VirtualNetworkApplianceManager.RouterTemplateOvm3); } @Override diff --git a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManager.java b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManager.java index 8ef77d3fb32f..879323fd593c 100644 --- a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManager.java +++ b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManager.java @@ -41,7 +41,6 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA String RouterTemplateVmwareCK = "router.template.vmware"; String RouterTemplateHyperVCK = "router.template.hyperv"; String RouterTemplateLxcCK = "router.template.lxc"; - String RouterTemplateOvm3CK = "router.template.ovm3"; String SetServiceMonitorCK = "network.router.EnableServiceMonitoring"; String RouterAlertsCheckIntervalCK = "router.alerts.check.interval"; String VirtualRouterServiceOfferingCK = "router.service.offering"; @@ -61,9 +60,6 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA "Name of the default router template on Hyperv.", true, ConfigKey.Scope.Zone, null); ConfigKey RouterTemplateLxc = new ConfigKey<>(String.class, RouterTemplateLxcCK, "Advanced", "SystemVM Template (LXC)", "Name of the default router template on LXC.", true, ConfigKey.Scope.Zone, null); - ConfigKey RouterTemplateOvm3 = new ConfigKey<>(String.class, RouterTemplateOvm3CK, "Advanced", "SystemVM Template (Ovm3)", - "Name of the default router template on Ovm3.", true, ConfigKey.Scope.Zone, null); - ConfigKey VirtualRouterUserData = new ConfigKey<>(String.class, "virtual.router.userdata", ConfigKey.CATEGORY_ADVANCED, "", "UUID for user data of VR, VPC VR, internal LB, and elastic LB. This works only when systemvm.userdata.enabled is set to true", diff --git a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index dd65719ad033..fe810da5acdb 100644 --- a/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -3363,7 +3363,6 @@ public ConfigKey[] getConfigKeys() { RouterTemplateVmware, RouterTemplateHyperV, RouterTemplateLxc, - RouterTemplateOvm3, UseExternalDnsServers, RouterVersionCheckEnabled, SetServiceMonitor, diff --git a/server/src/main/java/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/main/java/com/cloud/network/vpc/VpcManagerImpl.java index c5f36e856550..15030a8417f0 100644 --- a/server/src/main/java/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/main/java/com/cloud/network/vpc/VpcManagerImpl.java @@ -333,8 +333,8 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("VpcChecker")); private List vpcElements = null; private final List nonSupportedServices = Arrays.asList(Service.SecurityGroup, Service.Firewall); - private final List supportedProviders = Arrays.asList(Provider.VPCVirtualRouter, Provider.NiciraNvp, Provider.InternalLbVm, Provider.Netscaler, - Provider.JuniperContrailVpcRouter, Provider.Ovs, Provider.BigSwitchBcf, Provider.ConfigDrive, Provider.Nsx, Provider.Netris); + private final List supportedProviders = Arrays.asList(Provider.VPCVirtualRouter, Provider.InternalLbVm, Provider.Netscaler, + Provider.Ovs, Provider.ConfigDrive, Provider.Nsx, Provider.Netris); int _cleanupInterval; int _maxNetworks; @@ -350,7 +350,6 @@ protected void setupSupportedVpcHypervisorsList() { hTypes.add(HypervisorType.Simulator); hTypes.add(HypervisorType.LXC); hTypes.add(HypervisorType.Hyperv); - hTypes.add(HypervisorType.Ovm3); hTypes.add(HypervisorType.External); } @@ -654,11 +653,6 @@ public VpcOffering createVpcOffering(final String name, final String displayText final Map> svcProviderMap = new HashMap>(); final Set defaultProviders = new HashSet(); defaultProviders.add(Provider.VPCVirtualRouter); - // Just here for 4.1, replaced by commit 836ce6c1 in newer versions - final Set sdnProviders = new HashSet(); - sdnProviders.add(Provider.NiciraNvp); - sdnProviders.add(Provider.JuniperContrailVpcRouter); - boolean sourceNatSvc = false; boolean firewallSvs = false; // populate the services first @@ -669,12 +663,7 @@ public VpcOffering createVpcOffering(final String name, final String displayText throw new InvalidParameterValueException("Service " + serviceName + " is not supported in VPC"); } - if (service == Service.Connectivity) { - logger.debug("Applying Connectivity workaround, setting provider to NiciraNvp"); - svcProviderMap.put(service, sdnProviders); - } else { - svcProviderMap.put(service, defaultProviders); - } + svcProviderMap.put(service, defaultProviders); if (service == Service.NetworkACL) { firewallSvs = true; } @@ -2621,7 +2610,6 @@ public List getVpcElements() { if (vpcElements == null) { vpcElements = new ArrayList(); vpcElements.add((VpcProvider) _ntwkModel.getElementImplementingProvider(Provider.VPCVirtualRouter.getName())); - vpcElements.add((VpcProvider) _ntwkModel.getElementImplementingProvider(Provider.JuniperContrailVpcRouter.getName())); } if (vpcElements == null) { diff --git a/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java b/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java index 0f6933664f93..665064e98cfb 100755 --- a/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/main/java/com/cloud/resource/ResourceManagerImpl.java @@ -597,14 +597,6 @@ public List discoverCluster(final AddClusterCmd cmd) throws I if (clusterType == Cluster.ClusterType.CloudManaged) { final Map details = new HashMap<>(); - // should do this nicer perhaps ? - if (hypervisorType == HypervisorType.Ovm3) { - final Map allParams = cmd.getFullUrlParams(); - details.put("ovm3vip", allParams.get("ovm3vip")); - details.put("ovm3pool", allParams.get("ovm3pool")); - details.put("ovm3cluster", allParams.get("ovm3cluster")); - } - details.put(VmDetailConstants.CPU_OVER_COMMIT_RATIO, CapacityManager.CpuOverprovisioningFactor.value().toString()); details.put(VmDetailConstants.MEMORY_OVER_COMMIT_RATIO, CapacityManager.MemOverprovisioningFactor.value().toString()); _clusterDetailsDao.persist(cluster.getId(), details); @@ -2969,7 +2961,7 @@ public List getSupportedHypervisorTypes(final long zoneId, final for (final ClusterVO cluster : clustersForZone) { final HypervisorType hType = cluster.getHypervisorType(); - if (!forVirtualRouter || (hType != HypervisorType.BareMetal && hType != HypervisorType.External && hType != HypervisorType.Ovm)) { + if (!forVirtualRouter || (hType != HypervisorType.BareMetal && hType != HypervisorType.External)) { hypervisorTypes.add(hType); } } diff --git a/server/src/main/java/com/cloud/server/ConfigurationServerImpl.java b/server/src/main/java/com/cloud/server/ConfigurationServerImpl.java index 8f10dd84b54d..d2b381fc7abf 100644 --- a/server/src/main/java/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/main/java/com/cloud/server/ConfigurationServerImpl.java @@ -228,9 +228,6 @@ public void persistDefaultValues() throws InternalErrorException { _configDao.update("user.password.encoders.exclude", "MD5,LDAP,PLAINTEXT"); logger.debug("Configuration server excluded insecure encoders"); - _configDao.update("user.authenticators.exclude", "PLAINTEXT"); - logger.debug("Configuration server excluded plaintext authenticator"); - // Save default service offerings createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance", ProvisioningType.THIN, false, false, null); createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance", ProvisioningType.THIN, false, false, null); diff --git a/server/src/main/java/com/cloud/server/ManagementServerImpl.java b/server/src/main/java/com/cloud/server/ManagementServerImpl.java index e5066b6da5cc..16d9d7185042 100644 --- a/server/src/main/java/com/cloud/server/ManagementServerImpl.java +++ b/server/src/main/java/com/cloud/server/ManagementServerImpl.java @@ -899,7 +899,7 @@ public class ManagementServerImpl extends MutualExclusiveIdsManagerBase implemen private static final VirtualMachine.Type []systemVmTypes = { VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.ConsoleProxy}; private static final List LIVE_MIGRATION_SUPPORTING_HYPERVISORS = List.of(HypervisorType.Hyperv, HypervisorType.KVM, - HypervisorType.LXC, HypervisorType.Ovm, HypervisorType.Ovm3, HypervisorType.Simulator, HypervisorType.VMware, HypervisorType.XenServer); + HypervisorType.LXC, HypervisorType.Simulator, HypervisorType.VMware, HypervisorType.XenServer); @Inject public AccountManager _accountMgr; @@ -1463,13 +1463,13 @@ private void validateVmForHostMigration(VirtualMachine vm) { if (!LIVE_MIGRATION_SUPPORTING_HYPERVISORS.contains(vm.getHypervisorType())) { if (logger.isDebugEnabled()) { - logger.debug(vm + " is not XenServer/VMware/KVM/Ovm/Hyperv/Ovm3, cannot migrate this Instance."); + logger.debug(vm + " is not XenServer/VMware/KVM/Hyperv, cannot migrate this Instance."); } - throw new InvalidParameterValueException("Unsupported Hypervisor Type for Instance migration, we support " + "XenServer/VMware/KVM/Ovm/Hyperv/Ovm3 only"); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for Instance migration, we support XenServer/VMware/KVM/Hyperv only"); } if (VirtualMachine.Type.User.equals(vm.getType()) && HypervisorType.LXC.equals(vm.getHypervisorType())) { - throw new InvalidParameterValueException("Unsupported Hypervisor Type for User instance migration, we support XenServer/VMware/KVM/Ovm/Hyperv/Ovm3 only"); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for User instance migration, we support XenServer/VMware/KVM/Hyperv only"); } } diff --git a/server/src/main/java/com/cloud/storage/OCFS2ManagerImpl.java b/server/src/main/java/com/cloud/storage/OCFS2ManagerImpl.java index 0bc586c28de4..68caba238fd9 100644 --- a/server/src/main/java/com/cloud/storage/OCFS2ManagerImpl.java +++ b/server/src/main/java/com/cloud/storage/OCFS2ManagerImpl.java @@ -181,6 +181,7 @@ public void processDeletHostEventAfter(Host host) { String.format("Prepare OCFS2 nodes failed after delete host %s (zone: %s, pod: %s, cluster: %s", host, host.getDataCenterId(), host.getPodId(), host.getClusterId()); + // OCFS2 node management was only used by the removed OVM hypervisor plugin if (host.getHypervisorType() != HypervisorType.Ovm) { return; } diff --git a/server/src/main/java/com/cloud/storage/StorageManagerImpl.java b/server/src/main/java/com/cloud/storage/StorageManagerImpl.java index 7c501c78beeb..1e24a5ac8ef2 100644 --- a/server/src/main/java/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/main/java/com/cloud/storage/StorageManagerImpl.java @@ -3424,7 +3424,7 @@ public HypervisorType getHypervisorTypeFromFormat(ImageFormat format) { } else if (format == ImageFormat.QCOW2) { return HypervisorType.KVM; } else if (format == ImageFormat.RAW) { - return HypervisorType.Ovm; + return HypervisorType.KVM; } else if (format == ImageFormat.VHDX) { return HypervisorType.Hyperv; } else { diff --git a/server/src/main/java/com/cloud/storage/listener/StoragePoolMonitor.java b/server/src/main/java/com/cloud/storage/listener/StoragePoolMonitor.java index 2f9750edee2d..c3620a11dd50 100644 --- a/server/src/main/java/com/cloud/storage/listener/StoragePoolMonitor.java +++ b/server/src/main/java/com/cloud/storage/listener/StoragePoolMonitor.java @@ -116,8 +116,8 @@ public void processConnect(Host host, StartupCommand cmd, boolean forRebalance) StartupRoutingCommand scCmd = (StartupRoutingCommand)cmd; if (scCmd.getHypervisorType() == HypervisorType.XenServer || scCmd.getHypervisorType() == HypervisorType.KVM || scCmd.getHypervisorType() == HypervisorType.VMware || scCmd.getHypervisorType() == HypervisorType.Simulator || - scCmd.getHypervisorType() == HypervisorType.Ovm || scCmd.getHypervisorType() == HypervisorType.Hyperv || - scCmd.getHypervisorType() == HypervisorType.LXC || scCmd.getHypervisorType() == HypervisorType.Ovm3) { + scCmd.getHypervisorType() == HypervisorType.Hyperv || + scCmd.getHypervisorType() == HypervisorType.LXC) { String sags[] = _storageManager.getStorageAccessGroups(null, null, null, host.getId()); List pools = new ArrayList<>(); diff --git a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java index ce01048eaa56..3a803e2f1734 100755 --- a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -1570,10 +1570,6 @@ private boolean supportedByHypervisor(VolumeInfo volume, boolean isFromVmSnapsho hypervisorType = volume.getHypervisorType(); } - if (hypervisorType.equals(HypervisorType.Ovm)) { - throw new InvalidParameterValueException("Ovm won't support taking snapshot"); - } - if (hypervisorType.equals(HypervisorType.KVM)) { List hosts = null; if (scope.equals(ScopeType.CLUSTER)) { diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index 60482c431ebb..427e19f827cb 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -7263,12 +7263,12 @@ public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) thr } if (!isOnSupportedHypevisorForMigration(vm)) { - logger.error(vm + " is not XenServer/VMware/KVM/Ovm/Hyperv, cannot migrate this VM from hypervisor type " + vm.getHypervisorType()); - throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM/Ovm/Hyperv/Ovm3 only"); + logger.error(vm + " is not XenServer/VMware/KVM/Hyperv, cannot migrate this VM from hypervisor type " + vm.getHypervisorType()); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM/Hyperv only"); } if (vm.getType().equals(VirtualMachine.Type.User) && vm.getHypervisorType().equals(HypervisorType.LXC)) { - throw new InvalidParameterValueException("Unsupported Hypervisor Type for User VM migration, we support XenServer/VMware/KVM/Ovm/Hyperv/Ovm3 only"); + throw new InvalidParameterValueException("Unsupported Hypervisor Type for User VM migration, we support XenServer/VMware/KVM/Hyperv only"); } if (isVMUsingLocalStorage(vm)) { @@ -7426,11 +7426,9 @@ private boolean isOnSupportedHypevisorForMigration(VMInstanceVO vm) { return (vm.getHypervisorType().equals(HypervisorType.XenServer) || vm.getHypervisorType().equals(HypervisorType.VMware) || vm.getHypervisorType().equals(HypervisorType.KVM) || - vm.getHypervisorType().equals(HypervisorType.Ovm) || vm.getHypervisorType().equals(HypervisorType.Hyperv) || vm.getHypervisorType().equals(HypervisorType.LXC) || - vm.getHypervisorType().equals(HypervisorType.Simulator) || - vm.getHypervisorType().equals(HypervisorType.Ovm3)); + vm.getHypervisorType().equals(HypervisorType.Simulator)); } private boolean checkIfHostIsDedicated(HostVO host) { diff --git a/server/src/test/async-job-component.xml b/server/src/test/async-job-component.xml index 3597041f904a..20203313b2c2 100644 --- a/server/src/test/async-job-component.xml +++ b/server/src/test/async-job-component.xml @@ -125,9 +125,6 @@ - - - diff --git a/server/src/test/java/com/cloud/api/ApiResponseHelperTest.java b/server/src/test/java/com/cloud/api/ApiResponseHelperTest.java index c0c019f6dbd8..c85786d46bfd 100644 --- a/server/src/test/java/com/cloud/api/ApiResponseHelperTest.java +++ b/server/src/test/java/com/cloud/api/ApiResponseHelperTest.java @@ -438,10 +438,9 @@ public void testCreateTrafficTypeResponse() { String vmwareLabel = "vmware"; String simulatorLabel = "simulator"; String hypervLabel = "hyperv"; - String ovmLabel = "ovm"; String vlan = "vlan"; String trafficType = "Public"; - PhysicalNetworkTrafficType pnetTrafficType = new PhysicalNetworkTrafficTypeVO(pnet.getId(), Networks.TrafficType.getTrafficType(trafficType), xenLabel, kvmLabel, vmwareLabel, simulatorLabel, vlan, hypervLabel, ovmLabel); + PhysicalNetworkTrafficType pnetTrafficType = new PhysicalNetworkTrafficTypeVO(pnet.getId(), Networks.TrafficType.getTrafficType(trafficType), xenLabel, kvmLabel, vmwareLabel, simulatorLabel, vlan, hypervLabel, null); TrafficTypeResponse response = apiResponseHelper.createTrafficTypeResponse(pnetTrafficType); assertFalse(UUID.fromString(response.getId()).toString().isEmpty()); @@ -451,7 +450,6 @@ public void testCreateTrafficTypeResponse() { assertEquals(response.getKvmLabel(), kvmLabel); assertEquals(response.getVmwareLabel(), vmwareLabel); assertEquals(response.getHypervLabel(), hypervLabel); - assertEquals(response.getOvm3Label(), ovmLabel); assertEquals(response.getVlan(), vlan); assertEquals(response.getIsolationMethods(), "VXLAN,STT"); diff --git a/server/src/test/java/com/cloud/network/guru/DirectNetworkGuruTest.java b/server/src/test/java/com/cloud/network/guru/DirectNetworkGuruTest.java index 50d8af5e520d..83b3f691b46a 100644 --- a/server/src/test/java/com/cloud/network/guru/DirectNetworkGuruTest.java +++ b/server/src/test/java/com/cloud/network/guru/DirectNetworkGuruTest.java @@ -103,7 +103,6 @@ public void setup() { when(offering.getGuestType()).thenReturn(GuestType.Shared); when(offering.getTrafficType()).thenReturn(TrafficType.Guest); when(offering.getId()).thenReturn(42l); - when(ntwkOfferingSrvcDao.isProviderForNetworkOffering(offering.getId(), Network.Provider.NiciraNvp)).thenReturn(false); } @After diff --git a/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java b/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java index e4bc2096b9da..2698b5fe160f 100644 --- a/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java +++ b/server/src/test/java/com/cloud/vpc/MockNetworkManagerImpl.java @@ -475,7 +475,7 @@ public long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficTy */ @Override public PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String isolationMethod, String xenLabel, String kvmLabel, String vmwareLabel, - String simulatorLabel, String vlan, String hypervLabel, String ovm3Label) { + String simulatorLabel, String vlan, String hypervLabel) { // TODO Auto-generated method stub return null; } @@ -493,7 +493,7 @@ public PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id) { * @see com.cloud.network.NetworkService#updatePhysicalNetworkTrafficType(java.lang.Long, java.lang.String, java.lang.String, java.lang.String) */ @Override - public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel, String hypervLabel, String ovm3Label) { + public PhysicalNetworkTrafficType updatePhysicalNetworkTrafficType(Long id, String xenLabel, String kvmLabel, String vmwareLabel, String hypervLabel) { // TODO Auto-generated method stub return null; } diff --git a/test/integration/component/test_asa1000v_fw.py b/test/integration/component/test_asa1000v_fw.py deleted file mode 100644 index 35d94744d9a7..000000000000 --- a/test/integration/component/test_asa1000v_fw.py +++ /dev/null @@ -1,136 +0,0 @@ -# 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. - -""" Cisco ASA1000v external firewall -""" -#Import Local Modules -from nose.plugins.attrib import attr -from marvin.cloudstackTestCase import cloudstackTestCase -from marvin.lib.utils import cleanup_resources -from marvin.lib.base import (NetworkOffering, - PhysicalNetwork, - VNMC, - ASA1000V, - Cluster) -from marvin.lib.common import get_zone - - -class Services: - """Test Cisco ASA1000v services - """ - - def __init__(self): - self.services = { - "vnmc": { - "ipaddress": '10.147.28.236', - "username": 'admin', - "password": 'Password_123', - }, - "asa": { - "ipaddress": '10.147.28.238', - "insideportprofile": 'asa-in123', - }, - "network_offering": { - "name": 'CiscoVnmc', - "displaytext": 'CiscoVnmc', - "guestiptype": 'Isolated', - "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Firewall,UserData,StaticNat', - "traffictype": 'GUEST', - "availability": 'Optional', - "serviceProviderList": { - "Dhcp": 'VirtualRouter', - "Dns": 'VirtualRouter', - "SourceNat": 'CiscoVnmc', - "PortForwarding": 'CiscoVnmc', - "Firewall": 'CiscoVnmc', - "UserData": 'VirtualRouter', - "StaticNat": 'CiscoVnmc', - }, - }, - "network": { - "name": "CiscoVnmc", - "displaytext": "CiscoVnmc", - }, - } - -class TestASASetup(cloudstackTestCase): - - @classmethod - def setUpClass(cls): - cls.apiclient = super( - TestASASetup, - cls - ).getClsTestClient().getApiClient() - cls.services = Services().services - cls.network_offering = NetworkOffering.create( - cls.apiclient, - cls.services["network_offering"], - conservemode=True) - # Enable network offering - cls.network_offering.update(cls.apiclient, state='Enabled') - - cls._cleanup = [ - cls.network_offering, - ] - return - - @classmethod - def tearDownClass(cls): - try: - # Cleanup - cleanup_resources(cls.apiclient, cls._cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - - self.zone = get_zone(self.apiclient, self.testClient.getZoneForTests()) - self.physicalnetworks = PhysicalNetwork.list(self.apiclient, zoneid=self.zone.id) - self.assertNotEqual(len(self.physicalnetworks), 0, "Check if the list physical network API returns a non-empty response") - self.clusters = Cluster.list(self.apiclient, hypervisor='VMware') - self.assertNotEqual(len(self.clusters), 0, "Check if the list cluster API returns a non-empty response") - - self.cleanup = [] - return - - def tearDown(self): - try: - self.debug("Cleaning up the resources") - cleanup_resources(self.apiclient, self.cleanup) - self.debug("Cleanup complete!") - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - @attr(tags=["device", "asa"]) - def test_registerVnmc(self): - Vnmc = VNMC.create(self.apiclient, self.services["vnmc"]["ipaddress"], self.services["vnmc"]["username"], self.services["vnmc"]["password"], self.physicalnetworks[0].id) - self.debug("Cisco VNMC appliance with id %s deployed"%(Vnmc.id)) - VnmcList = VNMC.list(self.apiclient, physicalnetworkid = self.physicalnetworks[0].id) - self.assertNotEqual(len(VnmcList), 0, "List VNMC API returned an empty response") - Vnmc.delete(self.apiclient) - - @attr(tags=["device", "asa"]) - def test_registerAsa1000v(self): - Asa = ASA1000V.create(self.apiclient, self.services["asa"]["ipaddress"], self.services["asa"]["insideportprofile"], self.clusters[0].id, self.physicalnetworks[0].id) - self.debug("Cisco ASA 1000v appliance with id %s deployed"%(Asa.id)) - AsaList = ASA1000V.list(self.apiclient, physicalnetworkid = self.physicalnetworks[0].id) - self.assertNotEqual(len(AsaList), 0, "List ASA 1000v API returned an empty response") - Asa.delete(self.apiclient) diff --git a/test/integration/component/test_bigswitch_bcf.py b/test/integration/component/test_bigswitch_bcf.py deleted file mode 100644 index c4cec8f6ff6c..000000000000 --- a/test/integration/component/test_bigswitch_bcf.py +++ /dev/null @@ -1,776 +0,0 @@ -# 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. - -""" P1 tests for BigSwitchBcf network Plugin -""" -#Import Local Modules -from nose.plugins.attrib import attr -from marvin.cloudstackTestCase import cloudstackTestCase -from marvin.cloudstackAPI import * -from marvin.lib.utils import (cleanup_resources, - random_gen, validateList) -from marvin.lib.base import (Account, - VirtualMachine, - ServiceOffering, - NetworkOffering, - VpcOffering, - Network, - PublicIPAddress, - FireWallRule, - NATRule, - Configurations) -from marvin.lib.common import (get_domain, - get_zone, - get_template) -from marvin.sshClient import SshClient -from marvin.codes import PASS -import subprocess -import time - - -class Services: - """Test BigSwitchBcf plugin - """ - - def __init__(self): - self.services = { - "account": { - "email": "cloudstack@cloudmonkey.com", - "firstname": "cloudstack", - "lastname": "bob", - "username": "bobbuilder", - "password": "password", - }, - "service_offering": { - "name": "Tiny Instance", - "displaytext": "Tiny Instance", - "cpunumber": 1, - "cpuspeed": 100, # in MHz - "memory": 128, # In MBs - }, - "virtual_machine": { - "displayname": "TestVM", - "username": "root", - "password": "password", - "ssh_port": 22, - "hypervisor": 'KVM', - "privateport": 22, - "publicport": 22, - "protocol": 'TCP', - }, - "natrule": { - "privateport": 22, - "publicport": 22, - "startport": 22, - "endport": 22, - "protocol": "TCP", - "cidrlist": '0.0.0.0/0', - }, - "net1_net2_aclrule": { - "protocol": "ICMP", - "cidrlist": '0.0.0.0/0', - }, - "big_switch_bcf_device": { - "hostname": '10.212.1.104', - "username": 'admin', - "password": 'bsn', - "retrycount": '4', - "retryinterval": '60' - }, - #services supported by Big Switch BCF for isolated networks. - "network_offering": { - "name": 'BCF network offering (marvin)', - "displaytext": 'BCF (marvin)', - "guestiptype": 'Isolated', - "supportedservices": 'Dhcp,SourceNat,Connectivity,StaticNat,PortForwarding,Firewall', - "traffictype": 'GUEST', - "availability": 'Optional', - "serviceProviderList": { - "PortForwarding": 'VirtualRouter', - "Dhcp" : 'VirtualRouter', - "Connectivity" : 'BigSwitchBcf', - "StaticNat" : 'VirtualRouter', - "SourceNat" : 'VirtualRouter', - "Firewall" : 'VirtualRouter' - }, - }, - "vpc_network_offering": { - "name": 'BCF VPC network offering (marvin)', - "displaytext": 'BCF VPC (marvin)', - "guestiptype": 'Isolated', - "supportedservices": 'Dhcp,SourceNat,Connectivity,PortForwarding,StaticNat,NetworkACL', - "traffictype": 'GUEST', - "availability": 'Optional', - "useVpc": 'on', - "serviceProviderList": { - "Dhcp": 'VpcVirtualRouter', - "SourceNat": 'VpcVirtualRouter', - "PortForwarding": 'VpcVirtualRouter', - "StaticNat": 'VpcVirtualRouter', - "NetworkACL": 'VpcVirtualRouter', - "Connectivity" : 'BigSwitchBcf' - }, - }, - "vpc_offering": { - "name": 'BCF VPC', - "displaytext": 'BCF VPC', - "supportedservices": 'Dhcp,SourceNat,PortForwarding,StaticNat,NetworkACL,Connectivity', - }, - "vpc": { - "name": "TestVPC", - "displaytext": "TestVPC", - "cidr": '10.0.0.1/16' - }, - "network": { - "name": "BCF network", - "displaytext": "BCF network", - }, - "ostype": 'CentOS 5.3 (64-bit)', - "sleep": 60, - "timeout": 10 - } - -class TestBigSwitchBcf(cloudstackTestCase): - - - @classmethod - def setUpClass(cls): - cls._cleanup = [] - cls.testClient = super(TestBigSwitchBcf, cls).getClsTestClient() - cls.api_client = cls.testClient.getApiClient() - - cls.services = Services().services - - # Get Zone, Domain and templates - cls.domain = get_domain(cls.api_client) - cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) - cls.template = get_template( - cls.api_client, - cls.zone.id, - cls.services["ostype"] - ) - cls.services["virtual_machine"]["zoneid"] = cls.zone.id - cls.services["virtual_machine"]["template"] = cls.template.id - - # Get test parameters - cls.bigswitch_services = cls.services["big_switch_bcf_device"] - try: - # Get physical network - resp = listPhysicalNetworks.listPhysicalNetworksCmd() - resp.zoneid = cls.zone.id - physical_networks = cls.api_client.listPhysicalNetworks(resp) - if isinstance(physical_networks, list): - cls.debug("phy net %s" % physical_networks) - physical_network = physical_networks[1] - - # Get bigswitch network service provider - resp = listNetworkServiceProviders.listNetworkServiceProvidersCmd() - resp.name = 'BigSwitchBcf' - resp.physicalnetworkid = physical_network.id - nw_service_providers = cls.api_client.listNetworkServiceProviders(resp) - if isinstance(nw_service_providers, list): - bigswitch_provider = nw_service_providers[0] - cls.debug("net serv prov %s" % nw_service_providers) - else: - # Create bigswitch provider if not already existent - resp_add_nsp = addNetworkServiceProvider.addNetworkServiceProviderCmd() - resp_add_nsp.name = 'BigSwitchBcf' - resp_add_nsp.physicalnetworkid = physical_network.id - bigswitch_provider = cls.api_client.addNetworkServiceProvider(resp_add_nsp) - # add BCF controller - resp_add_device = addBigSwitchBcfDevice.addBigSwitchBcfDeviceCmd() - resp_add_device.physicalnetworkid = physical_network.id - resp_add_device.username = cls.bigswitch_services["username"] - resp_add_device.password = cls.bigswitch_services["password"] - resp_add_device.hostname = cls.bigswitch_services["hostname"] - resp_add_device.retrycount = cls.bigswitch_services["retrycount"] - resp_add_device.retryinterval = cls.bigswitch_services["retryinterval"] - cls.bigswitch = cls.api_client.addBigSwitchBcfDevice(resp_add_device) - - if bigswitch_provider.state != 'Enabled': - cmd = updateNetworkServiceProvider.updateNetworkServiceProviderCmd() - cmd.id = bigswitch_provider.id - cmd.state = 'Enabled' - cls.api_client.updateNetworkServiceProvider(cmd) - - # Create non-VPC network offering - cls.network_offering = NetworkOffering.create( - cls.api_client, - cls.services["network_offering"], - conservemode=True - ) - cls._cleanup.append(cls.network_offering) - - cls.network_offering.update(cls.api_client, state='Enabled') - - # Create VPC network offering - cls.vpc_network_offering = NetworkOffering.create( - cls.api_client, - cls.services["vpc_network_offering"], - conservemode=False - ) - cls._cleanup.append(cls.vpc_network_offering) - - cls.vpc_network_offering.update(cls.api_client, state='Enabled') - - # Create VPC offering - cls.vpc_offering = VpcOffering.create( - cls.api_client, - cls.services["vpc_offering"] - ) - cls._cleanup.append(cls.vpc_offering) - - cls.vpc_offering.update(cls.api_client, state='Enabled') - - # Create compute service offering - cls.service_offering = ServiceOffering.create( - cls.api_client, - cls.services["service_offering"] - ) - cls._cleanup.append(cls.service_offering) - - except Exception as e: - cls.tearDownClass() - raise Exception ("Warning: Exception in setUpClass: %s" % e) - return - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.api_client, cls._cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - self.account = Account.create( - self.apiclient, - self.services["account"], - admin=True, - domainid=self.domain.id - ) -# self._cleanup = [self.account] - return - - def tearDown(self): - try: - self.debug("Cleaning up the resources") - cleanup_resources(self.apiclient, self._cleanup) - interval = Configurations.list( - self.apiclient, - name='network.gc.interval' - ) - wait = Configurations.list( - self.apiclient, - name='network.gc.wait' - ) - time.sleep(int(interval[0].value) + int(wait[0].value)) - self.debug("Cleanup complete!") - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - - @attr(tags = ["advancedns"]) - def test_network_bcf(self): - """Test basic workflow with BigSwitch BCF plugin - 1. Create a non-VPC guest network - 2. Create two VMs on the network - 3. Add firewall rule to make virtual router pingable - 4. Test ping to virtual router public IP - 5. Add static NAT to vm_1, with firewall rule to allow ssh - 6. Ssh to vm_1, ping vm_2 private address, ping google.com - """ - - self.debug("STEP 1: Creating network with network offering: %s" % - self.network_offering.id) - self.network = Network.create( - self.apiclient, - self.services["network"], - accountid=self.account.name, - domainid=self.account.domainid, - networkofferingid=self.network_offering.id, - zoneid=self.zone.id - ) - self.debug("Created network with ID: %s" % self.network.id) - - self.debug("STEP 2: Deploying VMs in account: %s" % self.account.name) - - vm_1 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[ str(self.network.id), ] - ) - self.debug("Deployed VM in network: %s" % self.network.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=vm_1.id - ) - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % vm_1.id - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - vm_2 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[ str(self.network.id), ] - ) - self.debug("Deployed VM in network: %s" % self.network.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=vm_2.id - ) - - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % vm_2.id - ) - - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - self.debug("STEP 3: Add FW rule to allow source nat ping") - src_nat_list = PublicIPAddress.list( - self.apiclient, - associatednetworkid=self.network.id, - account=self.account.name, - domainid=self.account.domainid, - listall=True, - issourcenat=True, - ) - self.assertEqual( - isinstance(src_nat_list, list), - True, - "List Public IP should return a valid source NAT" - ) - self.assertNotEqual( - len(src_nat_list), - 0, - "Length of response from listPublicIp should not be 0" - ) - - src_nat = src_nat_list[0] - - #Create Firewall rules on source NAT - fw_rule_icmp = FireWallRule.create( - self.apiclient, - ipaddressid=src_nat.id, - protocol='ICMP', - cidrlist=["0.0.0.0/0",] - ) - self.debug("Created firewall rule: %s" % fw_rule_icmp.id) - - self.debug("STEP 4: Trying to ping source NAT %s" % src_nat.ipaddress) - # User should be able to ping router via source nat ip - try: - self.debug("Trying to ping source NAT %s" % src_nat.ipaddress) - result = subprocess.call( - ['ping', '-c 1', src_nat.ipaddress]) - - self.debug("Ping result: %s" % result) - # if ping successful, then result should be 0 - self.assertEqual( - result, - 0, - "Check if ping is successful or not" - ) - except Exception as e: - self.fail("Ping failed for source NAT %s (%s)" - % (src_nat.ipaddress, e)) - - self.debug("STEP 5: Add static NAT to vm_1 with FW rule to allow SSH") - floating_ip_1 = PublicIPAddress.create( - self.apiclient, - accountid=self.account.name, - zoneid=self.zone.id, - domainid=self.account.domainid, - networkid=self.network.id, - ) - self.debug("Associated %s with network %s" % ( - floating_ip_1.ipaddress, - self.network.id - ) - ) - NATRule.create( - self.apiclient, - vm_1, - self.services["natrule"], - ipaddressid=floating_ip_1.ipaddress.id, - openfirewall=False, - networkid=self.network.id - ) - - # Should be able to SSH vm_1 via static nat, then ping vm_2 & Internet - try: - self.debug("STEP 6: SSH into vm_1: %s" % floating_ip_1) - - ssh = vm_1.get_ssh_client( - ipaddress=floating_ip_1.ipaddress.ipaddress - ) - self.debug("Ping vm_2 at %s" % vm_2.ipaddress) - # Ping vm_2 - res_1 = ssh.execute("ping -c 1 %s" % vm_2.ipaddress) - - self.debug("Ping to google.com from VM") - # Ping Internet - res_2 = ssh.execute("ping -c 1 www.google.com") - - # res = 64 bytes from maa03s17-in-f20.1e100.net (74.125.236.212): - # icmp_req=1 ttl=57 time=25.9 ms - # --- www.l.google.com ping statistics --- - # 1 packets transmitted, 1 received, 0% packet loss, time 0ms - # rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms - except Exception as e: - self.fail("SSH Access failed: %s" % e) - - self.debug("ping result1: %s" % res_1); - self.debug("ping result2: %s" % res_2); - - result1 = str(res_1) - self.assertEqual( - result1.count("1 received"), - 1, - "Ping vm_2 from vm_1 should be successful" - ) - - result2 = str(res_2) - self.assertEqual( - result2.count("1 received"), - 1, - "Ping Internet from vm_1 should be successful" - ) - - # Deleting two test VMs - VirtualMachine.delete(vm_1, self.apiclient, expunge=True) - VirtualMachine.delete(vm_2, self.apiclient, expunge=True) - - # Delete Network - Network.delete(self.network, self.apiclient) - - return - - @attr(tags = ["advancedns"]) - def test_vpc_network_bcf(self): - """Test VPC workflow with BigSwitch BCF plugin - 1. Create a VPC with three networks - 2. Create one VM on each of the three networks - 3. Add firewall rule to make virtual router pingable - 4. Test ping to virtual router public IP - 5. Add static NAT to vm_1, with firewall rule to allow ssh - 6. Add NAT rule to allow ping between net1 and net2 - 7. Ssh to vm_1, ping vm_2 private address, should succeed - 8. continue ... ping vm_3 private address, should fail - 9. continue ... ping Internet, should succeed - """ - - self.debug("STEP 1: Creating VPC with VPC offering: %s" % - self.vpc_offering.id) - vpc = VPC.create( - self.apiclient, - self.services["vpc"], - accountid=self.account.name, - domainid=self.account.domainid, - vpcofferingid=self.vpc_offering.id, - zoneid=self.zone.id - ) - self.debug("Created VPC with ID: %s" % self.vpc.id) - - # Creating network using the vpc network offering created - self.debug("Creating networks with vpc network offering: %s" % - self.vpc_network_offering.id) - net1 = Network.create( - self.apiclient, - self.services["vpc_network"], - accountid=self.account.name, - domainid=self.account.domainid, - networkofferingid=self.vpc_network_offering.id, - zoneid=self.zone.id, - gateway="10.0.100.1", - vpcid=vpc.id - ) - self.debug("Created network with ID: %s" % net1.id) - - net2 = Network.create( - self.apiclient, - self.services["vpc_network"], - accountid=self.account.name, - domainid=self.account.domainid, - networkofferingid=self.vpc_network_offering.id, - zoneid=self.zone.id, - gateway="10.0.101.1", - vpcid=vpc.id - ) - self.debug("Created network with ID: %s" % net2.id) - - net3 = Network.create( - self.apiclient, - self.services["vpc_network"], - accountid=self.account.name, - domainid=self.account.domainid, - networkofferingid=self.vpc_network_offering.id, - zoneid=self.zone.id, - gateway="10.0.102.0", - vpcid=vpc.id - ) - self.debug("Created network with ID: %s" % net3.id) - - self.debug("STEP 2: Deploying VMs in networks") - - vm_1 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[ str(net1.id), ] - ) - self.debug("Deployed VM in network: %s" % net1.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=vm_1.id - ) - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % vm_1.id - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - vm_2 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[ str(net2.id), ] - ) - self.debug("Deployed VM in network: %s" % net2.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=vm_2.id - ) - - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % vm_2.id - ) - - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - vm_3 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[ str(net3.id), ] - ) - self.debug("Deployed VM in network: %s" % net3.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=vm_3.id - ) - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % vm_3.id - ) - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - self.debug("STEP 3: Add FW rule to allow source nat ping") - src_nat_list = PublicIPAddress.list( - self.apiclient, - account=self.account.name, - domainid=self.account.domainid, - listall=True, - issourcenat=True, - vpcid=vpc.id - ) - self.assertEqual( - isinstance(src_nat_list, list), - True, - "List Public IP should return a valid source NAT" - ) - self.assertNotEqual( - len(src_nat_list), - 0, - "Length of response from listPublicIp should not be 0" - ) - - src_nat = src_nat_list[0] - - #Create Firewall rules on source NAT - fw_rule_icmp = FireWallRule.create( - self.apiclient, - ipaddressid=src_nat.id, - protocol='ICMP', - cidrlist=["0.0.0.0/0",] - ) - self.debug("Created firewall rule: %s" % fw_rule_icmp.id) - - self.debug("STEP 4: Trying to ping source NAT %s" % src_nat.ipaddress) - # User should be able to ping router via source nat ip - try: - self.debug("Trying to ping source NAT %s" % src_nat.ipaddress) - result = subprocess.call( - ['ping', '-c 1', src_nat.ipaddress]) - - self.debug("Ping result: %s" % result) - # if ping successful, then result should be 0 - self.assertEqual( - result, - 0, - "Check if ping is successful or not" - ) - except Exception as e: - self.fail("Ping failed for source NAT %s (%s)" - % (src_nat.ipaddress, e)) - - self.debug("STEP 5: Add static NAT to vm_1 with FW rule to allow SSH") - floating_ip_1 = PublicIPAddress.create( - self.apiclient, - accountid=self.account.name, - zoneid=self.zone.id, - domainid=self.account.domainid, - networkid=net1.id, - vpcid=vpc.id - ) - self.debug("Associated %s with network %s" % ( - floating_ip_1.ipaddress, - net1.id - ) - ) - NATRule.create( - self.apiclient, - vm_1, - self.services["natrule"], - ipaddressid=floating_ip_1.ipaddress.id, - openfirewall=False, - networkid=net1.id, - vpcid=vpc.id - ) - - # Should be able to SSH vm_1 via static nat, then ping vm_2 & Internet - try: - self.debug("STEP 6: SSH into vm_1: %s" % floating_ip_1) - - ssh = vm_1.get_ssh_client( - ipaddress=floating_ip_1.ipaddress.ipaddress - ) -# self.debug("Ping vm_2 at %s" % vm_2.ipaddress) - # Ping to outsite world -# res_1 = ssh.execute("ping -c 1 %s" % vm_2.ipaddress) - -# self.debug("Ping to google.com from VM") - # Ping to outsite world -# res_2 = ssh.execute("ping -c 1 www.google.com") - - # res = 64 bytes from maa03s17-in-f20.1e100.net (74.125.236.212): - # icmp_req=1 ttl=57 time=25.9 ms - # --- www.l.google.com ping statistics --- - # 1 packets transmitted, 1 received, 0% packet loss, time 0ms - # rtt min/avg/max/mdev = 25.970/25.970/25.970/0.000 ms - except Exception as e: - self.fail("SSH Access failed: %s" % e) - -# self.debug("ping result1: %s" % res_1); -# self.debug("ping result2: %s" % res_2); - -# result1 = str(res_1) -# self.assertEqual( -# result1.count("1 received"), -# 1, -# "Ping vm_2 from vm_1 should be successful" -# ) - -# result2 = str(res_2) -# self.assertEqual( -# result2.count("1 received"), -# 1, -# "Ping Internet from vm_1 should be successful" -# ) - - # Deleting two test VMs - VirtualMachine.delete(vm_1, self.apiclient, expunge=True) - VirtualMachine.delete(vm_2, self.apiclient, expunge=True) - - # Delete Network - Network.delete(self.network, self.apiclient) - - return diff --git a/test/integration/component/test_brocade_vcs.py b/test/integration/component/test_brocade_vcs.py deleted file mode 100644 index 1f45d93b0e59..000000000000 --- a/test/integration/component/test_brocade_vcs.py +++ /dev/null @@ -1,331 +0,0 @@ -# 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. - -""" P1 tests for brocade -""" -#Import Local Modules -from nose.plugins.attrib import attr -from marvin.cloudstackTestCase import cloudstackTestCase -import unittest -from marvin.cloudstackAPI import (listPhysicalNetworks, - listNetworkServiceProviders, - addNetworkServiceProvider, - addBrocadeVcsDevice, - updateNetworkServiceProvider, - deleteBrocadeVcsDevice) -from marvin.lib.utils import (cleanup_resources) -from marvin.lib.base import (Account, - VirtualMachine, - ServiceOffering, - NetworkOffering, - Configurations, - Network) -from marvin.lib.common import (get_domain, - get_zone, - get_template) -import time - -class Services: - """Test brocade plugin - """ - - def __init__(self): - self.services = { - "account": { - "email": "test@test.com", - "firstname": "Test", - "lastname": "User", - "username": "test", - # Random characters are appended for unique - # username - "password": "password", - }, - "service_offering": { - "name": "Tiny Instance", - "displaytext": "Tiny Instance", - "cpunumber": 1, - "cpuspeed": 100, # in MHz - "memory": 128, # In MBs - }, - "virtual_machine": { - "displayname": "TestVM", - "username": "root", - "password": "password", - "ssh_port": 22, - "hypervisor": 'XenServer', - "privateport": 22, - "publicport": 22, - "protocol": 'TCP', - }, - "network_offering": { - "name": 'Brocade', - "displaytext": 'Brocade', - "guestiptype": 'Isolated', - "supportedservices": 'SourceNat,Connectivity', - "traffictype": 'GUEST', - "availability": 'Optional', - "serviceProviderList": { - "SourceNat": 'VirtualRouter', - "Connectivity" : 'BrocadeVcs' - }, - }, - "network": { - "name": "Brocade", - "displaytext": "Brocade", - }, - "ostype": 'CentOS 5.3 (64-bit)', - # Cent OS 5.3 (64 bit) - "sleep": 60, - "timeout": 10 - } - -class TestBrocadeVcs(cloudstackTestCase): - - - @classmethod - def setUpClass(cls): - cls._cleanup = [] - cls.testClient = super(TestBrocadeVcs, cls).getClsTestClient() - cls.api_client = cls.testClient.getApiClient() - - cls.services = Services().services - # Get Zone, Domain and templates - cls.domain = get_domain(cls.api_client) - cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) - cls.template = get_template( - cls.api_client, - cls.zone.id, - cls.services["ostype"] - ) - try: - cls.brocadeDeviceData = cls.config.__dict__["brocadeDeviceData"].__dict__ - assert cls.brocadeDeviceData["ipaddress"], "ipaddress of brocade device\ - not present in config file" - assert cls.brocadeDeviceData["username"], "username of brocade device\ - not present in config file" - except Exception as e: - raise unittest.SkipTest("Exception occurred while reading\ - brocade device data from config file: %s" % e) - try: - - """ Adds Brocade device and enables NS provider""" - cmd = listPhysicalNetworks.listPhysicalNetworksCmd() - cmd.zoneid = cls.zone.id - physical_networks = cls.api_client.listPhysicalNetworks(cmd) - if isinstance(physical_networks, list): - physical_network = physical_networks[0] - cmd = listNetworkServiceProviders.listNetworkServiceProvidersCmd() - cmd.name = 'BrocadeVcs' - cmd.physicalnetworkid = physical_network.id - nw_service_providers = cls.api_client.listNetworkServiceProviders(cmd) - - if isinstance(nw_service_providers, list): - brocade_provider = nw_service_providers[0] - else: - cmd1 = addNetworkServiceProvider.addNetworkServiceProviderCmd() - cmd1.name = 'BrocadeVcs' - cmd1.physicalnetworkid = physical_network.id - brocade_provider = cls.api_client.addNetworkServiceProvider(cmd1) - - cmd2 = addBrocadeVcsDevice.addBrocadeVcsDeviceCmd() - cmd2.physicalnetworkid = physical_network.id - cmd2.username = cls.brocadeDeviceData["username"] - cmd2.password = cls.brocadeDeviceData["password"] - cmd2.hostname = cls.brocadeDeviceData["ipaddress"] - cls.brocade = cls.api_client.addBrocadeVcsDevice(cmd2) - - if brocade_provider.state != 'Enabled': - cmd = updateNetworkServiceProvider.updateNetworkServiceProviderCmd() - cmd.id = brocade_provider.id - cmd.state = 'Enabled' - cls.api_client.updateNetworkServiceProvider(cmd) - - - cls.network_offering = NetworkOffering.create( - cls.api_client, - cls.services["network_offering"], - conservemode=True - ) - cls._cleanup.append(cls.network_offering) - - # Enable Network offering - cls.network_offering.update(cls.api_client, state='Enabled') - cls.services["virtual_machine"]["zoneid"] = cls.zone.id - cls.services["virtual_machine"]["template"] = cls.template.id - cls.service_offering = ServiceOffering.create( - cls.api_client, - cls.services["service_offering"] - ) - cls._cleanup.append(cls.service_offering) - except Exception as e: - cls.tearDownClass() - raise Exception ("Warning: Exception in setUpClass: %s" % e) - return - - @classmethod - def tearDownClass(cls): - try: - #Cleanup resources used - cmd = deleteBrocadeVcsDevice.deleteBrocadeVcsDeviceCmd() - cmd.vcsdeviceid = cls.brocade.vcsdeviceid - cls.brocade = cls.api_client.deleteBrocadeVcsDevice(cmd) - cleanup_resources(cls.api_client, cls._cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - self.account = Account.create( - self.apiclient, - self.services["account"], - admin=True, - domainid=self.domain.id - ) - self.cleanup = [self.account] - return - - def tearDown(self): - try: - self.debug("Cleaning up the resources") - #Clean up, terminate the created network offerings - #cleanup_resources(self.apiclient, self.cleanup) - interval = Configurations.list( - self.apiclient, - name='network.gc.interval' - ) - wait = Configurations.list( - self.apiclient, - name='network.gc.wait' - ) - # Sleep to ensure that all resources are deleted - time.sleep(int(interval[0].value) + int(wait[0].value)) - self.debug("Cleanup complete!") - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - - @attr(tags = ["advancedns"]) - def test_network_vcs(self): - """Test Brocade Network and VM Creation - """ - - - # Validate the following - # 1. Deploy the first VM using a network from the above created - # Network offering. - # 2. Deploy another VM. - # 3. Delete The VMs and the Network - - # Creating network using the network offering created - self.debug("Creating network with network offering: %s" % - self.network_offering.id) - self.network = Network.create( - self.apiclient, - self.services["network"], - accountid=self.account.name, - domainid=self.account.domainid, - networkofferingid=self.network_offering.id, - zoneid=self.zone.id - ) - self.debug("Created network with ID: %s" % self.network.id) - - self.debug("Deploying VM in account: %s" % self.account.name) - - # Spawn an instance in that network - virtual_machine_1 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[str(self.network.id)] - ) - self.debug("Deployed VM in network: %s" % self.network.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=virtual_machine_1.id - ) - - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % virtual_machine_1.id - ) - - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - self.debug("Deploying another VM in account: %s" % - self.account.name) - - # Spawn an instance in that network - virtual_machine_2 = VirtualMachine.create( - self.apiclient, - self.services["virtual_machine"], - accountid=self.account.name, - domainid=self.account.domainid, - serviceofferingid=self.service_offering.id, - networkids=[str(self.network.id)] - ) - self.debug("Deployed VM in network: %s" % self.network.id) - list_vm_response = VirtualMachine.list( - self.apiclient, - id=virtual_machine_2.id - ) - - self.debug( - "Verify listVirtualMachines response for virtual machine: %s" \ - % virtual_machine_2.id - ) - - self.assertEqual( - isinstance(list_vm_response, list), - True, - "Check list response returns a valid list" - ) - vm_response = list_vm_response[0] - - self.assertEqual( - vm_response.state, - "Running", - "VM state should be running after deployment" - ) - - # Deleting a single VM - VirtualMachine.delete(virtual_machine_1, self.apiclient, expunge=True) - - - # Deleting a single VM - VirtualMachine.delete(virtual_machine_2, self.apiclient, expunge=True) - - - # Delete Network - Network.delete(self.network, self.apiclient) - - return diff --git a/test/integration/plugins/datera/TestVolumes.py b/test/integration/plugins/datera/TestVolumes.py deleted file mode 100644 index 68d9896b6a95..000000000000 --- a/test/integration/plugins/datera/TestVolumes.py +++ /dev/null @@ -1,1127 +0,0 @@ -# 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. - -import logging -import unittest -import random -import os -import json -import time -import math -import XenAPI -import collections -import distutils.util - -logger = logging.getLogger(__name__) -logger_handler = logging.FileHandler('/var/tmp/{}.log'.format(__name__)) -logger_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') -logger_handler.setFormatter(logger_formatter) -logger.addHandler(logger_handler) -logger.setLevel(logging.INFO) - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -from nose.plugins.attrib import attr - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import (Account, DiskOffering, ServiceOffering, - StoragePool, User, VirtualMachine, Volume) - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import (get_domain, get_template, get_zone, - list_clusters, list_hosts, - list_virtual_machines, - list_volumes, list_disk_offering) - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -from marvin.cloudstackAPI import resizeVolume - -#from dfs_sdk import DateraApi -from dfs_sdk import get_api - - -class TestData(): - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - managedComputeOffering = "managedComputeoffering" - nonManagedComputeOffering = "nonManagedComputeoffering" - diskName = "diskname" - diskOffering = "diskoffering" - domainId = "domainId" - hypervisor = "hypervisor" - login = "login" - mvip = "mvip" - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - Datera = "datera" - storageTag = "Datera_SAN_1" - tags = "tags" - templateCacheName = "centos56-x86-64-xen" # TODO - templateName = "templatename" - testAccount = "testaccount" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - virtualMachine2 = "virtualmachine2" - volume_1 = "volume_1" - volume_2 = "volume_2" - xenServer = "xenserver" - zoneId = "zoneId" - - def __init__(self): - self.testdata = { - TestData.Datera: { - TestData.mvip: "172.19.2.214", - TestData.login: "admin", - TestData.password: "password", - TestData.port: 80, - TestData.url: "https://172.19.2.214:443" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "password" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - "username": "test", - "password": "test" - }, - TestData.testAccount: { - "email": "test2@test2.com", - "firstname": "Jane", - "lastname": "Doe", - "username": "test2", - "password": "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - "username": "testuser", - "password": "password" - }, - TestData.primaryStorage: { - "name": "Datera-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - "url": "MVIP=172.19.2.214;SVIP=172.28.214.9;" + - "clusterAdminUsername=admin;clusterAdminPassword=password;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "numReplicas=3;", - TestData.provider: "Datera", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.virtualMachine: { - "name": "TestVM", - "displayname": "TestVM", - "privateport": 22, - "publicport": 22, - "protocol": "tcp" - }, - TestData.virtualMachine2: { - "name": "TestVM2", - "displayname": "TestVM2", - "privateport": 22, - "publicport": 22, - "protocol": "tcp" - }, - TestData.managedComputeOffering: { - "name": "DT_CO_1", - "displaytext": "DT_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 200, - "tags": TestData.storageTag - }, - TestData.nonManagedComputeOffering: { - "name": "DT_CO_2", - "displaytext": "DT_CO_2 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 200, - "tags": TestData.storageTag - }, - - TestData.diskOffering: { - "name": "DT_DO_1", - "displaytext": "DT_DO_1 (5GB Min IOPS = 300; Max IOPS = 500)", - "disksize": 5, - "customizediops": False, - "miniops": 300, - "maxiops": 500, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - "testdiskofferings": { - "customiopsdo": { - "name": "DT_Custom_Iops_DO", - "displaytext": "Customized Iops DO", - "disksize": 5, - "customizediops": True, - "miniops": 500, - "maxiops": 1000, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - "customsizedo": { - "name": "DT_Custom_Size_DO", - "displaytext": "Customized Size DO", - "disksize": 5, - "customizediops": False, - "miniops": 500, - "maxiops": 1000, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - "customsizeandiopsdo": { - "name": "DT_Custom_Iops_Size_DO", - "displaytext": "Customized Size and Iops DO", - "disksize": 10, - "customizediops": True, - "miniops": 400, - "maxiops": 800, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - "newiopsdo": { - "name": "DT_New_Iops_DO", - "displaytext": "New Iops (min=350, max = 700)", - "disksize": 5, - "miniops": 350, - "maxiops": 700, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - "newsizedo": { - "name": "DT_New_Size_DO", - "displaytext": "New Size: 10", - "disksize": 10, - "customizediops": False, - "miniops": 400, - "maxiops": 800, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - "newsizeandiopsdo": { - "name": "DT_New_Size_Iops_DO", - "displaytext": "New Size and Iops", - "disksize": 10, - "customizediops": False, - "miniops": 200, - "maxiops": 800, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - }, - TestData.volume_1: { - TestData.diskName: "test-volume", - }, - TestData.volume_2: { - TestData.diskName: "test-volume-2", - }, - TestData.templateName: "tiny linux kvm", # TODO - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - } - - def update(self, overrideFileName): - if os.path.exists(overrideFileName): - with open(overrideFileName) as fd: - self.testdata = self._update(self.testdata, json.loads(fd.read())) - - def _update(self, d, u): - - for k, v in u.items(): - if isinstance(v, collections.Mapping): - r = self.update(d.get(k, {}), v) - d[k] = r - else: - d[k] = u[k] - return d - - -class TestVolumes(cloudstackTestCase): - _should_only_be_one_vm_in_list_err_msg = "There should only be one VM in this list." - _should_only_be_one_volume_in_list_err_msg = "There should only be one volume in this list." - _volume_vm_id_and_vm_id_do_not_match_err_msg = "The volume's VM ID and the VM's ID do not match." - _vm_not_in_running_state_err_msg = "The VM is not in the 'Running' state." - _vm_not_in_stopped_state_err_msg = "The VM is not in the 'Stopped' state." - _sr_not_shared_err_msg = "The SR is not shared." - _list_should_be_empty = "The list should be empty." - _volume_resize_err = "The Volume was not resized correctly." - - @classmethod - def setUpXenServer(cls): - - # Set up xenAPI connection - hosts = list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId]) - xenserver_info = cls.testdata[TestData.xenServer] - - for h in hosts: - host_ip = "https://" + h.ipaddress - try: - cls.xen_session = XenAPI.Session(host_ip) - cls.xen_session.xenapi.login_with_password(xenserver_info[TestData.username], - xenserver_info[TestData.password]) - break - except XenAPI.Failure as e: - pass - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.managedComputeOffering] - ) - - cls.device_name = 'xvdb' - - @classmethod - def setUpKVM(cls): - logger.info("Setting up KVM") - # KVM doesn't support root disks - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.nonManagedComputeOffering] - ) - - cls.device_name = 'vdb' - - @classmethod - def setUpClass(cls): - """ - 1. Init ACS API and DB connection - 2. Init Datera API connection - 3. Create ACS Primary storage - 4. Create ACS compute and disk offering. - 5. Create ACS data disk without attaching to a VM - """ - logger.info("Setting up Class") - - # Set up API client - testclient = super(TestVolumes, cls).getClsTestClient() - cls.apiClient = testclient.getApiClient() - cls.dbConnection = testclient.getDbConnection() - - # Setup test data - td = TestData() - if cls.config.TestData and cls.config.TestData.Path: - td.update(cls.config.TestData.Path) - cls.testdata = td.testdata - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_name=cls.config.zones[0].name) - cls.cluster = list_clusters(cls.apiClient)[0] - cls.template = get_template(cls.apiClient, cls.zone.id) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Set up datera connection - datera = cls.testdata[TestData.Datera] - cls.dt_client = get_api( - username=datera[TestData.login], - password=datera[TestData.password], - hostname=datera[TestData.mvip], - version="v2" - ) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - cls.disk_offering = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering] - ) - - cls.disk_offering_new = DiskOffering.create( - cls.apiClient, - cls.testdata['testdiskofferings']['newsizeandiopsdo'] - ) - - cls.supports_resign = cls._get_supports_resign() - - # Set up hypervisor specific connections - if cls.cluster.hypervisortype.lower() == 'xenserver': - cls.setUpXenServer() - if cls.cluster.hypervisortype.lower() == 'kvm': - cls.setUpKVM() - - # Create 1 data volume_1 - cls.volume = Volume.create( - cls.apiClient, - cls.testdata[TestData.volume_1], - account=cls.account.name, - domainid=cls.domain.id, - zoneid=cls.zone.id, - diskofferingid=cls.disk_offering.id - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.volume, - cls.compute_offering, - cls.disk_offering, - cls.disk_offering_new, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - logger.info("Tearing Down Class") - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - cls._purge_datera_volumes() - - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - logger.info("Setup test") - self.attached = False - self.cleanup = [] - - def tearDown(self): - logger.info("Tearing Down test") - cleanup_resources(self.apiClient, self.cleanup) - - @classmethod - def _set_supports_resign(cls, val): - - supports_resign = str(val).lower() - cls.supports_resign = val - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - - sql_query = "Update host_details Set value = '" + supports_resign + "' Where name = 'supportsResign'" - cls.dbConnection.execute(sql_query) - - sql_query = "Update cluster_details Set value = '" + supports_resign + "' Where name = 'supportsResign'" - cls.dbConnection.execute(sql_query) - - @classmethod - def _get_supports_resign(cls): - - sql_query = "SELECT value from cluster_details Where name='supportsResign' AND cluster_id=%d" % cls.testdata[ - TestData.clusterId] - - sql_result = cls.dbConnection.execute(sql_query) - logger.warn(sql_result) - - if len(sql_result) < 1: - return False - - return bool(distutils.util.strtobool(sql_result[0][0].lower())) - - def _get_cs_storage_pool_db_id(self, storage_pool): - return self._get_db_id("storage_pool", storage_pool) - - def _get_db_id(self, table, db_obj): - sql_query = "Select id From " + table + " Where uuid = '" + str(db_obj.id) + "'" - sql_result = self.dbConnection.execute(sql_query) - return sql_result[0][0] - - @classmethod - def _purge_datera_volumes(cls): - logger.warn("Deleting all volumes") - for ai in list(cls.dt_client.app_instances.get().values()): - logger.warn(ai) - if 'CS-T' in ai['name']: - ai.set(admin_state="offline") - ai.delete() - - def test_01_attach_new_volume_to_stopped_VM(self): - - '''Attach a volume to a stopped virtual machine, then start VM''' - # Create VM and volume for tests - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True, - mode='advanced' - ) - self.cleanup.append(virtual_machine) - - template_volume_name = \ - self._get_app_instance_name_from_cs_volume(self.template, - vol_type='TEMPLATE') - dt_volume = self._check_and_get_dt_volume(template_volume_name) - - virtual_machine.stop(self.apiClient, forced=True) - - new_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_2], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering.id - ) - - self.cleanup.append(new_volume) - - self._check_and_get_cs_volume(new_volume.id, self.testdata[TestData.volume_2][TestData.diskName]) - - new_volume = virtual_machine.attach_volume( - self.apiClient, - new_volume - ) - - newvolume = self._check_and_get_cs_volume(new_volume.id, self.testdata[TestData.volume_2][TestData.diskName]) - - virtual_machine.start(self.apiClient) - - vm = self._get_vm(virtual_machine.id) - - self.assertEqual( - newvolume.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - "running", - TestVolumes._vm_not_in_running_state_err_msg - ) - - dt_volume_size = self._get_volume_size_with_hsr(newvolume) - - iqn = self._get_iqn(newvolume) - - dt_new_volname = self._get_app_instance_name_from_cs_volume(newvolume) - - dt_volume = self._check_and_get_dt_volume(dt_new_volname) - - self._check_size_and_iops(dt_volume, newvolume, dt_volume_size) - - initiator_group_name = self._get_initiator_group_name() - - self._check_initiator_group(dt_volume, initiator_group_name) - - self._check_hypervisor(iqn) - logger.info("Detach volume from the VM") - virtual_machine.detach_volume( - self.apiClient, - new_volume - ) - - def test_02_attach_detach_attach_volume(self): - '''Attach, detach, and attach volume to a running VM''' - - # Create VM and volume for tests - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True, - mode='advanced' - ) - self.cleanup.append(virtual_machine) - - self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - ####################################### - ####################################### - # STEP 1: Attach volume to running VM # - ####################################### - ####################################### - self.volume = virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - vm = self._get_vm(virtual_machine.id) - - initiator_group_name = self._get_initiator_group_name() - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - iqn = self._get_iqn(self.volume) - - dt_volume_size = self._get_volume_size_with_hsr(self.volume) - - dt_volume_name = self._get_app_instance_name_from_cs_volume(self.volume) - - dt_volume = self._check_and_get_dt_volume(dt_volume_name) - - self._check_initiator_group(dt_volume, initiator_group_name) - - self._check_size_and_iops(dt_volume, vol, dt_volume_size) - - self._check_hypervisor(iqn) - - ######################################### - ######################################### - # STEP 2: Detach volume from running VM # - ######################################### - ######################################### - - self.volume = virtual_machine.detach_volume( - self.apiClient, - self.volume - ) - - self.attached = False - - vol = self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - vm = self._get_vm(virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - None, - "The volume should not be attached to a VM." - ) - - self.assertEqual( - vm.state.lower(), - 'running', - str(vm.state) - ) - - dt_volume = self._check_and_get_dt_volume(dt_volume_name) - - self._check_initiator_group(dt_volume, initiator_group_name, False) - - self._check_hypervisor(iqn, False) - - ####################################### - ####################################### - # STEP 3: Attach volume to running VM # - ####################################### - ####################################### - - time.sleep(30) - self.volume = virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - vm = self._get_vm(virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - dt_volume = self._check_and_get_dt_volume(dt_volume_name) - - self._check_initiator_group(dt_volume, initiator_group_name) - - self._check_hypervisor(iqn) - - def test_03_attached_volume_reboot_VM(self): - '''Attach volume to running VM, then reboot.''' - # Create VM and volume for tests - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True, - mode='advanced' - ) - self.cleanup.append(virtual_machine) - - self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - ####################################### - ####################################### - # STEP 1: Attach volume to running VM # - ####################################### - ####################################### - - self.volume = virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - dt_volume_name = self._get_app_instance_name_from_cs_volume(self.volume) - - vol = self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - vm = self._get_vm(virtual_machine.id) - - initiator_group_name = self._get_initiator_group_name() - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - iqn = self._get_iqn(self.volume) - - volume_size_gb = self._get_volume_size_with_hsr(self.volume) - - dt_volume = self._check_and_get_dt_volume(dt_volume_name) - - self._check_size_and_iops(dt_volume, vol, volume_size_gb) - - self._check_initiator_group(dt_volume, initiator_group_name) - - self._check_hypervisor(iqn) - - ####################################### - ####################################### - # STEP 2: Reboot VM with attached vol # - ####################################### - ####################################### - virtual_machine.reboot(self.apiClient) - - vol = self._check_and_get_cs_volume(self.volume.id, self.testdata[TestData.volume_1][TestData.diskName]) - - vm = self._get_vm(virtual_machine.id) - - iqn = self._get_iqn(self.volume) - - dt_volume_size = self._get_volume_size_with_hsr(self.volume) - - dt_volume = self._check_and_get_dt_volume(dt_volume_name) - - self._check_size_and_iops(dt_volume, vol, dt_volume_size) - - self._check_initiator_group(dt_volume, initiator_group_name) - - self._check_hypervisor(iqn) - - def _check_if_device_visible_in_vm(self, vm, dev_name): - - try: - ssh_client = vm.get_ssh_client() - except Exception as e: - self.fail("SSH failed for virtual machine: %s - %s" % - (vm.ipaddress, e)) - - cmd = "iostat | grep %s" % dev_name - res = ssh_client.execute(cmd) - logger.warn(cmd) - logger.warn(res) - - if not res: - self.fail("Device %s not found on VM: %s" % (dev_name, vm.ipaddress)) - - def _check_list(self, in_list, expected_size_of_list, err_msg): - self.assertEqual( - isinstance(in_list, list), - True, - "'in_list' is not a list." - ) - - self.assertEqual( - len(in_list), - expected_size_of_list, - err_msg - ) - - def _check_initiator_group(self, dt_volume, initiator_group_name, should_exist=True): - - volume_initiator_groups = dt_volume['storage_instances']['storage-1']['acl_policy']['initiator_groups'] - - if should_exist: - self.assertTrue( - initiator_group_name in volume_initiator_groups[0], - "Initiator group not assigned to volume" - ) - - else: - - self.assertTrue( - len(volume_initiator_groups) == 0, - "Initiator group still asigined to volume, should have been removed" - ) - - def _check_volume(self, volume, volume_name, disk_offering): - self.assertTrue( - volume.name.startswith(volume_name), - "The volume name is incorrect." - ) - - self.assertEqual( - volume.diskofferingid, - disk_offering.id, - "The disk offering is incorrect." - ) - - self.assertEqual( - volume.zoneid, - self.zone.id, - "The zone is incorrect." - ) - - self.assertEqual( - volume.storagetype, - self.disk_offering.storagetype, - "The storage type is incorrect." - ) - - def _check_size_and_iops(self, dt_volume, cs_volume, size): - - dt_max_total_iops = dt_volume['storage_instances']['storage-1']['volumes']['volume-1']['performance_policy'][ - 'total_iops_max'] - self.assertEqual( - dt_max_total_iops, - cs_volume.maxiops, - "Check QOS - Max IOPS: " + str(dt_max_total_iops) - ) - - dt_volume_size = dt_volume['storage_instances']['storage-1']['volumes']['volume-1']['size'] - self.assertEqual( - dt_volume_size, - size, - "Check volume size: " + str(dt_volume_size) - ) - - def _check_and_get_cs_volume(self, volume_id, volume_name, disk_offering=None): - - if not disk_offering: - disk_offering = self.disk_offering - - list_volumes_response = list_volumes( - self.apiClient, - id=volume_id - ) - - self._check_list(list_volumes_response, 1, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - cs_volume = list_volumes_response[0] - - self._check_volume(cs_volume, volume_name, disk_offering) - - return cs_volume - - def _get_app_instance_name_from_cs_volume(self, cs_volume, vol_type='VOLUME'): - """ - Get Datera app_instance name based on ACS data object types - Eg. CS-V-test-volume-7XWJ5Q-dfc41254-371a-40b3-b410-129eb79893c0 - """ - app_inst_prefix = 'CS' - - if vol_type == 'VOLUME': - vol_type_char = 'V' - uuid = cs_volume.id - name = cs_volume.name - app_instance_name = app_inst_prefix + '-' + vol_type_char + '-' + name + '-' + uuid - - if vol_type == 'TEMPLATE': - vol_type_char = 'T' - uuid = cs_volume.id - primary_storage_db_id = str(self._get_cs_storage_pool_db_id(self.primary_storage)) - app_instance_name = app_inst_prefix + '-' + vol_type_char + '-' + uuid + '-' + primary_storage_db_id - - return app_instance_name - - def _get_iqn(self, cs_volume): - """ - Get IQN for the CS volume from Datera - """ - app_instance_name = self._get_app_instance_name_from_cs_volume(cs_volume) - app_instance = self.dt_client.app_instances.get(app_instance_name) - return app_instance['storage_instances']['storage-1']['access']['iqn'] - - def _get_cs_volume_size_with_hsr(self, cs_volume): - - disk_size_bytes = cs_volume.size - - disk_offering_id = cs_volume.diskofferingid - - disk_offering = list_disk_offering(self.apiClient, id=disk_offering_id)[0] - - hsr = disk_offering.hypervisorsnapshotreserve - - disk_size_with_hsr_bytes = disk_size_bytes + (disk_size_bytes * hsr) / 100 - - disk_size_with_hsr_gb = int(math.ceil(disk_size_with_hsr_bytes / (1024 ** 3))) - - return disk_size_with_hsr_gb - - def _get_volume_size_with_hsr(self, cs_volume): - - app_instance_name = self._get_app_instance_name_from_cs_volume(cs_volume) - app_instance = self.dt_client.app_instances.get(app_instance_name) - - volume_size_gb = app_instance['storage_instances']['storage-1']['volumes']['volume-1']['size'] - - self.assertEqual( - isinstance(volume_size_gb, int), - True, - "The volume size should be a non-zero integer." - ) - - return volume_size_gb - - def _get_initiator_group_name(self): - init_group_prefix = 'CS-InitiatorGroup' - initiator_group_name = init_group_prefix + '-' + self.cluster.id - self.dt_client.initiator_groups.get(initiator_group_name) - return initiator_group_name - - def _get_dt_volumes(self): - return self.dt_client.app_instances.get() - - def _get_vm(self, vm_id): - list_vms_response = list_virtual_machines(self.apiClient, id=vm_id) - - self._check_list(list_vms_response, 1, TestVolumes._should_only_be_one_vm_in_list_err_msg) - - return list_vms_response[0] - - def _check_and_get_dt_volume(self, dt_volume_name, should_exist=True): - dt_volume = None - dt_volumes = self._get_dt_volumes() - - for volume in list(dt_volumes.values()): - if volume['name'] == dt_volume_name: - dt_volume = volume - break - - if should_exist: - self.assertNotEqual( - dt_volume, - None, - "Check if Datera volume was created: " + str(dt_volumes) - ) - else: - self.assertEqual( - dt_volume, - None, - "Check if volume was deleted: " + str(dt_volumes) - ) - - return dt_volume - - def _resize_volume(self, volume, new_disk_offering): - - cmd = resizeVolume.resizeVolumeCmd() - cmd.id = self.volume.id - cmd.diskofferingid = new_disk_offering.id - - self.apiClient.resizeVolume(cmd) - - do_size_bytes = int(new_disk_offering.disksize * (1024 ** 3)) - retries = 3 - success = False - - while retries > 0: - retries -= 1 - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id - ) - - for vol in list_volumes_response: - if vol.id == volume.id and \ - int(vol.size) == do_size_bytes and \ - vol.state == 'Ready': - success = True - - if success: - break - else: - time.sleep(10) - - self.assertEqual(success, True, self._volume_resize_err) - - def _check_hypervisor(self, iqn, should_exist=True): - if self.cluster.hypervisortype.lower() == 'xenserver': - self._check_xen_sr(iqn, should_exist) - else: - return - - def _check_xen_sr(self, iqn, should_exist=True): - - xen_sr_name = "/" + iqn + "/0" - if should_exist: - xen_sr = self.xen_session.xenapi.SR.get_by_name_label(xen_sr_name)[0] - - self.sr_shared = self.xen_session.xenapi.SR.get_shared(xen_sr) - - self.assertEqual( - self.sr_shared, - True, - TestVolumes._sr_not_shared_err_msg - ) - else: - xen_sr = self.xen_session.xenapi.SR.get_by_name_label(xen_sr_name) - - self._check_list(xen_sr, 0, TestVolumes._list_should_be_empty) - - def _check_if_device_removed_in_vm(self, vm, dev_name): - - try: - ssh_client = vm.get_ssh_client() - except Exception as e: - self.fail("SSH failed for virtual machine: %s - %s" % - (vm.ipaddress, e)) - - cmd = "iostat | grep %s" % dev_name - res = ssh_client.execute(cmd) - logger.warn(cmd) - logger.warn(res) - - if res: - self.fail("Device %s still attached on VM: %s" % (dev_name, vm.ipaddress)) - - def _start_device_io(self, vm, dev_name): - - try: - ssh_client = vm.get_ssh_client() - except Exception as e: - self.fail("SSH failed for virtual machine: %s - %s" % - (vm.ipaddress, e)) - - cmd = "dd if=/dev/urandom of=/dev/%s &" % dev_name - res = ssh_client.execute(cmd) - logger.warn(cmd) - logger.warn(res) - - def _stop_device_io(self, vm, dev_name): - - try: - ssh_client = vm.get_ssh_client() - except Exception as e: - self.fail("SSH failed for virtual machine: %s - %s" % - (vm.ipaddress, e)) - - cmd = "killall -9 dd" - res = ssh_client.execute(cmd) - logger.warn(cmd) - logger.warn(res) - - def _get_bytes_written(self, vm, dev_name): - - try: - ssh_client = vm.get_ssh_client() - except Exception as e: - self.fail("SSH failed for virtual machine: %s - %s" % - (vm.ipaddress, e)) - - cmd = "iostat | grep %s " % dev_name - res = ssh_client.execute(cmd) - logger.warn(cmd) - logger.warn(res) - - self.assertNotEqual(res, None, "Error getting iostat info") - - ret_data = ' '.join(map(str, res)).strip() - return int(ret_data.split()[-1]) diff --git a/test/integration/plugins/solidfire/TestAddRemoveHosts.py b/test/integration/plugins/solidfire/TestAddRemoveHosts.py deleted file mode 100644 index 1f67f771c82d..000000000000 --- a/test/integration/plugins/solidfire/TestAddRemoveHosts.py +++ /dev/null @@ -1,957 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import time -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, ServiceOffering, User, Host, StoragePool, VirtualMachine - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_volumes - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster (two hosts for XenServer / one host for KVM with another added/removed during the tests) -# -# Running the tests: -# Change the "hypervisor_type" variable to control which hypervisor type to test. -# If using XenServer, set a breakpoint on each test after the first one. When the breakpoint is hit, reset the -# added/removed host to a snapshot state and re-start it. Once it's up and running, run the test code. -# Check that ip_address_of_new_xenserver_host / ip_address_of_new_kvm_host is correct. -# If using XenServer, verify the "xen_server_master_hostname" variable is correct. -# If using KVM, verify the "kvm_1_ip_address" variable is correct. -# -# Note: -# If you do have more than one cluster, you might need to change this line: cls.cluster = list_clusters(cls.apiClient)[0] and -# this variable's value: TestData.clusterId. - - -class TestData: - #constants - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - displayText = "displaytext" - diskSize = "disksize" - domainId = "domainId" - hypervisor = "hypervisor" - kvm = "kvm" - mvip = "mvip" - name = "name" - newXenServerHost = "newXenServerHost" - newKvmHost = "newKvmHost" - newHostDisplayName = "newHostDisplayName" - password = "password" - podId = "podid" - port = "port" - primaryStorage = "primarystorage" - primaryStorage2 = "primarystorage2" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - storageTag2 = "SolidFire_Volume_1" - tags = "tags" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - volume_1 = "volume_1" - xenServer = "xenserver" - zoneId = "zoneid" - - # modify to control which hypervisor type to test - hypervisor_type = xenServer - xen_server_master_hostname = "XenServer-6.5-1" - kvm_1_ip_address = "10.117.40.111" - ip_address_of_new_xenserver_host = "10.117.40.118" - ip_address_of_new_kvm_host = "10.117.40.115" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.78.225", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.78.225:443" - }, - TestData.kvm: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.newXenServerHost: { - TestData.username: "root", - TestData.password: "solidfire", - TestData.url: "http://" + TestData.ip_address_of_new_xenserver_host, - TestData.podId : "1", - TestData.zoneId: "1" - }, - TestData.newKvmHost: { - TestData.username: "root", - TestData.password: "solidfire", - TestData.url: "http://" + TestData.ip_address_of_new_kvm_host, - TestData.podId : "1", - TestData.zoneId: "1" - }, - TestData.primaryStorage: { - TestData.name: "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.78.225;SVIP=10.117.94.225;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.primaryStorage2: { - TestData.name: "SolidFireShared-%d" % random.randint(0, 100), - TestData.scope: "CLUSTER", - TestData.url: "MVIP=10.117.78.225;SVIP=10.117.94.225;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "minIops=5000;maxIops=50000;burstIops=75000", - TestData.provider: "SolidFireShared", - TestData.tags: TestData.storageTag2, - TestData.capacityIops: 5000, - TestData.capacityBytes: 1099511627776, - TestData.hypervisor: "XenServer", - TestData.podId: 1 - }, - TestData.virtualMachine: { - TestData.name: "TestVM", - "displayname": "Test VM" - }, - TestData.computeOffering: { - TestData.name: "SF_CO_1", - TestData.displayText: "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag - }, - TestData.volume_1: { - "diskname": "testvolume", - }, - TestData.newHostDisplayName: "XenServer-6.5-3", - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestAddRemoveHosts(cloudstackTestCase): - _vag_id_should_be_non_zero_int_err_msg = "The SolidFire VAG ID should be a non-zero integer." - _sf_account_id_should_be_non_zero_int_err_msg = "The SolidFire account ID should be a non-zero integer." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestAddRemoveHosts, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - if TestData.hypervisor_type == TestData.xenServer: - cls.xs_pool_master_ip = list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_master_hostname)[0].ipaddress - - cls._connect_to_hypervisor() - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.cluster = list_clusters(cls.apiClient)[0] - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata[TestData.account], - admin=1 - ) - - # Set up connection to make customized API calls - user = User.create( - cls.apiClient, - cls.testdata[TestData.user], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - cls._cleanup = [ - cls.compute_offering, - user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.virtual_machine = None - - self.cleanup = [] - - def tearDown(self): - try: - if self.virtual_machine is not None: - self.virtual_machine.delete(self.apiClient, True) - - cleanup_resources(self.apiClient, self.cleanup) - except Exception as e: - logging.debug("Exception in tearDown(self): %s" % e) - - def test_add_remove_host_with_solidfire_plugin_1(self): - primarystorage = self.testdata[TestData.primaryStorage] - - primary_storage = StoragePool.create( - self.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=self.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage) - - self.virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - if TestData.hypervisor_type == TestData.xenServer: - root_volume = self._get_root_volume(self.virtual_machine) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, root_volume, self) - self._perform_add_remove_xenserver_host(primary_storage.id, sf_iscsi_name) - elif TestData.hypervisor_type == TestData.kvm: - self._perform_add_remove_kvm_host(primary_storage.id) - else: - self.assertTrue(False, "Invalid hypervisor type") - - def test_add_remove_host_with_solidfire_plugin_2(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - primarystorage2 = self.testdata[TestData.primaryStorage2] - - primary_storage_2 = StoragePool.create( - self.apiClient, - primarystorage2, - scope=primarystorage2[TestData.scope], - zoneid=self.zone.id, - clusterid=self.cluster.id, - provider=primarystorage2[TestData.provider], - tags=primarystorage2[TestData.tags], - capacityiops=primarystorage2[TestData.capacityIops], - capacitybytes=primarystorage2[TestData.capacityBytes], - hypervisor=primarystorage2[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage_2) - - sf_iscsi_name = self._get_iqn_2(primary_storage_2) - - self._perform_add_remove_xenserver_host(primary_storage_2.id, sf_iscsi_name) - - def test_add_remove_host_with_solidfire_plugin_3(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - primarystorage = self.testdata[TestData.primaryStorage] - - primary_storage = StoragePool.create( - self.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=self.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage) - - self.virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - root_volume = self._get_root_volume(self.virtual_machine) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, root_volume, self) - - primarystorage2 = self.testdata[TestData.primaryStorage2] - - primary_storage_2 = StoragePool.create( - self.apiClient, - primarystorage2, - scope=primarystorage2[TestData.scope], - zoneid=self.zone.id, - clusterid=self.cluster.id, - provider=primarystorage2[TestData.provider], - tags=primarystorage2[TestData.tags], - capacityiops=primarystorage2[TestData.capacityIops], - capacitybytes=primarystorage2[TestData.capacityBytes], - hypervisor=primarystorage2[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage_2) - - self._perform_add_remove_xenserver_host(primary_storage.id, sf_iscsi_name) - - def test_add_remove_host_with_solidfire_plugin_4(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - primarystorage2 = self.testdata[TestData.primaryStorage2] - - primary_storage_2 = StoragePool.create( - self.apiClient, - primarystorage2, - scope=primarystorage2[TestData.scope], - zoneid=self.zone.id, - clusterid=self.cluster.id, - provider=primarystorage2[TestData.provider], - tags=primarystorage2[TestData.tags], - capacityiops=primarystorage2[TestData.capacityIops], - capacitybytes=primarystorage2[TestData.capacityBytes], - hypervisor=primarystorage2[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage_2) - - sf_iscsi_name = self._get_iqn_2(primary_storage_2) - - primarystorage = self.testdata[TestData.primaryStorage] - - primary_storage = StoragePool.create( - self.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=self.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage) - - self.virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - self._perform_add_remove_xenserver_host(primary_storage_2.id, sf_iscsi_name) - - # Make sure each host is in its own VAG. - # Create a VM that needs a new volume from the storage that has a VAG per host. - # Verify the volume is in all VAGs. - # Remove one of the hosts. - # Check that the IQN is no longer in its previous VAG, but that the volume ID is still in that VAG, though. - # Add the host back into the cluster. The IQN should be added to a VAG that already has an IQN from this cluster in it. - def test_vag_per_host_5(self): - hosts = list_hosts(self.apiClient, clusterid=self.cluster.id) - - self.assertTrue( - len(hosts) >= 2, - "There needs to be at least two hosts." - ) - - unique_vag_ids = self._get_unique_vag_ids(hosts) - - self.assertTrue(len(hosts) == len(unique_vag_ids), "To run this test, each host should be in its own VAG.") - - primarystorage = self.testdata[TestData.primaryStorage] - - primary_storage = StoragePool.create( - self.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=self.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - self.cleanup.append(primary_storage) - - self.virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - root_volume = self._get_root_volume(self.virtual_machine) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, primary_storage.id, self, TestAddRemoveHosts._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, root_volume.name, self) - - sf_vag_ids = sf_util.get_vag_ids(self.cs_api, self.cluster.id, primary_storage.id, self) - - sf_util.check_vags(sf_volume, sf_vag_ids, self) - - host = Host(hosts[0].__dict__) - - host_iqn = self._get_host_iqn(host) - - all_vags = sf_util.get_all_vags(self.sfe) - - host_vag = self._get_host_vag(host_iqn, all_vags) - - self.assertTrue(host_vag != None, "The host should be in a VAG.") - - host.delete(self.apiClient) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, root_volume.name, self) - - sf_util.check_vags(sf_volume, sf_vag_ids, self) - - all_vags = sf_util.get_all_vags(self.sfe) - - host_vag = self._get_host_vag(host_iqn, all_vags) - - self.assertTrue(host_vag == None, "The host should not be in a VAG.") - - details = { - TestData.username: "root", - TestData.password: "solidfire", - TestData.url: "http://" + host.ipaddress, - TestData.podId : host.podid, - TestData.zoneId: host.zoneid - } - - host = Host.create( - self.apiClient, - self.cluster, - details, - hypervisor=host.hypervisor - ) - - self.assertTrue( - isinstance(host, Host), - "'host' is not a 'Host'." - ) - - hosts = list_hosts(self.apiClient, clusterid=self.cluster.id) - - unique_vag_ids = self._get_unique_vag_ids(hosts) - - self.assertTrue(len(hosts) == len(unique_vag_ids) + 1, "There should be one more host than unique VAG.") - - def _get_unique_vag_ids(self, hosts): - all_vags = sf_util.get_all_vags(self.sfe) - - unique_vag_ids = [] - - for host in hosts: - host = Host(host.__dict__) - - host_iqn = self._get_host_iqn(host) - - host_vag = self._get_host_vag(host_iqn, all_vags) - - if host_vag != None and host_vag.volume_access_group_id not in unique_vag_ids: - unique_vag_ids.append(host_vag.volume_access_group_id) - - return unique_vag_ids - - def _get_host_vag(self, host_iqn, vags): - self.assertTrue(host_iqn, "'host_iqn' should not be 'None'.") - self.assertTrue(vags, "'vags' should not be 'None'.") - - self.assertTrue(isinstance(host_iqn, str), "'host_iqn' should be a 'string'.") - self.assertTrue(isinstance(vags, list), "'vags' should be a 'list'.") - - for vag in vags: - if host_iqn in vag.initiators: - return vag - - return None - - def _perform_add_remove_xenserver_host(self, primary_storage_id, sr_name): - xen_sr = self.xen_session.xenapi.SR.get_by_name_label(sr_name)[0] - - pbds = self.xen_session.xenapi.SR.get_PBDs(xen_sr) - - self._verify_all_pbds_attached(pbds) - - num_pbds = len(pbds) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, primary_storage_id, self) - - host_iscsi_iqns = self._get_xenserver_host_iscsi_iqns() - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self._verifyVag(host_iscsi_iqns, sf_vag_initiators) - - sf_vag_initiators_len_orig = len(sf_vag_initiators) - - xen_session = XenAPI.Session("https://" + TestData.ip_address_of_new_xenserver_host) - - xenserver = self.testdata[TestData.xenServer] - - xen_session.xenapi.login_with_password(xenserver[TestData.username], xenserver[TestData.password]) - - xen_session.xenapi.pool.join(self.xs_pool_master_ip, xenserver[TestData.username], xenserver[TestData.password]) - - time.sleep(60) - - pbds = self.xen_session.xenapi.SR.get_PBDs(xen_sr) - - self.assertEqual( - len(pbds), - num_pbds + 1, - "'len(pbds)' is not equal to 'num_pbds + 1'." - ) - - num_pbds = num_pbds + 1 - - num_pbds_not_attached = 0 - - for pbd in pbds: - pbd_record = self.xen_session.xenapi.PBD.get_record(pbd) - - if pbd_record["currently_attached"] == False: - num_pbds_not_attached = num_pbds_not_attached + 1 - - self.assertEqual( - num_pbds_not_attached, - 1, - "'num_pbds_not_attached' is not equal to 1." - ) - - host = Host.create( - self.apiClient, - self.cluster, - self.testdata[TestData.newXenServerHost], - hypervisor="XenServer" - ) - - self.assertTrue( - isinstance(host, Host), - "'host' is not a 'Host'." - ) - - pbds = self.xen_session.xenapi.SR.get_PBDs(xen_sr) - - self.assertEqual( - len(pbds), - num_pbds, - "'len(pbds)' is not equal to 'num_pbds'." - ) - - self._verify_all_pbds_attached(pbds) - - host_iscsi_iqns = self._get_xenserver_host_iscsi_iqns() - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self._verifyVag(host_iscsi_iqns, sf_vag_initiators) - - sf_vag_initiators_len_new = len(sf_vag_initiators) - - self.assertEqual( - sf_vag_initiators_len_new, - sf_vag_initiators_len_orig + 1, - "sf_vag_initiators_len_new' != sf_vag_initiators_len_orig + 1" - ) - - host.delete(self.apiClient) - - pbds = self.xen_session.xenapi.SR.get_PBDs(xen_sr) - - self.assertEqual( - len(pbds), - num_pbds, - "'len(pbds)' is not equal to 'num_pbds'." - ) - - self._verify_all_pbds_attached(pbds) - - host_iscsi_iqns = self._get_xenserver_host_iscsi_iqns() - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self.assertEqual( - len(host_iscsi_iqns) - 1, - len(sf_vag_initiators), - "'len(host_iscsi_iqns) - 1' is not equal to 'len(sf_vag_initiators)'." - ) - - host_ref = self.xen_session.xenapi.host.get_by_name_label(self.testdata[TestData.newHostDisplayName])[0] - - self.xen_session.xenapi.pool.eject(host_ref) - - time.sleep(120) - - pbds = self.xen_session.xenapi.SR.get_PBDs(xen_sr) - - self.assertEqual( - len(pbds), - num_pbds - 1, - "'len(pbds)' is not equal to 'num_pbds - 1'." - ) - - self._verify_all_pbds_attached(pbds) - - host_iscsi_iqns = self._get_xenserver_host_iscsi_iqns() - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self._verifyVag(host_iscsi_iqns, sf_vag_initiators) - - sf_vag_initiators_len_new = len(sf_vag_initiators) - - self.assertEqual( - sf_vag_initiators_len_new, - sf_vag_initiators_len_orig, - "sf_vag_initiators_len_new' != sf_vag_initiators_len_orig" - ) - - def _perform_add_remove_kvm_host(self, primary_storage_id): - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, primary_storage_id, self) - - kvm_login = self.testdata[TestData.kvm] - - kvm_hosts = [] - - kvm_hosts.append(TestData.kvm_1_ip_address) - - host_iscsi_iqns = self._get_kvm_host_iscsi_iqns(kvm_hosts, kvm_login[TestData.username], kvm_login[TestData.password]) - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self._verifyVag(host_iscsi_iqns, sf_vag_initiators) - - sf_vag_initiators_len_orig = len(sf_vag_initiators) - - host = Host.create( - self.apiClient, - self.cluster, - self.testdata[TestData.newKvmHost], - hypervisor="KVM" - ) - - self.assertTrue( - isinstance(host, Host), - "'host' is not a 'Host'." - ) - - kvm_hosts = [] - - kvm_hosts.append(TestData.kvm_1_ip_address) - kvm_hosts.append(TestData.ip_address_of_new_kvm_host) - - host_iscsi_iqns = self._get_kvm_host_iscsi_iqns(kvm_hosts, kvm_login[TestData.username], kvm_login[TestData.password]) - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self._verifyVag(host_iscsi_iqns, sf_vag_initiators) - - sf_vag_initiators_len_new = len(sf_vag_initiators) - - self.assertEqual( - sf_vag_initiators_len_new, - sf_vag_initiators_len_orig + 1, - "sf_vag_initiators_len_new' != sf_vag_initiators_len_orig + 1" - ) - - host.delete(self.apiClient) - - kvm_hosts = [] - - kvm_hosts.append(TestData.kvm_1_ip_address) - - host_iscsi_iqns = self._get_kvm_host_iscsi_iqns(kvm_hosts, kvm_login[TestData.username], kvm_login[TestData.password]) - - sf_vag = self._get_sf_vag(sf_vag_id) - - sf_vag_initiators = self._get_sf_vag_initiators(sf_vag) - - self._verifyVag(host_iscsi_iqns, sf_vag_initiators) - - sf_vag_initiators_len_new = len(sf_vag_initiators) - - self.assertEqual( - sf_vag_initiators_len_new, - sf_vag_initiators_len_orig, - "sf_vag_initiators_len_new' != sf_vag_initiators_len_orig" - ) - - def _verify_all_pbds_attached(self, pbds): - for pbd in pbds: - pbd_record = self.xen_session.xenapi.PBD.get_record(pbd) - - self.assertEqual( - pbd_record["currently_attached"], - True, - "Not all PBDs are currently attached." - ) - - def _get_root_volume(self, vm): - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=vm.id, - listall=True - ) - - self.assertNotEqual( - list_volumes_response, - None, - "'list_volumes_response' should not be equal to 'None'." - ) - - self.assertEqual( - len(list_volumes_response) > 0, - True, - "'len(list_volumes_response)' should be greater than 0." - ) - - for volume in list_volumes_response: - if volume.type.upper() == "ROOT": - return volume - - self.assertTrue(False, "Unable to locate the ROOT volume of the VM with the following ID: " + str(vm.id)) - - def _get_iqn_2(self, primary_storage): - sql_query = "Select path From storage_pool Where uuid = '" + str(primary_storage.id) + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - return sql_result[0][0] - - def _get_host_iqn(self, host): - sql_query = "Select url From host Where uuid = '" + str(host.id) + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - return sql_result[0][0] - - def _get_xenserver_host_iscsi_iqns(self): - hosts = self.xen_session.xenapi.host.get_all() - - self.assertEqual( - isinstance(hosts, list), - True, - "'hosts' is not a list." - ) - - host_iscsi_iqns = [] - - for host in hosts: - host_iscsi_iqns.append(self._get_xenserver_host_iscsi_iqn(host)) - - return host_iscsi_iqns - - def _get_xenserver_host_iscsi_iqn(self, host): - other_config = self.xen_session.xenapi.host.get_other_config(host) - - return other_config["iscsi_iqn"] - - def _get_kvm_host_iscsi_iqns(self, kvm_ip_addresses, common_username, common_password): - host_iscsi_iqns = [] - - for kvm_ip_address in kvm_ip_addresses: - host_iscsi_iqn = self._get_kvm_iqn(kvm_ip_address, common_username, common_password) - - host_iscsi_iqns.append(host_iscsi_iqn) - - return host_iscsi_iqns - - def _get_kvm_iqn(self, ip_address, username, password): - ssh_connection = sf_util.get_ssh_connection(ip_address, username, password) - - searchFor = "InitiatorName=" - - stdout = ssh_connection.exec_command("sudo grep " + searchFor + " /etc/iscsi/initiatorname.iscsi")[1] - - result = stdout.read() - - ssh_connection.close() - - self.assertFalse(result is None, "Unable to locate the IQN of the KVM host (None)") - self.assertFalse(len(result.strip()) == 0, "Unable to locate the IQN of the KVM host (Zero-length string)") - - return result[len(searchFor):].strip() - - def _get_sf_vag(self, sf_vag_id): - return self.sfe.list_volume_access_groups(sf_vag_id, 1).volume_access_groups[0] - - def _get_sf_vag_initiators(self, sf_vag): - return sf_vag.initiators - - def _verifyVag(self, host_iscsi_iqns, sf_vag_initiators): - self.assertEqual( - isinstance(host_iscsi_iqns, list), - True, - "'host_iscsi_iqns' is not a list." - ) - - self.assertEqual( - isinstance(sf_vag_initiators, list), - True, - "'sf_vag_initiators' is not a list." - ) - - self.assertEqual( - len(host_iscsi_iqns), - len(sf_vag_initiators), - "Lists are not the same size." - ) - - for host_iscsi_iqn in host_iscsi_iqns: - # an error should occur if host_iscsi_iqn is not in sf_vag_initiators - sf_vag_initiators.index(host_iscsi_iqn) - - @classmethod - def _connect_to_hypervisor(cls): - if TestData.hypervisor_type == TestData.kvm: - pass - elif TestData.hypervisor_type == TestData.xenServer: - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_master_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xen_server = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password]) diff --git a/test/integration/plugins/solidfire/TestCapacityManagement.py b/test/integration/plugins/solidfire/TestCapacityManagement.py deleted file mode 100644 index 0cc9db2dae1a..000000000000 --- a/test/integration/plugins/solidfire/TestCapacityManagement.py +++ /dev/null @@ -1,333 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, ServiceOffering, StoragePool, User, VirtualMachine - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_hosts - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster -# -# Running the tests: -# If using XenServer, verify the "xen_server_hostname" variable is correct. -# -# Note: -# If you do have more than one cluster, you might need to change this variable: TestData.clusterId. - - -class TestData(): - # constants - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - computeOffering2 = "computeoffering2" - domainId = "domainId" - email = "email" - firstname = "firstname" - hypervisor = "hypervisor" - lastname = "lastname" - mvip = "mvip" - name = "name" - password = "password" - port = "port" - primaryStorage = "primarystorage" - primaryStorage2 = "primarystorage2" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - storageTag2 = "SolidFire_SAN_2" - tags = "tags" - url = "url" - user = "user" - username = "username" - xenServer = "xenserver" - zoneId = "zoneId" - - hypervisor_type = xenServer - xen_server_hostname = "XenServer-6.5-1" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.40.120", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.40.120:443" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - TestData.email: "test@test.com", - TestData.firstname: "John", - TestData.lastname: "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - TestData.email: "user@test.com", - TestData.firstname: "Jane", - TestData.lastname: "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.primaryStorage: { - TestData.name: "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 100000, - TestData.capacityBytes: 214748364800, # 200 GiB - TestData.hypervisor: "Any" - }, - TestData.primaryStorage2: { - TestData.name: "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag2, - TestData.capacityIops: 800, - TestData.capacityBytes: 2251799813685248, # 2 PiB - TestData.hypervisor: "Any" - }, - TestData.computeOffering: { - TestData.name: "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 300; Max IOPS = 600)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "300", - "maxiops": "600", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag - }, - TestData.computeOffering2: { - TestData.name: "SF_CO_2", - "displaytext": "SF_CO_2 (Min IOPS = 300; Max IOPS = 600)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "300", - "maxiops": "600", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag2 - }, - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestCapacityManagement(cloudstackTestCase): - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestCapacityManagement, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - sf_util.set_supports_resign(True, cls.dbConnection) - - cls._connect_to_hypervisor() - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - primarystorage2 = cls.testdata[TestData.primaryStorage2] - - cls.primary_storage_2 = StoragePool.create( - cls.apiClient, - primarystorage2, - scope=primarystorage2[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage2[TestData.provider], - tags=primarystorage2[TestData.tags], - capacityiops=primarystorage2[TestData.capacityIops], - capacitybytes=primarystorage2[TestData.capacityBytes], - hypervisor=primarystorage2[TestData.hypervisor] - ) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - cls.compute_offering_2 = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering2] - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.compute_offering, - cls.compute_offering_2, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - cls.primary_storage_2.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - cleanup_resources(self.apiClient, self.cleanup) - - def test_01_not_enough_storage_space(self): - self._run_vms(self.compute_offering.id) - - def test_02_not_enough_storage_performance(self): - self._run_vms(self.compute_offering_2.id) - - def _run_vms(self, compute_offering_id): - try: - # Based on the primary storage's space or performance and the storage requirements - # of the compute offering, we should fail to create a VM on the third try. - for _ in range(0, 3): - number = random.randint(0, 1000) - - vm_name = { - TestData.name: "VM-%d" % number, - "displayname": "Test VM %d" % number - } - - virtual_machine = VirtualMachine.create( - self.apiClient, - vm_name, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=compute_offering_id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - self.cleanup.append(virtual_machine) - except: - pass - - self.assertEqual( - len(self.cleanup), - 2, - "Only two VMs should have been successfully created." - ) - - @classmethod - def _connect_to_hypervisor(cls): - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xen_server = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password]) diff --git a/test/integration/plugins/solidfire/TestManagedClusteredFilesystems.py b/test/integration/plugins/solidfire/TestManagedClusteredFilesystems.py deleted file mode 100644 index 053dfb6f3374..000000000000 --- a/test/integration/plugins/solidfire/TestManagedClusteredFilesystems.py +++ /dev/null @@ -1,431 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, Cluster, ServiceOffering, Snapshot, StoragePool, User, VirtualMachine, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_hosts, list_volumes - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Two clusters -# -# Running the tests: -# If using XenServer, verify the "xen_server_hostname" variable is correct. -# Set the Global Setting "max.number.managed.clustered.file.systems" equal to 2. -# -# Note: -# Verify that TestData.clusterId and TestData.clusterId2 are set properly. - - -class TestData(): - # constants - account = "account" - allocationstate = "allocationstate" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - clusterId2 = "clusterId2" - computeOffering = "computeoffering" - domainId = "domainId" - email = "email" - firstname = "firstname" - hypervisor = "hypervisor" - lastname = "lastname" - mvip = "mvip" - name = "name" - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - tags = "tags" - url = "url" - user = "user" - username = "username" - xenServer = "xenserver" - zoneId = "zoneId" - - hypervisor_type = xenServer - xen_server_hostname = "XenServer-6.5-1" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.78.225", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.78.225:443" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - TestData.email: "test@test.com", - TestData.firstname: "John", - TestData.lastname: "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - TestData.email: "user@test.com", - TestData.firstname: "Jane", - TestData.lastname: "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.primaryStorage: { - TestData.name: "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.78.225;SVIP=10.117.94.225;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.computeOffering: { - TestData.name: "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 300; Max IOPS = 600)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "300", - "maxiops": "600", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag - }, - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.clusterId2: 6, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestManagedClusteredFilesystems(cloudstackTestCase): - _should_only_be_one_volume_in_list_err_msg = "There should only be one volume in this list." - _volume_should_have_failed_to_attach_to_vm = "The volume should have failed to attach to the VM." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestManagedClusteredFilesystems, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - sf_util.set_supports_resign(True, cls.dbConnection) - - cls._connect_to_hypervisor() - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.compute_offering, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - cleanup_resources(self.apiClient, self.cleanup) - -# Only two 'permanent' SRs per cluster -# -# Disable the second cluster -# -# Create VM -# Create VM -# Create VM (should fail) -# Take snapshot of first root disk -# Create a volume from this snapshot -# Attach new volume to second VM (should fail) -# -# Enable the second cluster -# -# Attach new volume to second VM (should fail) -# Create VM (should end up in new cluster) -# Delete first VM (this should free up one SR in the first cluster) -# Attach new volume to second VM -# Detach new volume from second VM -# Attach new volume to second VM -# Create a volume from the snapshot -# Attach this new volume to the second VM (should fail) -# Attach this new volume to the first VM in the new cluster - def test_managed_clustered_filesystems_limit(self): - args = { "id": self.testdata[TestData.clusterId2], TestData.allocationstate: "Disabled" } - - Cluster.update(self.apiClient, **args) - - virtual_machine_names = { - "name": "TestVM1", - "displayname": "Test VM 1" - } - - virtual_machine_1 = self._create_vm(virtual_machine_names) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_1.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestManagedClusteredFilesystems._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - - virtual_machine_names = { - "name": "TestVM2", - "displayname": "Test VM 2" - } - - virtual_machine_2 = self._create_vm(virtual_machine_names) - - virtual_machine_names = { - "name": "TestVM3", - "displayname": "Test VM 3" - } - - class VMStartedException(Exception): - def __init__(self, *args, **kwargs): - Exception.__init__(self, *args, **kwargs) - - try: - # The VM should fail to be created as there should be an insufficient number of clustered filesystems - # remaining in the compute cluster. - self._create_vm(virtual_machine_names) - - raise VMStartedException("The VM should have failed to start.") - except VMStartedException: - raise - except Exception: - pass - - vol_snap = Snapshot.create( - self.apiClient, - volume_id=vm_1_root_volume.id - ) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot_1 = Volume.create_from_snapshot(self.apiClient, vol_snap.id, services, account=self.account.name, domainid=self.domain.id) - - class VolumeAttachedException(Exception): - def __init__(self, *args, **kwargs): - Exception.__init__(self, *args, **kwargs) - - try: - # The volume should fail to be attached as there should be an insufficient number of clustered filesystems - # remaining in the compute cluster. - virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot_1 - ) - - raise VolumeAttachedException(TestManagedClusteredFilesystems._volume_should_have_failed_to_attach_to_vm) - except VolumeAttachedException: - raise - except Exception: - pass - - args = { "id": self.testdata[TestData.clusterId2], TestData.allocationstate: "Enabled" } - - Cluster.update(self.apiClient, **args) - - try: - # The volume should fail to be attached as there should be an insufficient number of clustered filesystems - # remaining in the compute cluster. - virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot_1 - ) - - raise VolumeAttachedException(TestManagedClusteredFilesystems._volume_should_have_failed_to_attach_to_vm) - except VolumeAttachedException: - raise - except Exception: - pass - - virtual_machine_names = { - "name": "TestVMA", - "displayname": "Test VM A" - } - - virtual_machine_a = self._create_vm(virtual_machine_names) - - host_for_vm_1 = list_hosts(self.apiClient, id=virtual_machine_1.hostid)[0] - host_for_vm_a = list_hosts(self.apiClient, id=virtual_machine_a.hostid)[0] - - self.assertTrue( - host_for_vm_1.clusterid != host_for_vm_a.clusterid, - "VMs 1 and VM a should be in different clusters." - ) - - virtual_machine_1.delete(self.apiClient, True) - - volume_created_from_snapshot_1 = virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot_1 - ) - - virtual_machine_2.detach_volume(self.apiClient, volume_created_from_snapshot_1) - - volume_created_from_snapshot_1 = virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot_1 - ) - - services = {"diskname": "Vol-2", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot_2 = Volume.create_from_snapshot(self.apiClient, vol_snap.id, services, account=self.account.name, domainid=self.domain.id) - - try: - # The volume should fail to be attached as there should be an insufficient number of clustered filesystems - # remaining in the compute cluster. - virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot_2 - ) - - raise VolumeAttachedException(TestManagedClusteredFilesystems._volume_should_have_failed_to_attach_to_vm) - except VolumeAttachedException: - raise - except Exception: - pass - - virtual_machine_a.attach_volume( - self.apiClient, - volume_created_from_snapshot_2 - ) - - def _create_vm(self, virtual_machine_names): - return VirtualMachine.create( - self.apiClient, - virtual_machine_names, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - @classmethod - def _connect_to_hypervisor(cls): - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xen_server = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password]) diff --git a/test/integration/plugins/solidfire/TestManagedSystemVMs.py b/test/integration/plugins/solidfire/TestManagedSystemVMs.py deleted file mode 100644 index 4f2558756e64..000000000000 --- a/test/integration/plugins/solidfire/TestManagedSystemVMs.py +++ /dev/null @@ -1,626 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -from marvin.cloudstackAPI import destroySystemVm - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, Router, ServiceOffering, StoragePool, User, VirtualMachine, Zone - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_ssvms, list_routers - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources, wait_until - -# Prerequisites: -# * Only use one SolidFire cluster for the two primary storages based on the "SolidFire" storage plug-in. -# * Do not run other workloads on the SolidFire cluster while running this test as this test checks at a certain -# point to make sure no active SolidFire volumes exist. -# * Only one zone -# * Only one secondary storage VM and one console proxy VM running on NFS (no virtual router or user VMs exist) -# * Only one pod -# * Only one cluster -# -# Running the tests: -# Change the "hypervisor_type" variable to control which hypervisor type to test. -# If using XenServer, verify the "xen_server_hostname" variable is correct. -# Set the Global Setting "storage.cleanup.enabled" to true. -# Set the Global Setting "storage.cleanup.interval" to 150. -# Set the Global Setting "storage.cleanup.delay" to 60. - - -class TestData(): - # constants - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterid" - computeOffering = "computeoffering" - diskOffering = "diskoffering" - domainId = "domainid" - email = "email" - firstname = "firstname" - hypervisor = "hypervisor" - kvm = "kvm" - lastname = "lastname" - max_iops = "maxiops" - min_iops = "miniops" - mvip = "mvip" - name = "name" - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - systemOffering = "systemoffering" - systemOfferingFailure = "systemofferingFailure" - tags = "tags" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - xenServer = "xenserver" - zoneId = "zoneid" - - # modify to control which hypervisor type to test - hypervisor_type = xenServer - xen_server_hostname = "XenServer-6.5-1" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.40.120", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.40.120:443" - }, - TestData.kvm: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - TestData.email: "test@test.com", - TestData.firstname: "John", - TestData.lastname: "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - TestData.email: "user@test.com", - TestData.firstname: "Jane", - TestData.lastname: "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.primaryStorage: { - TestData.name: TestData.get_name_for_solidfire_storage(), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any", - TestData.zoneId: 1 - }, - TestData.virtualMachine: { - TestData.name: "TestVM", - "displayname": "Test VM" - }, - TestData.computeOffering: { - TestData.name: "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - TestData.min_iops: 10000, - TestData.max_iops: 15000, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag - }, - TestData.systemOffering: { - TestData.name: "SF_SO_1", - "displaytext": "Managed SO (Min IOPS = 4,000; Max IOPS = 8,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - TestData.min_iops: 4000, - TestData.max_iops: 8000, - TestData.tags: TestData.storageTag, - "issystem": True - }, - TestData.systemOfferingFailure: { - TestData.name: "SF_SO_2", - "displaytext": "Managed SO (Customized IOPS)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": True, - TestData.tags: TestData.storageTag, - "issystem": True - }, - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - @staticmethod - def get_name_for_solidfire_storage(): - return "SolidFire-%d" % random.randint(0, 100) - - -class TestManagedSystemVMs(cloudstackTestCase): - _unique_name_suffix = "-Temp" - - _secondary_storage_unique_name = "Cloud.com-SecondaryStorage" - _secondary_storage_temp_unique_name = _secondary_storage_unique_name + _unique_name_suffix - - _console_proxy_unique_name = "Cloud.com-ConsoleProxy" - _console_proxy_temp_unique_name = _console_proxy_unique_name + _unique_name_suffix - - _virtual_router_unique_name = "Cloud.com-SoftwareRouter" - _virtual_router_temp_unique_name = _virtual_router_unique_name + _unique_name_suffix - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestManagedSystemVMs, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - cls._connect_to_hypervisor() - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = Zone(get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]).__dict__) - cls.cluster = list_clusters(cls.apiClient)[0] - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - systemoffering = cls.testdata[TestData.systemOffering] - - systemoffering[TestData.name] = "Managed SSVM" - systemoffering['systemvmtype'] = "secondarystoragevm" - - cls.secondary_storage_offering = ServiceOffering.create( - cls.apiClient, - systemoffering - ) - - systemoffering[TestData.name] = "Managed CPVM" - systemoffering['systemvmtype'] = "consoleproxy" - - cls.console_proxy_offering = ServiceOffering.create( - cls.apiClient, - systemoffering - ) - - systemoffering[TestData.name] = "Managed VR" - systemoffering['systemvmtype'] = "domainrouter" - - cls.virtual_router_offering = ServiceOffering.create( - cls.apiClient, - systemoffering - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.secondary_storage_offering, - cls.console_proxy_offering, - cls.virtual_router_offering, - cls.compute_offering, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - try: - cleanup_resources(self.apiClient, self.cleanup) - - sf_util.purge_solidfire_volumes(self.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(self): %s" % e) - - def test_01_create_system_vms_on_managed_storage(self): - self._disable_zone_and_delete_system_vms(None, False) - - primary_storage = self.testdata[TestData.primaryStorage] - - primary_storage_1 = StoragePool.create( - self.apiClient, - primary_storage - ) - - self._prepare_to_use_managed_storage_for_system_vms() - - enabled = "Enabled" - - self.zone.update(self.apiClient, id=self.zone.id, allocationstate=enabled) - - system_vms = self._wait_for_and_get_running_system_vms(2) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - # This virtual machine was only created and started so that the virtual router would be created and started. - # Just delete this virtual machine once it has been created and started. - virtual_machine.delete(self.apiClient, True) - - virtual_router = list_routers(self.apiClient, listall=True, state="Running")[0] - - system_vms.append(virtual_router) - - self._check_system_vms(system_vms, primary_storage_1.id) - - primary_storage[TestData.name] = TestData.get_name_for_solidfire_storage() - - primary_storage_2 = StoragePool.create( - self.apiClient, - primary_storage - ) - - StoragePool.enableMaintenance(self.apiClient, primary_storage_1.id) - - self._wait_for_storage_cleanup_thread(system_vms) - - sf_util.purge_solidfire_volumes(self.sfe) - - system_vms = self._wait_for_and_get_running_system_vms(2) - - virtual_router = list_routers(self.apiClient, listall=True, state="Running")[0] - - system_vms.append(virtual_router) - - self._check_system_vms(system_vms, primary_storage_2.id) - - StoragePool.cancelMaintenance(self.apiClient, primary_storage_1.id) - - primary_storage_1.delete(self.apiClient) - - self._disable_zone_and_delete_system_vms(virtual_router) - - self._wait_for_storage_cleanup_thread(system_vms) - - sf_util.purge_solidfire_volumes(self.sfe) - - primary_storage_2.delete(self.apiClient) - - self._verify_no_active_solidfire_volumes() - - self._prepare_to_stop_using_managed_storage_for_system_vms() - - self.zone.update(self.apiClient, id=self.zone.id, allocationstate=enabled) - - self._wait_for_and_get_running_system_vms(2) - - def test_02_failure_to_create_service_offering_with_customized_iops(self): - try: - ServiceOffering.create( - self.apiClient, - self.testdata[TestData.systemOfferingFailure] - ) - except: - return - - self.assertTrue(False, "The service offering was created, but should not have been.") - - def _prepare_to_use_managed_storage_for_system_vms(self): - self._update_system_vm_unique_name(TestManagedSystemVMs._secondary_storage_unique_name, TestManagedSystemVMs._secondary_storage_temp_unique_name) - self._update_system_vm_unique_name(TestManagedSystemVMs._console_proxy_unique_name, TestManagedSystemVMs._console_proxy_temp_unique_name) - self._update_system_vm_unique_name(TestManagedSystemVMs._virtual_router_unique_name, TestManagedSystemVMs._virtual_router_temp_unique_name) - - self._update_system_vm_unique_name_based_on_uuid(self.secondary_storage_offering.id, TestManagedSystemVMs._secondary_storage_unique_name) - self._update_system_vm_unique_name_based_on_uuid(self.console_proxy_offering.id, TestManagedSystemVMs._console_proxy_unique_name) - self._update_system_vm_unique_name_based_on_uuid(self.virtual_router_offering.id, TestManagedSystemVMs._virtual_router_unique_name) - - def _prepare_to_stop_using_managed_storage_for_system_vms(self): - self._update_system_vm_unique_name_based_on_uuid(self.secondary_storage_offering.id, None) - self._update_system_vm_unique_name_based_on_uuid(self.console_proxy_offering.id, None) - self._update_system_vm_unique_name_based_on_uuid(self.virtual_router_offering.id, None) - - self._update_system_vm_unique_name(TestManagedSystemVMs._secondary_storage_temp_unique_name, TestManagedSystemVMs._secondary_storage_unique_name) - self._update_system_vm_unique_name(TestManagedSystemVMs._console_proxy_temp_unique_name, TestManagedSystemVMs._console_proxy_unique_name) - self._update_system_vm_unique_name(TestManagedSystemVMs._virtual_router_temp_unique_name, TestManagedSystemVMs._virtual_router_unique_name) - - def _wait_for_storage_cleanup_thread(self, system_vms): - retry_interval = 60 - num_tries = 10 - - wait_result, return_val = wait_until(retry_interval, num_tries, self._check_resource_state, system_vms) - - if not wait_result: - raise Exception(return_val) - - def _check_resource_state(self, system_vms): - try: - self._verify_system_vms_deleted(system_vms) - - return True, None - except: - return False, "The system is not in the necessary state." - - def _verify_system_vms_deleted(self, system_vms): - for system_vm in system_vms: - cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Expunged') - - self._verify_managed_system_vm_deleted(cs_root_volume.name) - - def _disable_zone_and_delete_system_vms(self, virtual_router, verify_managed_system_vm_deleted=True): - self.zone.update(self.apiClient, id=self.zone.id, allocationstate="Disabled") - - if virtual_router is not None: - Router.destroy(self.apiClient, virtual_router.id) - - if verify_managed_system_vm_deleted: - cs_root_volume = self._get_root_volume_for_system_vm(virtual_router.id, 'Expunged') - - self._verify_managed_system_vm_deleted(cs_root_volume.name) - - # list_ssvms lists the secondary storage VM and the console proxy VM - system_vms = list_ssvms(self.apiClient) - - for system_vm in system_vms: - destroy_ssvm_cmd = destroySystemVm.destroySystemVmCmd() - - destroy_ssvm_cmd.id = system_vm.id - - self.apiClient.destroySystemVm(destroy_ssvm_cmd) - - if verify_managed_system_vm_deleted: - cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Expunged') - - self._verify_managed_system_vm_deleted(cs_root_volume.name) - - def _verify_managed_system_vm_deleted(self, cs_root_volume_name): - sf_not_active_volumes = sf_util.get_not_active_sf_volumes(self.sfe) - - sf_root_volume = sf_util.check_and_get_sf_volume(sf_not_active_volumes, cs_root_volume_name, self) - - self.assertEqual( - len(sf_root_volume.volume_access_groups), - 0, - "The volume should not be in a volume access group." - ) - - if TestData.hypervisor_type == TestData.xenServer: - sr_name = sf_util.format_iqn(sf_root_volume.iqn) - - sf_util.check_xen_sr(sr_name, self.xen_session, self, False) - elif TestData.hypervisor_type == TestData.kvm: - list_hosts_response = list_hosts( - self.apiClient, - type="Routing" - ) - - kvm_login = self.testdata[TestData.kvm] - - sf_util.check_kvm_access_to_volume(sf_root_volume.iqn, list_hosts_response, kvm_login[TestData.username], kvm_login[TestData.password], self, False) - else: - self.assertTrue(False, "Invalid hypervisor type") - - def _wait_for_and_get_running_system_vms(self, expected_number_of_system_vms): - retry_interval = 60 - num_tries = 10 - - wait_result, return_val = wait_until(retry_interval, num_tries, self._check_number_of_running_system_vms, expected_number_of_system_vms) - - if not wait_result: - raise Exception(return_val) - - return return_val - - def _check_number_of_running_system_vms(self, expected_number_of_system_vms): - # list_ssvms lists the secondary storage VM and the console proxy VM - system_vms = list_ssvms(self.apiClient, state="Running") - - if system_vms is not None and len(system_vms) == expected_number_of_system_vms: - return True, system_vms - - return False, "Timed out waiting for running system VMs" - - def _verify_no_active_solidfire_volumes(self): - sf_active_volumes = sf_util.get_active_sf_volumes(self.sfe) - - sf_util.check_list(sf_active_volumes, 0, self, "There should be no active SolidFire volumes in the cluster.") - - def _check_system_vms(self, system_vms, primary_storage_id): - sf_active_volumes = sf_util.get_active_sf_volumes(self.sfe) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, primary_storage_id, self) - - for system_vm in system_vms: - cs_root_volume = self._get_root_volume_for_system_vm(system_vm.id, 'Ready') - sf_root_volume = sf_util.check_and_get_sf_volume(sf_active_volumes, cs_root_volume.name, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, cs_root_volume, self) - - sf_util.check_size_and_iops(sf_root_volume, cs_root_volume, sf_volume_size, self) - - self._check_iops_against_iops_of_system_offering(cs_root_volume, self.testdata[TestData.systemOffering]) - - sf_util.check_vag(sf_root_volume, sf_vag_id, self) - - if TestData.hypervisor_type == TestData.xenServer: - sr_name = sf_util.format_iqn(sf_root_volume.iqn) - - sf_util.check_xen_sr(sr_name, self.xen_session, self) - elif TestData.hypervisor_type == TestData.kvm: - list_hosts_response = list_hosts( - self.apiClient, - type="Routing" - ) - - kvm_login = self.testdata[TestData.kvm] - - sf_util.check_kvm_access_to_volume(sf_root_volume.iqn, list_hosts_response, kvm_login[TestData.username], kvm_login[TestData.password], self) - else: - self.assertTrue(False, "Invalid hypervisor type") - - def _check_iops_against_iops_of_system_offering(self, cs_volume, system_offering): - self.assertEqual( - system_offering[TestData.min_iops], - cs_volume.miniops, - "Check QoS - Min IOPS: of " + cs_volume.name + " should be " + str(system_offering[TestData.min_iops]) - ) - - self.assertEqual( - system_offering[TestData.max_iops], - cs_volume.maxiops, - "Check QoS - Min IOPS: of " + cs_volume.name + " should be " + str(system_offering[TestData.max_iops]) - ) - - def _get_root_volume_for_system_vm(self, system_vm_id, state): - sql_query = "Select id From vm_instance Where uuid = '" + system_vm_id + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - instance_id = sql_result[0][0] - - sql_query = "Select uuid, name, min_iops, max_iops From volumes Where instance_id = " + str(instance_id) + \ - " and state = '" + state + "' Order by removed desc" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - uuid = sql_result[0][0] - name = sql_result[0][1] - min_iops = sql_result[0][2] - max_iops = sql_result[0][3] - - class CloudStackVolume(object): - pass - - cs_volume = CloudStackVolume() - - cs_volume.id = uuid - cs_volume.name = name - cs_volume.miniops = min_iops - cs_volume.maxiops = max_iops - - return cs_volume - - def _update_system_vm_unique_name(self, unique_name, new_unique_name): - sql_query = "Update disk_offering set unique_name = '" + new_unique_name + "' Where unique_name = '" + unique_name + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - self.dbConnection.execute(sql_query) - - def _update_system_vm_unique_name_based_on_uuid(self, uuid, new_unique_name): - if (new_unique_name is None): - sql_query = "Update disk_offering set unique_name = NULL Where uuid = '" + uuid + "'" - else: - sql_query = "Update disk_offering set unique_name = '" + new_unique_name + "' Where uuid = '" + uuid + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - self.dbConnection.execute(sql_query) - - @classmethod - def _connect_to_hypervisor(cls): - if TestData.hypervisor_type == TestData.kvm: - pass - elif TestData.hypervisor_type == TestData.xenServer: - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xen_server = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password]) diff --git a/test/integration/plugins/solidfire/TestOnlineStorageMigration.py b/test/integration/plugins/solidfire/TestOnlineStorageMigration.py deleted file mode 100644 index f7d8c14e9129..000000000000 --- a/test/integration/plugins/solidfire/TestOnlineStorageMigration.py +++ /dev/null @@ -1,402 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, ServiceOffering, Snapshot, StoragePool, User, VirtualMachine, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import list_clusters, get_domain, list_hosts, list_snapshots, get_template, list_volumes, get_zone - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster -# -# Running the tests: -# If using XenServer, verify the "xen_server_hostname" variable is correct. -# -# Note: -# If you do have more than one cluster, you might need to change this line: cls.cluster = list_clusters(cls.apiClient)[0] - - -class TestData(): - # constants - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - domainId = "domainId" - email = "email" - firstname = "firstname" - hypervisor = "hypervisor" - lastname = "lastname" - managementServer = "managementServer" - mvip = "mvip" - name = "name" - nfs_folder = "/export/primary2" - nfs_path = "nfs://10.117.40.114" + nfs_folder - nfs_storage_tag = "NFS-123" - password = "password" - podId = "podId" - port = "port" - primaryStorage = "primarystorage" - primaryStorage2 = "primarystorage2" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - tags = "tags" - url = "url" - user = "user" - username = "username" - xenServer = "xenserver" - zoneId = "zoneId" - - hypervisor_type = xenServer - xen_server_hostname = "XenServer-6.5-1" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.40.120", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.40.120:443" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.managementServer: { - TestData.username: "cloudstack", - TestData.password: "solidfire" - }, - TestData.account: { - TestData.email: "test@test.com", - TestData.firstname: "John", - TestData.lastname: "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - TestData.email: "user@test.com", - TestData.firstname: "Jane", - TestData.lastname: "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.primaryStorage: { - TestData.name: "NFS-%d" % random.randint(0, 100), - TestData.scope: "CLUSTER", - TestData.clusterId: 1, - TestData.url: TestData.nfs_path, - TestData.tags: TestData.nfs_storage_tag - }, - TestData.primaryStorage2: { - TestData.name: "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, # 2 PiB - TestData.hypervisor: "Any" - }, - TestData.computeOffering: { - TestData.name: "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 300; Max IOPS = 600)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "300", - "maxiops": "600", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.nfs_storage_tag - }, - TestData.zoneId: 1, - TestData.podId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestOnlineStorageMigration(cloudstackTestCase): - _should_only_be_one_volume_in_list_err_msg = "There should only be one volume in this list." - _volume_not_on_correct_primary_storage = "The volume is not on the correct primary storage." - _snapshot_not_associated_with_correct_volume = "The snapshot is not associated with the correct volume." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestOnlineStorageMigration, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - sf_util.set_supports_resign(True, cls.dbConnection) - - cls._connect_to_hypervisor() - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.cluster = list_clusters(cls.apiClient)[0] - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - podid=cls.testdata[TestData.podId], - clusterid=cls.cluster.id, - tags=primarystorage[TestData.tags] - ) - - primarystorage2 = cls.testdata[TestData.primaryStorage2] - - cls.primary_storage_2 = StoragePool.create( - cls.apiClient, - primarystorage2, - scope=primarystorage2[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage2[TestData.provider], - tags=primarystorage2[TestData.tags], - capacityiops=primarystorage2[TestData.capacityIops], - capacitybytes=primarystorage2[TestData.capacityBytes], - hypervisor=primarystorage2[TestData.hypervisor] - ) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.compute_offering, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - cls.primary_storage_2.delete(cls.apiClient) - - ms = cls.testdata[TestData.managementServer] - ip_address = cls.testdata[TestData.url] - - cls._delete_all_files(ip_address, ms[TestData.username], ms[TestData.password], TestData.nfs_folder) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - cleanup_resources(self.apiClient, self.cleanup) - - def test_online_migrate_volume_from_nfs_storage_to_managed_storage(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - virtual_machine = VirtualMachine.create( - self.apiClient, - self._get_vm_name(), - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - self.cleanup.append(virtual_machine) - - vm_root_volume = self._get_only_volume(virtual_machine.id) - - self._verify_volume_on_primary_storage(vm_root_volume, self.primary_storage) - - # Migrate the root disk from NFS storage to managed storage. - - Volume.migrate(self.apiClient, livemigrate=True, volumeid=vm_root_volume.id, storageid=self.primary_storage_2.id) - - vm_root_volume = self._get_only_volume(virtual_machine.id) - - self._verify_volume_on_primary_storage(vm_root_volume, self.primary_storage_2) - - def test_online_migrate_volume_with_snapshot_from_nfs_storage_to_managed_storage(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - virtual_machine = VirtualMachine.create( - self.apiClient, - self._get_vm_name(), - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - self.cleanup.append(virtual_machine) - - vm_root_volume = self._get_only_volume(virtual_machine.id) - - self._verify_volume_on_primary_storage(vm_root_volume, self.primary_storage) - - vol_snap = Snapshot.create( - self.apiClient, - volume_id=vm_root_volume.id - ) - - self.cleanup.append(vol_snap) - - self._verify_snapshot_belongs_to_volume(vol_snap.id, vm_root_volume.id) - - # Migrate the root disk from NFS storage to managed storage. - - Volume.migrate(self.apiClient, livemigrate=True, volumeid=vm_root_volume.id, storageid=self.primary_storage_2.id) - - vm_root_volume = self._get_only_volume(virtual_machine.id) - - self._verify_volume_on_primary_storage(vm_root_volume, self.primary_storage_2) - - self._verify_snapshot_belongs_to_volume(vol_snap.id, vm_root_volume.id) - - def _verify_snapshot_belongs_to_volume(self, snapshot_id, volume_id): - snapshot = list_snapshots( - self.apiClient, - id=snapshot_id - )[0] - - self.assertEqual( - snapshot.volumeid, - volume_id, - TestOnlineStorageMigration._snapshot_not_associated_with_correct_volume - ) - - def _get_only_volume(self, virtual_machine_id): - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestOnlineStorageMigration._should_only_be_one_volume_in_list_err_msg) - - return list_volumes_response[0] - - def _verify_volume_on_primary_storage(self, vm_root_volume, primary_storage): - self.assertEqual( - vm_root_volume.storageid, - primary_storage.id, - TestOnlineStorageMigration._volume_not_on_correct_primary_storage - ) - - def _get_vm_name(self): - number = random.randint(0, 1000) - - vm_name = { - TestData.name: "VM-%d" % number, - "displayname": "Test VM %d" % number - } - - return vm_name - - @classmethod - def _delete_all_files(cls, ip_address, username, password, path): - ssh_connection = sf_util.get_ssh_connection(ip_address, username, password) - - ssh_connection.exec_command("sudo rm -rf " + path + "/*") - - ssh_connection.close() - - @classmethod - def _connect_to_hypervisor(cls): - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xen_server = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password]) diff --git a/test/integration/plugins/solidfire/TestSnapshots.py b/test/integration/plugins/solidfire/TestSnapshots.py deleted file mode 100644 index 722400385ed3..000000000000 --- a/test/integration/plugins/solidfire/TestSnapshots.py +++ /dev/null @@ -1,1769 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import time - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -from nose.plugins.attrib import attr - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, DiskOffering, ServiceOffering, Snapshot, StoragePool, Template, User, VirtualMachine, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_volumes, list_snapshots - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources, wait_until - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster -# -# Running the tests: -# Change the "hypervisor_type" variable to control which hypervisor type to test. -# If using KVM, set the Global Setting "kvm.snapshot.enabled" equal to true. - - -class TestData(): - # constants - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - diskName = "diskname" - diskOffering = "diskoffering" - domainId = "domainId" - hypervisor = "hypervisor" - kvm = "kvm" - mvip = "mvip" - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - tags = "tags" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - vmWare = "vmware" - volume_1 = "volume_1" - volume_2 = "volume_2" - xenServer = "xenserver" - zoneId = "zoneId" - - # modify to control which hypervisor type to test - hypervisor_type = xenServer - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.78.225", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.78.225:443" - }, - TestData.primaryStorage: { - "name": "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - "url": "MVIP=10.117.78.225;SVIP=10.117.94.225;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - "username": "test", - "password": "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.virtualMachine: { - "name": "TestVM", - "displayname": "Test VM" - }, - TestData.computeOffering: { - "name": "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 200, - "tags": "SolidFire_SAN_1" - }, - TestData.diskOffering: { - "name": "SF_DO_1", - "displaytext": "SF_DO_1 (Min IOPS = 300; Max IOPS = 500)", - "disksize": 128, - "customizediops": False, - "miniops": 300, - "maxiops": 500, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - TestData.volume_1: { - TestData.diskName: "test-volume", - }, - TestData.volume_2: { - TestData.diskName: "test-volume-2", - }, - TestData.zoneId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestSnapshots(cloudstackTestCase): - _should_be_zero_volume_access_groups_in_list_err_msg = "There shouldn't be any volume access groups in this list." - _should_be_zero_snapshots_in_list_err_msg = "There shouldn't be any snapshots in this list." - _should_only_be_one_snapshot_in_list_err_msg = "There should only be one snapshot in this list." - _should_be_two_snapshots_in_list_err_msg = "There should be two snapshots in this list." - _should_be_three_snapshots_in_list_err_msg = "There should be three snapshots in this list." - _should_be_zero_volumes_in_list_err_msg = "There shouldn't be any volumes in this list." - _should_only_be_one_volume_in_list_err_msg = "There should only be one volume in this list." - _should_be_two_volumes_in_list_err_msg = "There should be two volumes in this list." - _should_be_three_volumes_in_list_err_msg = "There should be three volumes in this list." - _should_be_four_volumes_in_list_err_msg = "There should be four volumes in this list." - _should_be_five_volumes_in_list_err_msg = "There should be five volumes in this list." - _should_be_six_volumes_in_list_err_msg = "There should be six volumes in this list." - _should_be_seven_volumes_in_list_err_msg = "There should be seven volumes in this list." - _should_be_five_items_in_list_err_msg = "There should be five items in this list." - _should_be_six_items_in_list_err_msg = "There should be six items in this list." - _should_be_seven_items_in_list_err_msg = "There should be seven items in this list." - _sf_account_id_should_be_non_zero_int_err_msg = "The SolidFire account ID should be a non-zero integer." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestSnapshots, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - cls.disk_offering = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering] - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.compute_offering, - cls.disk_offering, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - cleanup_resources(self.apiClient, self.cleanup) - - def test_01_create_volume_snapshot_using_sf_snapshot(self): - if TestData.hypervisor_type == TestData.xenServer: - sf_util.set_supports_resign(True, self.dbConnection) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestSnapshots._sf_account_id_should_be_non_zero_int_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - primary_storage_db_id = self._get_cs_storage_pool_db_id(self.primary_storage) - - vol_snap_1 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - vol_snap_3 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 3, TestSnapshots._should_be_three_snapshots_in_list_err_msg) - - self._delete_and_test_snapshot(vol_snap_2) - - self._delete_and_test_snapshot(vol_snap_1) - - self._delete_and_test_snapshot(vol_snap_3) - - vol_snap_1 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - self._delete_and_test_snapshot(vol_snap_1) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - self._delete_and_test_snapshot(vol_snap_2) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 0, self, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - vol_snap_1 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - vol_snap_3 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 3, TestSnapshots._should_be_three_snapshots_in_list_err_msg) - - services = {"displaytext": "Template-1", "name": "Template-1-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template = Template.create_from_snapshot(self.apiClient, vol_snap_2, services) - - self.cleanup.append(template) - - virtual_machine_dict = {"name": "TestVM2", "displayname": "Test VM 2"} - - virtual_machine_2 = VirtualMachine.create( - self.apiClient, - virtual_machine_dict, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_2.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_2_root_volume = list_volumes_response[0] - vm_2_root_volume_name = vm_2_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots_2 = self.sfe.list_snapshots(volume_id=sf_volume_2.volume_id).snapshots - - sf_util.check_list(sf_snapshots_2, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - vol_snap_a = self._create_and_test_snapshot(vm_2_root_volume, sf_volume_2, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot = Volume.create_from_snapshot(self.apiClient, vol_snap_a.id, services, account=self.account.name, domainid=self.domain.id) - - volume_created_from_snapshot_name = volume_created_from_snapshot.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 3, self, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - sf_util.check_list(sf_volume_3.volume_access_groups, 0, self, TestSnapshots._should_be_zero_volume_access_groups_in_list_err_msg) - - volume_created_from_snapshot = virtual_machine.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - self._delete_and_test_snapshot(vol_snap_a) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 3, self, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - volume_created_from_snapshot = virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - self._delete_and_test_snapshot(vol_snap_2) - - self._delete_and_test_snapshot(vol_snap_3) - - self._delete_and_test_snapshot(vol_snap_1) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - virtual_machine_2.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - list_volumes_response = list_volumes( - self.apiClient, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - data_volume = list_volumes_response[0] - - data_volume = Volume(data_volume.__dict__) - - data_volume.delete(self.apiClient) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 0, self, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - @attr(hypervisor='XenServer') - def test_02_create_volume_snapshot_using_sf_volume(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - sf_util.set_supports_resign(False, self.dbConnection) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestSnapshots._sf_account_id_should_be_non_zero_int_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - primary_storage_db_id = self._get_cs_storage_pool_db_id(self.primary_storage) - - sf_volume_id = sf_volume.volume_id - sf_volume_size = sf_volume.total_size - - vol_snap_1 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 1, primary_storage_db_id, sf_volume_size, - sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 2, primary_storage_db_id, sf_volume_size, - sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - vol_snap_3 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 3, primary_storage_db_id, sf_volume_size, - sf_account_id, 4, TestSnapshots._should_be_four_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_2, sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_1, sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_3, sf_account_id, 1, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vol_snap_1 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 4, primary_storage_db_id, sf_volume_size, - sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 5, primary_storage_db_id, sf_volume_size, - sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_1, sf_account_id, 1, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_2, sf_account_id, 0, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - sf_volume_id = sf_volume.volume_id - sf_volume_size = sf_volume.total_size - - vol_snap_1 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 1, primary_storage_db_id, sf_volume_size, - sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 2, primary_storage_db_id, sf_volume_size, - sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - vol_snap_3 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 3, primary_storage_db_id, sf_volume_size, - sf_account_id, 4, TestSnapshots._should_be_four_volumes_in_list_err_msg) - - services = {"displaytext": "Template-1", "name": "Template-1-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template = Template.create_from_snapshot(self.apiClient, vol_snap_2, services) - - self.cleanup.append(template) - - virtual_machine_dict = {"name": "TestVM2", "displayname": "Test VM 2"} - - virtual_machine_2 = VirtualMachine.create( - self.apiClient, - virtual_machine_dict, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_2.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_2_root_volume = list_volumes_response[0] - vm_2_root_volume_name = vm_2_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 5, self, TestSnapshots._should_be_five_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots_2 = self.sfe.list_snapshots(volume_id=sf_volume_2.volume_id).snapshots - - sf_util.check_list(sf_snapshots_2, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - sf_volume_id_2 = sf_volume_2.volume_id - sf_volume_size_2 = sf_volume_2.total_size - - vol_snap_a = self._create_and_test_snapshot_2(vm_2_root_volume.id, sf_volume_id_2, sf_volume_id + 5, primary_storage_db_id, sf_volume_size_2, - sf_account_id, 6, TestSnapshots._should_be_six_volumes_in_list_err_msg) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot = Volume.create_from_snapshot(self.apiClient, vol_snap_a.id, services, account=self.account.name, domainid=self.domain.id) - - volume_created_from_snapshot_name = volume_created_from_snapshot.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 7, self, TestSnapshots._should_be_seven_volumes_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - sf_util.check_list(sf_volume_3.volume_access_groups, 0, self, TestSnapshots._should_be_zero_volume_access_groups_in_list_err_msg) - - volume_created_from_snapshot = virtual_machine.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - self._delete_and_test_snapshot_2(vol_snap_a, sf_account_id, 6, TestSnapshots._should_be_six_volumes_in_list_err_msg) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 5, self, TestSnapshots._should_be_five_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - volume_created_from_snapshot = virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - self._delete_and_test_snapshot_2(vol_snap_2, sf_account_id, 4, TestSnapshots._should_be_four_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_3, sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_1, sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - virtual_machine_2.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - list_volumes_response = list_volumes( - self.apiClient, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - data_volume = list_volumes_response[0] - - data_volume = Volume(data_volume.__dict__) - - data_volume.delete(self.apiClient) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 0, self, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - time.sleep(60) - - virtual_machine.stop(self.apiClient, True) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - sf_volume_id = sf_volume.volume_id - sf_volume_size = sf_volume.total_size - - vol_snap_1 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 1, primary_storage_db_id, sf_volume_size, - sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot = Volume.create_from_snapshot(self.apiClient, vol_snap_1.id, services, account=self.account.name, domainid=self.domain.id) - - volume_created_from_snapshot_name = volume_created_from_snapshot.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 3, self, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - sf_util.check_list(sf_volume_2.volume_access_groups, 0, self, TestSnapshots._should_be_zero_volume_access_groups_in_list_err_msg) - - volume_created_from_snapshot = virtual_machine.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - sf_volume_id_2 = sf_volume_2.volume_id - sf_volume_size_2 = sf_volume_2.total_size - - vol_snap_a = self._create_and_test_snapshot_2(volume_created_from_snapshot.id, sf_volume_id_2, sf_volume_id + 3, primary_storage_db_id, sf_volume_size_2, - sf_account_id, 4, TestSnapshots._should_be_four_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_1, sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_a, sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - list_volumes_response = list_volumes( - self.apiClient, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vol_snap_a = self._create_and_test_snapshot_2(volume_created_from_snapshot.id, sf_volume_id_2, sf_volume_id + 4, primary_storage_db_id, sf_volume_size_2, - sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - data_volume = list_volumes_response[0] - - data_volume = Volume(data_volume.__dict__) - - data_volume.delete(self.apiClient) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - list_volumes_response = list_volumes( - self.apiClient, - listall=True - ) - - self.assertEqual( - list_volumes_response, - None, - "'list_volumes_response' should be equal to 'None'." - ) - - self._delete_and_test_snapshot_2(vol_snap_a, sf_account_id, 0, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - @attr(hypervisor='XenServer') - def test_03_create_volume_snapshot_using_sf_volume_and_sf_snapshot(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - sf_util.set_supports_resign(False, self.dbConnection) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestSnapshots._sf_account_id_should_be_non_zero_int_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - primary_storage_db_id = self._get_cs_storage_pool_db_id(self.primary_storage) - - sf_volume_id = sf_volume.volume_id - sf_volume_size = sf_volume.total_size - - vol_snap_1 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 1, primary_storage_db_id, sf_volume_size, - sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot_2(vm_1_root_volume.id, sf_volume_id, sf_volume_id + 2, primary_storage_db_id, sf_volume_size, - sf_account_id, 3, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - sf_util.set_supports_resign(True, self.dbConnection) - - vol_snap_a = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_b = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - services = {"displaytext": "Template-1", "name": "Template-1-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template_1 = Template.create_from_snapshot(self.apiClient, vol_snap_1, services) - - self.cleanup.append(template_1) - - virtual_machine_dict = {"name": "TestVM2", "displayname": "Test VM 2"} - - virtual_machine_2 = VirtualMachine.create( - self.apiClient, - virtual_machine_dict, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template_1.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_2.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_2_root_volume = list_volumes_response[0] - vm_2_root_volume_name = vm_2_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 4, self, TestSnapshots._should_be_four_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume_2.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot_1 = Volume.create_from_snapshot(self.apiClient, vol_snap_2.id, services, account=self.account.name, domainid=self.domain.id) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 5, self, TestSnapshots._should_be_five_volumes_in_list_err_msg) - - volume_created_from_snapshot_1 = virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot_1 - ) - - services = {"displaytext": "Template-A", "name": "Template-A-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template_a = Template.create_from_snapshot(self.apiClient, vol_snap_a, services) - - self.cleanup.append(template_a) - - virtual_machine_dict = {"name": "TestVM3", "displayname": "Test VM 3"} - - virtual_machine_3 = VirtualMachine.create( - self.apiClient, - virtual_machine_dict, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template_a.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_3.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_3_root_volume = list_volumes_response[0] - vm_3_root_volume_name = vm_3_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 6, self, TestSnapshots._should_be_six_volumes_in_list_err_msg) - - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_3_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume_3.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - services = {"diskname": "Vol-A", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot_a = Volume.create_from_snapshot(self.apiClient, vol_snap_b.id, services, account=self.account.name, domainid=self.domain.id) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 7, self, TestSnapshots._should_be_seven_volumes_in_list_err_msg) - - volume_created_from_snapshot_a = virtual_machine_3.attach_volume( - self.apiClient, - volume_created_from_snapshot_a - ) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - # should still be 7 volumes because the SolidFire volume for the root disk of the VM just destroyed - # is still needed for the SolidFire snapshots - sf_util.check_list(sf_volumes, 7, self, TestSnapshots._should_be_seven_volumes_in_list_err_msg) - - virtual_machine_2.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 6, self, TestSnapshots._should_be_six_volumes_in_list_err_msg) - - virtual_machine_3.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 5, self, TestSnapshots._should_be_five_volumes_in_list_err_msg) - - data_volume = Volume(volume_created_from_snapshot_a.__dict__) - - data_volume.delete(self.apiClient) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 4, self, TestSnapshots._should_be_four_volumes_in_list_err_msg) - - data_volume = Volume(volume_created_from_snapshot_1.__dict__) - - data_volume.delete(self.apiClient) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 3, self, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_1, sf_account_id, 2, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - self._delete_and_test_snapshot(vol_snap_b) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - # should still be 2 volumes because the SolidFire volume for the root disk of the VM just destroyed - # is still needed for the SolidFire snapshots - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - self._delete_and_test_snapshot(vol_snap_a) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - self._delete_and_test_snapshot_2(vol_snap_2, sf_account_id, 0, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - @attr(hypervisor='XenServer') - def test_04_create_volume_snapshot_using_sf_snapshot_and_archiving(self): - if TestData.hypervisor_type != TestData.xenServer: - return - - sf_util.set_supports_resign(True, self.dbConnection) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestSnapshots._sf_account_id_should_be_non_zero_int_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - primary_storage_db_id = self._get_cs_storage_pool_db_id(self.primary_storage) - - vol_snap_1_archive = self._create_and_test_archive_snapshot(vm_1_root_volume.id, sf_volume) - - vol_snap_2 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_3_archive = self._create_and_test_archive_snapshot(vm_1_root_volume.id, sf_volume) - - vol_snap_4 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - self._delete_and_test_archive_snapshot(vol_snap_3_archive) - - self._delete_and_test_snapshot(vol_snap_2) - - self._delete_and_test_snapshot(vol_snap_4) - - self._delete_and_test_archive_snapshot(vol_snap_1_archive) - - vol_snap_1_archive = self._create_and_test_archive_snapshot(vm_1_root_volume.id, sf_volume) - - vol_snap_2 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - self._delete_and_test_archive_snapshot(vol_snap_1_archive) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - self._delete_and_test_snapshot(vol_snap_2) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 0, self, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - vol_snap_1 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_2_archive = self._create_and_test_archive_snapshot(vm_1_root_volume.id, sf_volume) - - vol_snap_3 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - vol_snap_4_archive = self._create_and_test_archive_snapshot(vm_1_root_volume.id, sf_volume) - - services = {"displaytext": "Template-1", "name": "Template-1-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template = Template.create_from_snapshot(self.apiClient, vol_snap_2_archive, services) - - self.cleanup.append(template) - - virtual_machine_dict = {"name": "TestVM2", "displayname": "Test VM 2"} - - virtual_machine_2 = VirtualMachine.create( - self.apiClient, - virtual_machine_dict, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine_2.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_2_root_volume = list_volumes_response[0] - vm_2_root_volume_name = vm_2_root_volume.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots_2 = self.sfe.list_snapshots(volume_id=sf_volume_2.volume_id).snapshots - - sf_util.check_list(sf_snapshots_2, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - vol_snap_a_archive = self._create_and_test_archive_snapshot(vm_2_root_volume.id, sf_volume_2) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot = Volume.create_from_snapshot(self.apiClient, vol_snap_a_archive.id, services, account=self.account.name, domainid=self.domain.id) - - volume_created_from_snapshot_name = volume_created_from_snapshot.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 3, self, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - sf_util.check_list(sf_volume_3.volume_access_groups, 0, self, TestSnapshots._should_be_zero_volume_access_groups_in_list_err_msg) - - volume_created_from_snapshot = virtual_machine.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - self._delete_and_test_archive_snapshot(vol_snap_a_archive) - - virtual_machine.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 3, self, TestSnapshots._should_be_three_volumes_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - volume_created_from_snapshot = virtual_machine_2.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - self._delete_and_test_archive_snapshot(vol_snap_4_archive) - - self._delete_and_test_snapshot(vol_snap_1) - - self._delete_and_test_archive_snapshot(vol_snap_2_archive) - - self._delete_and_test_snapshot(vol_snap_3) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_2_root_volume_name) - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - virtual_machine_2.delete(self.apiClient, True) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume_3 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - list_volumes_response = list_volumes( - self.apiClient, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - data_volume = list_volumes_response[0] - - data_volume = Volume(data_volume.__dict__) - - data_volume.delete(self.apiClient) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 0, self, TestSnapshots._should_be_zero_volumes_in_list_err_msg) - - def test_05_create_volume_snapshot_using_sf_snapshot_and_revert_volume_to_snapshot(self): - if TestData.hypervisor_type != TestData.vmWare and TestData.hypervisor_type != TestData.kvm: - return - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - vm_1_root_volume_name = vm_1_root_volume.name - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestSnapshots._sf_account_id_should_be_non_zero_int_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 1, self, TestSnapshots._should_only_be_one_volume_in_list_err_msg) - - sf_volume = sf_util.get_sf_volume_by_name(self, sf_volumes, vm_1_root_volume_name) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume.volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - primary_storage_db_id = self._get_cs_storage_pool_db_id(self.primary_storage) - - vol_snap_1 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot(vm_1_root_volume, sf_volume, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - virtual_machine.stop(self.apiClient, False) - - if TestData.hypervisor_type == TestData.vmWare: - try: - Volume.revertToSnapshot(self.apiClient, vol_snap_1.id) - - self.assertTrue(False, "An exception should have been thrown when trying to revert a volume to a snapshot and the volume is a root disk on VMware.") - except: - pass - else: - Volume.revertToSnapshot(self.apiClient, vol_snap_1.id) - - virtual_machine.start(self.apiClient) - - try: - Volume.revertToSnapshot(self.apiClient, vol_snap_1.id) - - self.assertTrue(False, "An exception should have been thrown when trying to revert a volume to a snapshot and the volume is attached to a running VM.") - except: - pass - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot = Volume.create_from_snapshot(self.apiClient, vol_snap_2.id, services, account=self.account.name, domainid=self.domain.id) - - volume_created_from_snapshot_name = volume_created_from_snapshot.name - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, 2, self, TestSnapshots._should_be_two_volumes_in_list_err_msg) - - sf_volume_2 = sf_util.get_sf_volume_by_name(self, sf_volumes, volume_created_from_snapshot_name) - - self._delete_and_test_snapshot(vol_snap_2) - - self._delete_and_test_snapshot(vol_snap_1) - - vol_snap_1 = self._create_and_test_snapshot(volume_created_from_snapshot, sf_volume_2, primary_storage_db_id, 1, TestSnapshots._should_only_be_one_snapshot_in_list_err_msg) - - vol_snap_2 = self._create_and_test_snapshot(volume_created_from_snapshot, sf_volume_2, primary_storage_db_id, 2, TestSnapshots._should_be_two_snapshots_in_list_err_msg) - - volume_created_from_snapshot = virtual_machine.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - virtual_machine.stop(self.apiClient, False) - - Volume.revertToSnapshot(self.apiClient, vol_snap_1.id) - - virtual_machine.start(self.apiClient) - - try: - Volume.revertToSnapshot(self.apiClient, vol_snap_1.id) - - self.assertTrue(False, "An exception should have been thrown when trying to revert a volume to a snapshot and the volume is attached to a running VM.") - except: - pass - - self._delete_and_test_snapshot(vol_snap_2) - - self._delete_and_test_snapshot(vol_snap_1) - - virtual_machine.delete(self.apiClient, True) - - volume_created_from_snapshot = Volume(volume_created_from_snapshot.__dict__) - - volume_created_from_snapshot.delete(self.apiClient) - - # used when SolidFire snapshots are being used for CloudStack volume snapshots - def _check_snapshot_details(self, sf_snapshot_details, cs_snapshot_id, volume, sf_volume_id, sf_snapshot_id, storage_pool_id, sf_volume_size): - if TestData.hypervisor_type == TestData.vmWare: - expected_num_details = 7 - - err_msg = TestSnapshots._should_be_seven_items_in_list_err_msg - else: - expected_num_details = 6 - - err_msg = TestSnapshots._should_be_six_items_in_list_err_msg - - volume_id = sf_util.get_cs_volume_db_id(self.dbConnection, volume) - - sf_util.check_list(sf_snapshot_details, expected_num_details, self, err_msg) - - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "takeSnapshot", "true") - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "volumeId", sf_volume_id) - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "snapshotId", sf_snapshot_id) - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "sfStoragePoolId", storage_pool_id) - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "sfVolumeSize", sf_volume_size) - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "originalCloudStackVolumeId", volume_id) - - if TestData.hypervisor_type == TestData.vmWare: - self._check_snapshot_detail_with(str.endswith, sf_snapshot_details, cs_snapshot_id, "vmdk", ".vmdk") - - # used when SolidFire volumes are being used for CloudStack volume snapshots - def _check_snapshot_details_2(self, sf_snapshot_details, cs_snapshot_id, sf_volume_id, storage_pool_id, sf_volume_size): - sf_util.check_list(sf_snapshot_details, 5, self, TestSnapshots._should_be_five_items_in_list_err_msg) - - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "volumeId", sf_volume_id) - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "sfStoragePoolId", storage_pool_id) - self._check_snapshot_detail(sf_snapshot_details, cs_snapshot_id, "sfVolumeSize", sf_volume_size) - self._check_snapshot_detail_with(str.startswith, sf_snapshot_details, cs_snapshot_id, "iqn", "/iqn.") - self._check_snapshot_detail_size(sf_snapshot_details, cs_snapshot_id, "path", 36) - - def _check_snapshot_detail(self, sf_snapshot_details_list, cs_snapshot_id, snapshot_detail_key, snapshot_detail_value): - for sf_snapshot_detail_dict in sf_snapshot_details_list: - if sf_snapshot_detail_dict["volumeSnapshotId"] != cs_snapshot_id: - raise Exception("This snapshot detail does not apply to the expected CloudStack volume snapshot.") - - if sf_snapshot_detail_dict["snapshotDetailsName"] == snapshot_detail_key: - if sf_snapshot_detail_dict["snapshotDetailsValue"] == str(snapshot_detail_value): - return - - raise Exception("There is a problem with the snapshot details key '" + snapshot_detail_key + "' and value '" + str(snapshot_detail_value) + "'.") - - def _check_snapshot_detail_with(self, with_f, sf_snapshot_details_list, cs_snapshot_id, snapshot_detail_key, with_str): - for sf_snapshot_detail_dict in sf_snapshot_details_list: - if sf_snapshot_detail_dict["volumeSnapshotId"] != cs_snapshot_id: - raise Exception("This snapshot detail does not apply to the expected CloudStack volume snapshot.") - - if sf_snapshot_detail_dict["snapshotDetailsName"] == snapshot_detail_key: - if with_f(str(sf_snapshot_detail_dict["snapshotDetailsValue"]), with_str): - return - - raise Exception("There is a problem with the snapshot details key '" + snapshot_detail_key + "' and 'starts with/ends with' value '" + with_str + "'.") - - def _check_snapshot_detail_size(self, sf_snapshot_details_list, cs_snapshot_id, snapshot_detail_key, length): - for sf_snapshot_detail_dict in sf_snapshot_details_list: - if sf_snapshot_detail_dict["volumeSnapshotId"] != cs_snapshot_id: - raise Exception("This snapshot detail does not apply to the expected CloudStack volume snapshot.") - - if sf_snapshot_detail_dict["snapshotDetailsName"] == snapshot_detail_key: - if len(sf_snapshot_detail_dict["snapshotDetailsValue"]) == length: - return - - raise Exception("There is a problem with the snapshot details key '" + snapshot_detail_key + "' and 'length' value '" + str(length) + "'.") - - def _most_recent_sf_snapshot(self, sf_snapshots): - sf_util.check_list_not_empty(self, sf_snapshots) - - most_recent_id = 0 - sf_snapshot_to_return = None - - for sf_snapshot in sf_snapshots: - if (sf_snapshot.snapshot_id > most_recent_id): - sf_snapshot_to_return = sf_snapshot - - most_recent_id = sf_snapshot.snapshot_id - - if (sf_snapshot_to_return == None): - raise Exception("Unable to find the most recent SolidFire snapshot in the provided list") - - return sf_snapshot_to_return - - def _get_cs_volume_snapshot_db_id(self, vol_snap): - return sf_util.get_db_id(self.dbConnection, "snapshots", vol_snap) - - def _get_cs_storage_pool_db_id(self, storage_pool): - return sf_util.get_db_id(self.dbConnection, "storage_pool", storage_pool) - - def _get_sf_volume_by_id(self, sf_volumes, sf_volume_id): - sf_util.check_list_not_empty(self, sf_volumes) - - sf_volume = None - - for volume in sf_volumes: - if volume.volume_id == sf_volume_id: - sf_volume = volume - - break - - self.assertNotEqual( - sf_volume, - None, - "The SolidFire volume could not be found in the expected account." - ) - - return sf_volume - - def _get_snapshot_detail(self, sf_snapshot_details_list, key): - for sf_snapshot_detail_dict in sf_snapshot_details_list: - if sf_snapshot_detail_dict["snapshotDetailsName"] == key: - return sf_snapshot_detail_dict["snapshotDetailsValue"] - - raise Exception("Unable to find the following snapshot details key: " + key) - - def _check_sf_snapshot_does_not_exist(self, sf_snapshots, sf_snapshot_id): - for sf_snapshot in sf_snapshots: - if sf_snapshot.snapshot_id == sf_snapshot: - raise Exception("The following SolidFire snapshot ID should not exist: " + sf_snapshot_id) - - def _check_snapshot_details_do_not_exist(self, vol_snap_db_id): - sql_query = "Select count(*) From snapshot_details Where snapshot_id = " + str(vol_snap_db_id) - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - self.assertEqual( - sql_result[0][0], - 0, - "Snapshot details should not exist for the following CloudStack volume snapshot DB ID: " + str(vol_snap_db_id) - ) - - # used when SolidFire snapshots are being used for CloudStack volume snapshots - def _create_and_test_snapshot(self, volume_for_snapshot, sf_volume, primary_storage_db_id, expected_num_snapshots, snapshot_err_msg): - vol_snap = Snapshot.create( - self.apiClient, - volume_id=volume_for_snapshot.id - ) - - self._wait_for_snapshot_state(vol_snap.id, Snapshot.BACKED_UP) - - sf_volume_id = sf_volume.volume_id - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume_id).snapshots - - sf_util.check_list(sf_snapshots, expected_num_snapshots, self, snapshot_err_msg) - - sf_snapshot = self._most_recent_sf_snapshot(sf_snapshots) - - sf_snapshot_details_request = {'snapshotid': vol_snap.id} - sf_snapshot_details_response = self.cs_api.getVolumeSnapshotDetails(sf_snapshot_details_request) - sf_snapshot_details = sf_snapshot_details_response['null'] # 'null' gets me the list that's in the dictionary - - vol_snap_db_id = self._get_cs_volume_snapshot_db_id(vol_snap) - - self._check_snapshot_details(sf_snapshot_details, vol_snap_db_id, volume_for_snapshot, sf_volume_id, sf_snapshot.snapshot_id, primary_storage_db_id, sf_volume.total_size) - - return vol_snap - - # used when SolidFire snapshots are being used for CloudStack volume snapshots to create a backup on secondary storage - def _create_and_test_archive_snapshot(self, volume_id_for_snapshot, sf_volume): - sf_volume_id = sf_volume.volume_id - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots_orig = self.sfe.list_snapshots(sf_volume_id).snapshots - - vol_snap = Snapshot.create( - self.apiClient, - volume_id=volume_id_for_snapshot, - locationtype="secondary" - ) - - self._wait_for_snapshot_state(vol_snap.id, Snapshot.BACKED_UP) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(sf_volume_id).snapshots - - sf_util.check_list(sf_snapshots, len(sf_snapshots_orig), self, "A new SolidFire snapshot was detected.") - - vol_snap_db_id = self._get_cs_volume_snapshot_db_id(vol_snap) - - self._check_snapshot_details_do_not_exist(vol_snap_db_id) - - return vol_snap - - # used when SolidFire volumes are being used for CloudStack volume snapshots - def _create_and_test_snapshot_2(self, volume_id_for_snapshot, sf_volume_id, sf_volume_id_for_volume_snapshot, primary_storage_db_id, sf_volume_size, - sf_account_id, expected_num_volumes, volume_err_msg): - vol_snap = Snapshot.create( - self.apiClient, - volume_id=volume_id_for_snapshot - ) - - self._wait_for_snapshot_state(vol_snap.id, Snapshot.BACKED_UP) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume_id).snapshots - - sf_util.check_list(sf_snapshots, 0, self, TestSnapshots._should_be_zero_snapshots_in_list_err_msg) - - sf_snapshot_details_request = {'snapshotid': vol_snap.id} - sf_snapshot_details_response = self.cs_api.getVolumeSnapshotDetails(sf_snapshot_details_request) - sf_snapshot_details = sf_snapshot_details_response['null'] # 'null' gets me the list that's in the dictionary - - vol_snap_db_id = self._get_cs_volume_snapshot_db_id(vol_snap) - - self._check_snapshot_details_2(sf_snapshot_details, vol_snap_db_id, sf_volume_id_for_volume_snapshot, primary_storage_db_id, sf_volume_size) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, expected_num_volumes, self, volume_err_msg) - - sf_volume_for_snapshot = self._get_sf_volume_by_id(sf_volumes, sf_volume_id_for_volume_snapshot) - - sf_util.check_list(sf_volume_for_snapshot.volume_access_groups, 0, self, TestSnapshots._should_be_zero_volume_access_groups_in_list_err_msg) - - return vol_snap - - def _wait_for_snapshot_state(self, vol_snap_id, snapshot_state): - retry_interval = 10 - num_tries = 10 - - wait_result, return_val = wait_until(retry_interval, num_tries, TestSnapshots._check_snapshot_state, self.apiClient, vol_snap_id, snapshot_state) - - if not wait_result: - raise Exception(return_val) - - @staticmethod - def _check_snapshot_state(api_client, vol_snap_id, snapshot_state): - volume_snapshot = list_snapshots( - api_client, - id=vol_snap_id, - listall=True - )[0] - - if str(volume_snapshot.state).lower() == snapshot_state.lower(): - return True, "" - - return False, "The snapshot is not in the '" + snapshot_state + "' state. State = " + str(volume_snapshot.state) - - # used when SolidFire snapshots are being used for CloudStack volume snapshots - def _delete_and_test_snapshot(self, vol_snap): - vol_snap_id = vol_snap.id - vol_snap_db_id = self._get_cs_volume_snapshot_db_id(vol_snap) - - sf_snapshot_details_request = {'snapshotid': vol_snap_id} - sf_snapshot_details_response = self.cs_api.getVolumeSnapshotDetails(sf_snapshot_details_request) - sf_snapshot_details = sf_snapshot_details_response['null'] # 'null' gets me the list that's in the dictionary - - sf_volume_id = self._get_snapshot_detail(sf_snapshot_details, "volumeId") - sf_snapshot_id = self._get_snapshot_detail(sf_snapshot_details, "snapshotId") - - vol_snap.delete(self.apiClient) - - # Get snapshot information for volume from SolidFire cluster - sf_snapshots = self.sfe.list_snapshots(volume_id=sf_volume_id).snapshots - - self._check_sf_snapshot_does_not_exist(sf_snapshots, sf_snapshot_id) - - self._check_snapshot_details_do_not_exist(vol_snap_db_id) - - # used when SolidFire snapshots are being used for CloudStack volume snapshots to create a backup on secondary storage - def _delete_and_test_archive_snapshot(self, vol_snap): - vol_snap.delete(self.apiClient) - - # used when SolidFire volumes are being used for CloudStack volume snapshots - def _delete_and_test_snapshot_2(self, vol_snap, sf_account_id, expected_num_volumes, volume_err_msg): - vol_snap_db_id = self._get_cs_volume_snapshot_db_id(vol_snap) - - vol_snap.delete(self.apiClient) - - self._check_snapshot_details_do_not_exist(vol_snap_db_id) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.check_list(sf_volumes, expected_num_volumes, self, volume_err_msg) diff --git a/test/integration/plugins/solidfire/TestUploadDownload.py b/test/integration/plugins/solidfire/TestUploadDownload.py deleted file mode 100644 index 1c650060e22c..000000000000 --- a/test/integration/plugins/solidfire/TestUploadDownload.py +++ /dev/null @@ -1,516 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import urllib.request, urllib.error, urllib.parse - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, DiskOffering, ServiceOffering, StoragePool, User, VirtualMachine, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_volumes - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources, wait_until - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster - -# Note: -# If you do have more than one cluster, you might need to change this line: cls.cluster = list_clusters(cls.apiClient)[0] -# Set extract.url.cleanup.interval to 240. -# Set extract.url.expiration.interval to 120. - - -class TestData: - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - diskOffering = "diskoffering" - domainId = "domainId" - hypervisor = "hypervisor" - kvm = "kvm" - login = "login" - mvip = "mvip" - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - tags = "tags" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - volume_1 = "volume_1" - xenServer = "xenserver" - zoneId = "zoneId" - - # modify to control which hypervisor type to test - hypervisor_type = kvm - volume_url = "http://10.117.40.114/tiny-centos-63.qcow2" - file_type = "QCOW2" - properties_file = "volume.properties" - install_path_index = 14 - secondary_storage_server = "10.117.40.114" - secondary_storage_server_root = "/export/secondary/" - secondary_storage_server_username = "cloudstack" - secondary_storage_server_password = "solidfire" - # "HTTP_DOWNLOAD" and "FTP_UPLOAD" are valid for download_mode, but they lead to the same behavior - download_mode = "HTTP_DOWNLOAD" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.40.120", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.40.120:443" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.primaryStorage: { - "name": "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - "url": "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.virtualMachine: { - "name": "TestVM", - "displayname": "Test VM" - }, - TestData.computeOffering: { - "name": "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag - }, - TestData.diskOffering: { - "name": "SF_DO_1", - "displaytext": "SF_DO_1 Custom Size", - "customizediops": False, - "miniops": 5000, - "maxiops": 10000, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - TestData.volume_1: { - "diskname": "testvolume", - }, - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestUploadDownload(cloudstackTestCase): - errorText = "should be either detached or the VM should be in stopped state" - assertText = "The length of the response for the 'volume_store_ref' result should be equal to 1." - assertText2 = "The length of the response for the 'volume_store_ref' result should be equal to 0." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestUploadDownload, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.cluster = list_clusters(cls.apiClient)[0] - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata[TestData.account], - admin=1 - ) - - # Set up connection to make customized API calls - user = User.create( - cls.apiClient, - cls.testdata[TestData.user], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - cls.disk_offering = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering], - custom=True - ) - - # Create VM and volume for tests - cls.virtual_machine = VirtualMachine.create( - cls.apiClient, - cls.testdata[TestData.virtualMachine], - accountid=cls.account.name, - zoneid=cls.zone.id, - serviceofferingid=compute_offering.id, - templateid=cls.template.id, - domainid=cls.domain.id, - startvm=True - ) - - cls._cleanup = [ - compute_offering, - cls.disk_offering, - user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cls.virtual_machine.delete(cls.apiClient, True) - - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - try: - cleanup_resources(self.apiClient, self.cleanup) - except Exception as e: - logging.debug("Exception in tearDown(self): %s" % e) - - def test_01_upload_and_download_snapshot(self): - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=self.virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, "There should only be one volume in this list.") - - vm_root_volume = list_volumes_response[0] - - ### Perform tests related to uploading a QCOW2 file to secondary storage and then moving it to managed storage - - volume_name = "Volume-A" - services = {"format": TestData.file_type, "diskname": volume_name} - - uploaded_volume = Volume.upload(self.apiClient, services, self.zone.id, - account=self.account.name, domainid=self.account.domainid, - url=TestData.volume_url, diskofferingid=self.disk_offering.id) - - self._wait_for_volume_state(uploaded_volume.id, "Uploaded") - - uploaded_volume_id = sf_util.get_cs_volume_db_id(self.dbConnection, uploaded_volume) - - result = self._get_volume_store_ref_row(uploaded_volume_id) - - self.assertEqual( - len(result), - 1, - TestUploadDownload.assertText - ) - - install_path = self._get_install_path(result[0][TestData.install_path_index]) - - self._verify_uploaded_volume_present(install_path) - - uploaded_volume = self.virtual_machine.attach_volume( - self.apiClient, - uploaded_volume - ) - - uploaded_volume = sf_util.check_and_get_cs_volume(self, uploaded_volume.id, volume_name, self) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, "The SolidFire account ID should be a non-zero integer.") - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - self.assertNotEqual( - len(sf_volumes), - 0, - "The length of the response for the SolidFire-volume query should not be zero." - ) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, uploaded_volume.name, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, uploaded_volume, self) - - sf_util.check_size_and_iops(sf_volume, uploaded_volume, sf_volume_size, self) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - result = self._get_volume_store_ref_row(uploaded_volume_id) - - self.assertEqual( - len(result), - 0, - TestUploadDownload.assertText2 - ) - - self._verify_uploaded_volume_not_present(install_path) - - ### Perform tests related to extracting the contents of a volume on managed storage to a QCOW2 file - ### and downloading the file - - try: - # for data disk - Volume.extract(self.apiClient, uploaded_volume.id, self.zone.id, TestData.download_mode) - - raise Exception("The volume extraction (for the data disk) did not fail (as expected).") - except Exception as e: - if TestUploadDownload.errorText in str(e): - pass - else: - raise - - vm_root_volume_id = sf_util.get_cs_volume_db_id(self.dbConnection, vm_root_volume) - - try: - # for root disk - Volume.extract(self.apiClient, vm_root_volume.id, self.zone.id, TestData.download_mode) - - raise Exception("The volume extraction (for the root disk) did not fail (as expected).") - except Exception as e: - if TestUploadDownload.errorText in str(e): - pass - else: - raise - - self.virtual_machine.stop(self.apiClient) - - self._extract_volume_and_verify(uploaded_volume_id, "Unable to locate the extracted file for the data disk (attached)") - - result = self._get_volume_store_ref_row(vm_root_volume_id) - - self.assertEqual( - len(result), - 0, - TestUploadDownload.assertText2 - ) - - self._extract_volume_and_verify(vm_root_volume_id, "Unable to locate the extracted file for the root disk") - - uploaded_volume = self.virtual_machine.detach_volume( - self.apiClient, - uploaded_volume - ) - - self._extract_volume_and_verify(uploaded_volume_id, "Unable to locate the extracted file for the data disk (detached)") - - uploaded_volume = Volume(uploaded_volume.__dict__) - - uploaded_volume.delete(self.apiClient) - - # self.virtual_machine.start(self.apiClient) - - def _verify_uploaded_volume_present(self, install_path, verify_properties_file=True): - result, result2 = self._get_results(install_path) - - self.assertFalse(result is None or len(result.strip()) == 0, "Unable to find the QCOW2 file") - - if verify_properties_file: - self.assertFalse(result2 is None or len(result2.strip()) == 0, "Unable to find the " + TestData.properties_file + " file") - - def _verify_uploaded_volume_not_present(self, install_path): - result, result2 = self._get_results(install_path) - - self.assertTrue(result is None or len(result.strip()) == 0, "QCOW2 file present, but should not be") - self.assertTrue(result2 is None or len(result2.strip()) == 0, TestData.properties_file + " file present, but should not be") - - def _get_results(self, install_path): - ssh_connection = sf_util.get_ssh_connection(TestData.secondary_storage_server, - TestData.secondary_storage_server_username, - TestData.secondary_storage_server_password) - - stdout = ssh_connection.exec_command("ls -l " + TestData.secondary_storage_server_root + - install_path + " | grep qcow2")[1] - - result = stdout.read() - - stdout = ssh_connection.exec_command("ls -l " + TestData.secondary_storage_server_root + - install_path + " | grep " + TestData.properties_file)[1] - - result2 = stdout.read() - - ssh_connection.close() - - return result, result2 - - def _get_install_path(self, install_path): - index = install_path.rfind('/') - - return install_path[:index] - - def _get_volume_store_ref_row(self, volume_id): - sql_query = "Select * From volume_store_ref Where volume_id = '" + str(volume_id) + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - return sql_result - - def _extract_volume_and_verify(self, volume_id, error_msg): - extract_result = Volume.extract(self.apiClient, volume_id, self.zone.id, TestData.download_mode) - - result = self._get_volume_store_ref_row(volume_id) - - self.assertEqual( - len(result), - 1, - TestUploadDownload.assertText - ) - - install_path = self._get_install_path(result[0][TestData.install_path_index]) - - self._verify_uploaded_volume_present(install_path, False) - - url_response = urllib.request.urlopen(extract_result.url) - - if url_response.code != 200: - raise Exception(error_msg) - - self._wait_for_removal_of_extracted_volume(volume_id, extract_result.url) - - def _wait_for_removal_of_extracted_volume(self, volume_id, extract_result_url): - retry_interval = 60 - num_tries = 10 - - wait_result, return_val = wait_until(retry_interval, num_tries, self._check_removal_of_extracted_volume_state, volume_id, extract_result_url) - - if not wait_result: - raise Exception(return_val) - - def _check_removal_of_extracted_volume_state(self, volume_id, extract_result_url): - result = self._get_volume_store_ref_row(volume_id) - - if len(result) == 0: - try: - urllib.request.urlopen(extract_result_url) - except Exception as e: - if "404" in str(e): - return True, "" - - return False, "The extracted volume has not been removed." - - def _wait_for_volume_state(self, volume_id, volume_state): - retry_interval = 30 - num_tries = 10 - - wait_result, return_val = wait_until(retry_interval, num_tries, TestUploadDownload._check_volume_state, self.apiClient, volume_id, volume_state) - - if not wait_result: - raise Exception(return_val) - - @staticmethod - def _check_volume_state(api_client, volume_id, volume_state): - volume = list_volumes( - api_client, - id=volume_id, - listall=True - )[0] - - if str(volume.state).lower() == volume_state.lower(): - return True, "" - - return False, "The volume is not in the '" + volume_state + "' state. State = " + str(volume.state) diff --git a/test/integration/plugins/solidfire/TestVMMigrationWithStorage.py b/test/integration/plugins/solidfire/TestVMMigrationWithStorage.py deleted file mode 100644 index 3933c184b06b..000000000000 --- a/test/integration/plugins/solidfire/TestVMMigrationWithStorage.py +++ /dev/null @@ -1,707 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, DiskOffering, ServiceOffering, StoragePool, User, VirtualMachine, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_volumes - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Two clusters (have system VMs (including the VR) running on local or NFS storage) -# -# Running the tests: -# Verify the "xen_server_hostname_src" and "xen_server_hostname_dest" variables are correct. - - -class TestData(): - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId1 = "clusterId1" - clusterId2 = "clusterId2" - computeOffering1 = "computeoffering1" - computeOffering2 = "computeoffering2" - computeOffering3 = "computeoffering3" - diskName = "diskname" - diskOffering1 = "diskoffering1" - diskOffering2 = "diskoffering2" - domainId = "domainid" - hypervisor = "hypervisor" - login = "login" - mvip = "mvip" - name = "name" - password = "password" - podId = "podid" - port = "port" - primaryStorage = "primarystorage" - primaryStorage2 = "primarystorage2" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - storageTag2 = "SolidFire_Volume_1" - tags = "tags" - templateCacheName = "centos56-x86-64-xen" - testAccount = "testaccount" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - virtualMachine2 = "virtualmachine2" - volume_1 = "volume_1" - xenServer = "xenserver" - zoneId = "zoneid" - - xen_server_hostname_src = "XenServer-6.5-1" - xen_server_hostname_dest = "XenServer-6.5-3" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.40.120", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.40.120:443" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - "username": "test", - "password": "test" - }, - TestData.testAccount: { - "email": "test2@test2.com", - "firstname": "Jane", - "lastname": "Doe", - "username": "test2", - "password": "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - "username": "testuser", - "password": "password" - }, - TestData.primaryStorage: { - TestData.name: "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any", - TestData.zoneId: 1 - }, - TestData.primaryStorage2: { - TestData.name: "SolidFireShared-%d" % random.randint(0, 100), - TestData.scope: "CLUSTER", - TestData.url: "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "minIops=5000;maxIops=50000;burstIops=75000", - TestData.provider: "SolidFireShared", - TestData.tags: TestData.storageTag2, - TestData.capacityIops: 5000, - TestData.capacityBytes: 1099511627776, - TestData.hypervisor: "XenServer", - TestData.podId: 1, - TestData.zoneId: 1 - }, - TestData.virtualMachine: { - "name": "TestVM", - "displayname": "Test VM" - }, - TestData.computeOffering1: { - "name": "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 1,000; Max IOPS = 2,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": 1000, - "maxiops": 2000, - "hypervisorsnapshotreserve": 125, - TestData.tags: TestData.storageTag, - }, - TestData.computeOffering2: { - "name": "SF_CO_2", - "displaytext": "SF_CO_2 (Min IOPS = 1,000; Max IOPS = 2,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": 1000, - "maxiops": 2000, - "hypervisorsnapshotreserve": 100, - TestData.tags: TestData.storageTag, - }, - TestData.computeOffering3: { - "name": "SF_CO_3", - "displaytext": "SF_CO_3 Desc", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - TestData.tags: TestData.storageTag2, - }, - TestData.diskOffering1: { - "name": "SF_DO_1", - "displaytext": "SF_DO_1 (Min IOPS = 3,000; Max IOPS = 6,000)", - "disksize": 100, - "customizediops": False, - "miniops": 3000, - "maxiops": 6000, - "hypervisorsnapshotreserve": 125, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - TestData.diskOffering2: { - "name": "SF_DO_2", - "displaytext": "SF_DO_2 (Min IOPS = 3,000; Max IOPS = 6,000)", - "disksize": 100, - "customizediops": False, - "miniops": 3000, - "maxiops": 6000, - "hypervisorsnapshotreserve": 100, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - TestData.volume_1: { - TestData.diskName: "test-volume", - }, - TestData.zoneId: 1, - TestData.clusterId1: 1, - TestData.clusterId2: 2, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestVMMigrationWithStorage(cloudstackTestCase): - _sf_account_id_should_be_non_zero_int_err_msg = "The SolidFire account ID should be a non-zero integer." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestVMMigrationWithStorage, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - xenserver = cls.testdata[TestData.xenServer] - - # Set up xenAPI connection - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId1], name=TestData.xen_server_hostname_src)[0].ipaddress - - # Set up XenAPI connection - cls.xen_session_1 = XenAPI.Session(host_ip) - - cls.xen_session_1.xenapi.login_with_password(xenserver[TestData.username], xenserver[TestData.password]) - - # Set up xenAPI connection - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId2], name=TestData.xen_server_hostname_dest)[0].ipaddress - - # Set up XenAPI connection - cls.xen_session_2 = XenAPI.Session(host_ip) - - cls.xen_session_2.xenapi.login_with_password(xenserver[TestData.username], xenserver[TestData.password]) - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.cluster_1 = list_clusters(cls.apiClient, id=cls.testdata[TestData.clusterId1])[0] - cls.cluster_2 = list_clusters(cls.apiClient, id=cls.testdata[TestData.clusterId2])[0] - cls.template = get_template(cls.apiClient, cls.zone.id, cls.configData["ostype"]) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage - ) - - cls.compute_offering_1 = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering1] - ) - - cls.compute_offering_2 = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering2] - ) - - cls.compute_offering_3 = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering3] - ) - - cls.disk_offering_1 = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering1] - ) - - cls.disk_offering_2 = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering2] - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.compute_offering_1, - cls.compute_offering_2, - cls.compute_offering_3, - cls.disk_offering_1, - cls.disk_offering_2, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - try: - cleanup_resources(self.apiClient, self.cleanup) - - sf_util.purge_solidfire_volumes(self.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(self): %s" % e) - - def test_01_storage_migrate_root_and_data_disks(self): - src_host, dest_host = self._get_source_and_dest_hosts() - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering_1.id, - templateid=self.template.id, - domainid=self.domain.id, - hostid=src_host.id, - startvm=True - ) - - self.cleanup.append(virtual_machine) - - cs_root_volume = list_volumes(self.apiClient, listall=True, virtualmachineid=virtual_machine.id)[0] - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, - TestVMMigrationWithStorage._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_root_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_root_volume.name, self) - - cs_data_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_1], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering_1.id - ) - - self.cleanup.append(cs_data_volume) - - cs_data_volume = virtual_machine.attach_volume( - self.apiClient, - cs_data_volume - ) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_data_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_data_volume.name, self) - - sf_root_volume, sf_data_volume = self._migrate_and_verify(virtual_machine, dest_host, cs_root_volume, cs_data_volume, sf_account_id, - sf_root_volume, sf_data_volume, self.xen_session_1, self.xen_session_2) - - src_host, dest_host = dest_host, src_host - - self._migrate_and_verify(virtual_machine, dest_host, cs_root_volume, cs_data_volume, sf_account_id, sf_root_volume, sf_data_volume, - self.xen_session_2, self.xen_session_1) - - def test_02_storage_migrate_root_and_data_disks(self): - primarystorage2 = self.testdata[TestData.primaryStorage2] - - primary_storage_2 = StoragePool.create( - self.apiClient, - primarystorage2, - clusterid=self.cluster_1.id - ) - - primary_storage_3 = StoragePool.create( - self.apiClient, - primarystorage2, - clusterid=self.cluster_2.id - ) - - src_host, dest_host = self._get_source_and_dest_hosts() - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering_3.id, - templateid=self.template.id, - domainid=self.domain.id, - hostid=src_host.id, - startvm=True - ) - - cs_data_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_1], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering_1.id - ) - - self.cleanup = [ - virtual_machine, - cs_data_volume, - primary_storage_2, - primary_storage_3 - ] - - cs_data_volume = virtual_machine.attach_volume( - self.apiClient, - cs_data_volume - ) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, - TestVMMigrationWithStorage._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_data_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_data_volume.name, self) - - sf_data_volume = self._migrate_and_verify_one_disk_only(virtual_machine, dest_host, cs_data_volume, sf_account_id, - sf_data_volume, self.xen_session_1, self.xen_session_2) - - src_host, dest_host = dest_host, src_host - - self._migrate_and_verify_one_disk_only(virtual_machine, dest_host, cs_data_volume, sf_account_id, sf_data_volume, - self.xen_session_2, self.xen_session_1) - - # The hypervisor snapshot reserve isn't large enough for either the compute or disk offering. - def test_03_storage_migrate_root_and_data_disks_fail(self): - self._execute_migration_failure(self.compute_offering_2.id, self.disk_offering_2.id) - - # The hypervisor snapshot reserve isn't large enough for the compute offering. - def test_04_storage_migrate_root_disk_fails(self): - self._execute_migration_failure(self.compute_offering_2.id, self.disk_offering_1.id) - - # The hypervisor snapshot reserve isn't large enough for the disk offering. - def test_05_storage_migrate_data_disk_fails(self): - self._execute_migration_failure(self.compute_offering_1.id, self.disk_offering_2.id) - - def _execute_migration_failure(self, compute_offering_id, disk_offering_id): - src_host, dest_host = self._get_source_and_dest_hosts() - - virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=compute_offering_id, - templateid=self.template.id, - domainid=self.domain.id, - hostid=src_host.id, - startvm=True - ) - - self.cleanup.append(virtual_machine) - - cs_root_volume = list_volumes(self.apiClient, listall=True, virtualmachineid=virtual_machine.id)[0] - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, - TestVMMigrationWithStorage._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_root_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_root_volume.name, self) - - cs_data_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_1], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=disk_offering_id - ) - - self.cleanup.append(cs_data_volume) - - cs_data_volume = virtual_machine.attach_volume( - self.apiClient, - cs_data_volume - ) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_data_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_data_volume.name, self) - - self._fail_migrate_and_verify(virtual_machine, dest_host, cs_root_volume, cs_data_volume, sf_account_id, - sf_root_volume, sf_data_volume, self.xen_session_1, self.xen_session_2) - - def _get_source_and_dest_hosts(self): - hosts = list_hosts(self.apiClient) - - for host in hosts: - if host.name == TestData.xen_server_hostname_src: - src_host = host - elif host.name == TestData.xen_server_hostname_dest: - dest_host = host - - self.assertIsNotNone(src_host, "Could not locate the source host") - - self.assertIsNotNone(dest_host, "Could not locate the destination host") - - return src_host, dest_host - - def _migrate_and_verify(self, virtual_machine, dest_host, cs_root_volume, cs_data_volume, sf_account_id, src_sf_root_volume, src_sf_data_volume, - src_xen_session, dest_xen_session): - self._verifyFields(cs_root_volume, src_sf_root_volume) - self._verifyFields(cs_data_volume, src_sf_data_volume) - - virtual_machine.migrate_vm_with_volume(self.apiClient, dest_host.id) - - cs_root_volume = self._get_updated_cs_volume(cs_root_volume.id) - cs_data_volume = self._get_updated_cs_volume(cs_data_volume.id) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - dest_sf_root_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_root_volume.name, self) - dest_sf_data_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_data_volume.name, self) - - self._verifyFields(cs_root_volume, dest_sf_root_volume) - self._verifyFields(cs_data_volume, dest_sf_data_volume) - - self._verify_no_basic_volume_details() - - self._verify_different_volume_access_groups(src_sf_root_volume, dest_sf_root_volume) - self._verify_different_volume_access_groups(src_sf_data_volume, dest_sf_data_volume) - - self._verify_same_account(src_sf_root_volume, dest_sf_root_volume) - self._verify_same_account(src_sf_data_volume, dest_sf_data_volume) - - self._verifySfVolumeIds(src_sf_root_volume, dest_sf_root_volume) - self._verifySfVolumeIds(src_sf_data_volume, dest_sf_data_volume) - - self._verify_xenserver_state(src_xen_session, src_sf_root_volume, dest_xen_session, dest_sf_root_volume) - self._verify_xenserver_state(src_xen_session, src_sf_data_volume, dest_xen_session, dest_sf_data_volume) - - return dest_sf_root_volume, dest_sf_data_volume - - def _migrate_and_verify_one_disk_only(self, virtual_machine, dest_host, cs_volume, sf_account_id, src_sf_volume, src_xen_session, dest_xen_session): - self._verifyFields(cs_volume, src_sf_volume) - - virtual_machine.migrate_vm_with_volume(self.apiClient, dest_host.id) - - cs_volume = self._get_updated_cs_volume(cs_volume.id) - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - dest_sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_volume.name, self) - - self._verifyFields(cs_volume, dest_sf_volume) - - self._verify_no_basic_volume_details() - - self._verify_different_volume_access_groups(src_sf_volume, dest_sf_volume) - - self._verify_same_account(src_sf_volume, dest_sf_volume) - - self._verifySfVolumeIds(src_sf_volume, dest_sf_volume) - - self._verify_xenserver_state(src_xen_session, src_sf_volume, dest_xen_session, dest_sf_volume) - - return dest_sf_volume - - def _fail_migrate_and_verify(self, virtual_machine, dest_host, cs_root_volume, cs_data_volume, sf_account_id, src_sf_root_volume, src_sf_data_volume, - src_xen_session, dest_xen_session): - self._verifyFields(cs_root_volume, src_sf_root_volume) - self._verifyFields(cs_data_volume, src_sf_data_volume) - - class MigrationException(Exception): - def __init__(self, *args, **kwargs): - Exception.__init__(self, *args, **kwargs) - - try: - virtual_machine.migrate_vm_with_volume(self.apiClient, dest_host.id) - - raise MigrationException("The migration did not fail (as expected).") - except MigrationException: - raise - except Exception: - pass - - self._verify_no_basic_volume_details() - - cs_root_volume_refreshed = self._get_updated_cs_volume(cs_root_volume.id) - cs_data_volume_refreshed = self._get_updated_cs_volume(cs_data_volume.id) - - self._verifyFields(cs_root_volume_refreshed, src_sf_root_volume) - self._verifyFields(cs_data_volume_refreshed, src_sf_data_volume) - - sf_volumes = sf_util.get_not_active_sf_volumes(self.sfe, sf_account_id) - - dest_sf_root_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_root_volume.name, self) - dest_sf_data_volume = sf_util.check_and_get_sf_volume(sf_volumes, cs_data_volume.name, self) - - self._verify_xenserver_state(dest_xen_session, dest_sf_root_volume, src_xen_session, src_sf_root_volume) - self._verify_xenserver_state(dest_xen_session, dest_sf_data_volume, src_xen_session, src_sf_data_volume) - - def _verify_different_volume_access_groups(self, src_sf_volume, dest_sf_volume): - src_vags = src_sf_volume.volume_access_groups - - sf_util.check_list(src_vags, 1, self, "'src_vags' should be a list with only one element in it.") - - dest_vags = dest_sf_volume.volume_access_groups - - sf_util.check_list(dest_vags, 1, self, "'dest_vags' should be a list with only one element in it.") - - self.assertNotEqual(src_vags[0], dest_vags[0], "The source and destination volumes should not be in the same volume access group.") - - def _get_updated_cs_volume(self, cs_volume_id): - return list_volumes(self.apiClient, listall=True, id=cs_volume_id)[0] - - def _verify_same_account(self, src_sf_volume, dest_sf_volume): - self.assertEqual(src_sf_volume.account_id, dest_sf_volume.account_id, "The source and destination volumes should be in the same SolidFire account.") - - def _verifySfVolumeIds(self, src_sf_volume, dest_sf_volume): - self.assertTrue(src_sf_volume.volume_id < dest_sf_volume.volume_id, - "The destination SolidFire root volume's ID should be greater than the id of the source one.") - - # verify the name, folder, and iscsi_name - def _verifyFields(self, cs_volume, sf_volume): - self.assertTrue(cs_volume.name == sf_volume.name, "The CloudStack volume name does not match the SolidFire volume name.") - - cs_volume_folder = self._get_cs_volume_folder(cs_volume.id) - - self.assertTrue(int(cs_volume_folder) == sf_volume.volume_id, "The CloudStack folder name does not match the SolidFire volume ID.") - - cs_volume_iscsi_name = self._get_cs_volume_iscsi_name(cs_volume.id) - - self.assertTrue(cs_volume_iscsi_name == sf_util.format_iqn(sf_volume.iqn), "The CloudStack volume iscsi_name does not match the SolidFire volume IQN.") - - def _get_cs_volume_property(self, cs_volume_id, volume_property): - sql_query = "Select " + volume_property + " From volumes Where uuid = '" + cs_volume_id + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - return sql_result[0][0] - - def _get_cs_volume_folder(self, cs_volume_id): - return self._get_cs_volume_property(cs_volume_id, "folder") - - def _get_cs_volume_iscsi_name(self, cs_volume_id): - return self._get_cs_volume_property(cs_volume_id, "iscsi_name") - - def _verify_no_basic_volume_details(self): - sql_query = "Select id From volume_details Where name like 'basic_'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = self.dbConnection.execute(sql_query) - - sf_util.check_list(sql_result, 0, self, "The cloud.volume_details table should not have any name fields that start with 'basic_'.") - - def _verify_xenserver_state(self, xen_session_1, sf_volume_1, xen_session_2, sf_volume_2): - sr_name = sf_util.format_iqn(sf_volume_1.iqn) - - sf_util.check_xen_sr(sr_name, xen_session_1, self, False) - - sr_name = sf_util.format_iqn(sf_volume_2.iqn) - - sf_util.check_xen_sr(sr_name, xen_session_2, self) diff --git a/test/integration/plugins/solidfire/TestVMSnapshots.py b/test/integration/plugins/solidfire/TestVMSnapshots.py deleted file mode 100644 index 106d5836fa73..000000000000 --- a/test/integration/plugins/solidfire/TestVMSnapshots.py +++ /dev/null @@ -1,784 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import time -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, DiskOffering, ServiceOffering, StoragePool, User, VirtualMachine, VmSnapshot, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_hosts, list_volumes - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster - -# Running the tests: -# Change the "hypervisor_type" variable to control which hypervisor type to test. -# If using XenServer, verify the "xen_server_hostname" variable is correct. - - -class TestData: - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - diskOffering = "diskoffering" - domainId = "domainId" - hypervisor = "hypervisor" - login = "login" - mvip = "mvip" - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - tags = "tags" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - volume_1 = "volume_1" - xenServer = "xenserver" - zoneId = "zoneId" - - # modify to control which hypervisor type to test - hypervisor_type = xenServer - xen_server_hostname = "XenServer-6.5-1" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.40.120", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.40.120:443" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - TestData.username: "test", - TestData.password: "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - TestData.username: "testuser", - TestData.password: "password" - }, - TestData.primaryStorage: { - "name": "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - "url": "MVIP=10.117.40.120;SVIP=10.117.41.120;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.virtualMachine: { - "name": "TestVM", - "displayname": "Test VM" - }, - TestData.computeOffering: { - "name": "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 400, - TestData.tags: TestData.storageTag - }, - TestData.diskOffering: { - "name": "SF_DO_1", - "displaytext": "SF_DO_1 (Min IOPS = 300; Max IOPS = 500)", - "disksize": 128, - "customizediops": False, - "miniops": 300, - "maxiops": 500, - "hypervisorsnapshotreserve": 400, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - TestData.volume_1: { - "diskname": "testvolume", - }, - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestVMSnapshots(cloudstackTestCase): - _should_be_no_vm_snapshots_err_msg = "There should be no VM snapshots." - _should_only_be_one_vm_snapshot_err_msg = "There should only be one VM snapshot." - _should_only_be_one_root_volume_err_msg = "There should only be one root volume." - _path_should_have_changed_err_msg = "The 'path' in the 'DB' should have changed." - _path_should_not_have_changed_err_msg = "The 'path' in the 'DB' should not have changed." - _should_only_be_one_vdi_err_msg = "There should only be one VDI." - _should_be_three_vdis_err_msg = "There should be three VDIs." - _active_vdis_should_not_be_the_same_err_msg = "The active VDIs should not be the same." - _active_vdis_should_be_the_same_err_msg = "The active VDIs should be the same." - _snapshot_vdis_should_be_the_same_err_msg = "The snapshot VDIs should be the same." - _base_vdis_should_be_the_same_err_msg = "The base VDIs should be the same." - _snapshot_parent_not_correct_err_msg = "Snapshot's parent is not correct." - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestVMSnapshots, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - - cls.testdata = TestData().testdata - - # Set up XenAPI connection - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xenserver = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xenserver[TestData.username], xenserver[TestData.password]) - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata[TestData.account], - admin=1 - ) - - # Set up connection to make customized API calls - user = User.create( - cls.apiClient, - cls.testdata[TestData.user], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - cls.disk_offering = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering] - ) - - # Create VM and volume for tests - cls.virtual_machine = VirtualMachine.create( - cls.apiClient, - cls.testdata[TestData.virtualMachine], - accountid=cls.account.name, - zoneid=cls.zone.id, - serviceofferingid=compute_offering.id, - templateid=template.id, - domainid=cls.domain.id, - startvm=True - ) - - cls._cleanup = [ - compute_offering, - cls.disk_offering, - user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - time.sleep(60) - - cls.virtual_machine.delete(cls.apiClient, True) - - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.cleanup = [] - - def tearDown(self): - try: - cleanup_resources(self.apiClient, self.cleanup) - except Exception as e: - logging.debug("Exception in tearDown(self): %s" % e) - - def test_01_take_VM_snapshot(self): - self.virtual_machine.start(self.apiClient) - - root_volumes = list_volumes(self.apiClient, type="ROOT", listAll="true") - - sf_util.check_list(root_volumes, 1, self, TestVMSnapshots._should_only_be_one_root_volume_err_msg) - - root_volume = root_volumes[0] - - volume_id = {'volumeid': root_volume.id} - - sf_iscsi_name_result = self.cs_api.getVolumeiScsiName(volume_id) - sf_iscsi_name = sf_iscsi_name_result['apivolumeiscsiname']['volumeiScsiName'] - - sf_util.check_iscsi_name(sf_iscsi_name, self) - - root_volume_path_1 = self._get_path(volume_id) - - ####################################### - ####################################### - # STEP 1: Take snapshot of running VM # - ####################################### - ####################################### - vm_snapshot = VmSnapshot.create( - self.apiClient, - vmid=self.virtual_machine.id, - snapshotmemory="false", - name="Test Snapshot", - description="Test Snapshot Desc" - ) - - list_vm_snapshots = VmSnapshot.list(self.apiClient, listAll="true") - - self._verify_vm_snapshot(list_vm_snapshots, vm_snapshot) - - root_volume_path_2 = self._get_path(volume_id) - - self.assertEqual( - root_volume_path_1, - root_volume_path_2, - TestVMSnapshots._path_should_not_have_changed_err_msg - ) - - xen_sr = self.xen_session.xenapi.SR.get_by_name_label(sf_iscsi_name)[0] - - xen_vdis = self.xen_session.xenapi.SR.get_VDIs(xen_sr) - - sf_util.check_list(xen_vdis, 3, self, TestVMSnapshots._should_be_three_vdis_err_msg) - - vdis_after_create = self._get_vdis(xen_vdis) - - vdiSnapshotOf = self.xen_session.xenapi.VDI.get_record(vdis_after_create.snapshot_vdi["snapshot_of"]) - - self.assertEqual( - vdiSnapshotOf["uuid"], - vdis_after_create.active_vdi["uuid"], - TestVMSnapshots._snapshot_parent_not_correct_err_msg - ) - - ####################################### - ####################################### - ### STEP 2: Revert VM to Snapshot ### - ####################################### - ####################################### - self.virtual_machine.stop(self.apiClient) - - VmSnapshot.revertToSnapshot(self.apiClient, vmsnapshotid=vm_snapshot.id) - - list_vm_snapshots = VmSnapshot.list(self.apiClient, listAll="true") - - sf_util.check_list(list_vm_snapshots, 1, self, TestVMSnapshots._should_only_be_one_vm_snapshot_err_msg) - - root_volume_path_3 = self._get_path(volume_id) - - self.assertNotEqual( - root_volume_path_1, - root_volume_path_3, - TestVMSnapshots._path_should_have_changed_err_msg - ) - - xen_vdis = self.xen_session.xenapi.SR.get_VDIs(xen_sr) - - sf_util.check_list(xen_vdis, 3, self, TestVMSnapshots._should_be_three_vdis_err_msg) - - vdis_after_revert = self._get_vdis(xen_vdis) - - self.assertNotEqual( - vdis_after_create.active_vdi["uuid"], - vdis_after_revert.active_vdi["uuid"], - TestVMSnapshots._active_vdis_should_not_be_the_same_err_msg - ) - - self.assertEqual( - vdis_after_create.snapshot_vdi["uuid"], - vdis_after_revert.snapshot_vdi["uuid"], - TestVMSnapshots._snapshot_vdis_should_be_the_same_err_msg - ) - - self.assertEqual( - vdis_after_create.base_vdi["uuid"], - vdis_after_revert.base_vdi["uuid"], - TestVMSnapshots._base_vdis_should_be_the_same_err_msg - ) - - ####################################### - ####################################### - ##### STEP 3: Delete VM snapshot ##### - ####################################### - ####################################### - VmSnapshot.deleteVMSnapshot(self.apiClient, vmsnapshotid=vm_snapshot.id) - - list_vm_snapshots = VmSnapshot.list(self.apiClient, listAll="true") - - self.assertEqual( - list_vm_snapshots, - None, - TestVMSnapshots._should_be_no_vm_snapshots_err_msg - ) - - root_volume_path_4 = self._get_path(volume_id) - - self.assertEqual( - root_volume_path_3, - root_volume_path_4, - TestVMSnapshots._path_should_not_have_changed_err_msg - ) - - xen_vdis = self.xen_session.xenapi.SR.get_VDIs(xen_sr) - - sf_util.check_list(xen_vdis, 1, self, TestVMSnapshots._should_only_be_one_vdi_err_msg) - - vdis_after_delete = self._get_vdis(xen_vdis, True) - - self.assertEqual( - vdis_after_revert.active_vdi["uuid"], - vdis_after_delete.active_vdi["uuid"], - TestVMSnapshots._active_vdis_should_be_the_same_err_msg - ) - - ####################################### - ####################################### - ##### STEP 4: Start VM ##### - ####################################### - ####################################### - self.virtual_machine.start(self.apiClient) - - def test_02_take_VM_snapshot_with_data_disk(self): - self.virtual_machine.start(self.apiClient) - - data_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_1], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering.id - ) - - self.cleanup = [data_volume] - - self.virtual_machine.attach_volume(self.apiClient, data_volume) - - root_volumes = list_volumes(self.apiClient, type="ROOT", listAll="true") - - sf_util.check_list(root_volumes, 1, self, TestVMSnapshots._should_only_be_one_root_volume_err_msg) - - root_volume = root_volumes[0] - - root_volume_id = {'volumeid': root_volume.id} - - sf_iscsi_name_result = self.cs_api.getVolumeiScsiName(root_volume_id) - sf_iscsi_root_volume_name = sf_iscsi_name_result['apivolumeiscsiname']['volumeiScsiName'] - - sf_util.check_iscsi_name(sf_iscsi_root_volume_name, self) - - root_volume_path_1 = self._get_path(root_volume_id) - - data_volumes = list_volumes(self.apiClient, type="DATADISK", listAll="true") - - sf_util.check_list(data_volumes, 1, self, "There should only be one data volume.") - - data_volume = data_volumes[0] - - data_volume_id = {'volumeid': data_volume.id} - - sf_iscsi_name_result = self.cs_api.getVolumeiScsiName(data_volume_id) - sf_iscsi_data_volume_name = sf_iscsi_name_result['apivolumeiscsiname']['volumeiScsiName'] - - sf_util.check_iscsi_name(sf_iscsi_data_volume_name, self) - - data_volume_path_1 = self._get_path(data_volume_id) - - ####################################### - ####################################### - # STEP 1: Take snapshot of running VM # - ####################################### - ####################################### - vm_snapshot = VmSnapshot.create( - self.apiClient, - vmid=self.virtual_machine.id, - snapshotmemory="false", - name="Test Snapshot", - description="Test Snapshot Desc" - ) - - list_vm_snapshots = VmSnapshot.list(self.apiClient, listAll="true") - - self._verify_vm_snapshot(list_vm_snapshots, vm_snapshot) - - root_volume_path_2 = self._get_path(root_volume_id) - - self.assertEqual( - root_volume_path_1, - root_volume_path_2, - TestVMSnapshots._path_should_not_have_changed_err_msg - ) - - data_volume_path_2 = self._get_path(data_volume_id) - - self.assertEqual( - data_volume_path_1, - data_volume_path_2, - TestVMSnapshots._path_should_not_have_changed_err_msg - ) - - root_volume_xen_sr = self.xen_session.xenapi.SR.get_by_name_label(sf_iscsi_root_volume_name)[0] - - root_volume_xen_vdis = self.xen_session.xenapi.SR.get_VDIs(root_volume_xen_sr) - - sf_util.check_list(root_volume_xen_vdis, 3, self, TestVMSnapshots._should_be_three_vdis_err_msg) - - root_volume_vdis_after_create = self._get_vdis(root_volume_xen_vdis) - - vdiSnapshotOf = self.xen_session.xenapi.VDI.get_record(root_volume_vdis_after_create.snapshot_vdi["snapshot_of"]) - - self.assertEqual( - vdiSnapshotOf["uuid"], - root_volume_vdis_after_create.active_vdi["uuid"], - TestVMSnapshots._snapshot_parent_not_correct_err_msg - ) - - data_volume_xen_sr = self.xen_session.xenapi.SR.get_by_name_label(sf_iscsi_data_volume_name)[0] - - data_volume_xen_vdis = self.xen_session.xenapi.SR.get_VDIs(data_volume_xen_sr) - - sf_util.check_list(data_volume_xen_vdis, 3, self, TestVMSnapshots._should_be_three_vdis_err_msg) - - data_volume_vdis_after_create = self._get_vdis(data_volume_xen_vdis) - - vdiSnapshotOf = self.xen_session.xenapi.VDI.get_record(data_volume_vdis_after_create.snapshot_vdi["snapshot_of"]) - - self.assertEqual( - vdiSnapshotOf["uuid"], - data_volume_vdis_after_create.active_vdi["uuid"], - TestVMSnapshots._snapshot_parent_not_correct_err_msg - ) - - ####################################### - ####################################### - ### STEP 2: Revert VM to Snapshot ### - ####################################### - ####################################### - self.virtual_machine.stop(self.apiClient) - - VmSnapshot.revertToSnapshot(self.apiClient, vmsnapshotid=vm_snapshot.id) - - list_vm_snapshots = VmSnapshot.list(self.apiClient, listAll="true") - - sf_util.check_list(list_vm_snapshots, 1, self, TestVMSnapshots._should_only_be_one_vm_snapshot_err_msg) - - root_volume_path_3 = self._get_path(root_volume_id) - - self.assertNotEqual( - root_volume_path_1, - root_volume_path_3, - TestVMSnapshots._path_should_have_changed_err_msg - ) - - root_volume_xen_vdis = self.xen_session.xenapi.SR.get_VDIs(root_volume_xen_sr) - - sf_util.check_list(root_volume_xen_vdis, 3, self, TestVMSnapshots._should_be_three_vdis_err_msg) - - root_volume_vdis_after_revert = self._get_vdis(root_volume_xen_vdis) - - self.assertNotEqual( - root_volume_vdis_after_create.active_vdi["uuid"], - root_volume_vdis_after_revert.active_vdi["uuid"], - TestVMSnapshots._active_vdis_should_not_be_the_same_err_msg - ) - - self.assertEqual( - root_volume_vdis_after_create.snapshot_vdi["uuid"], - root_volume_vdis_after_revert.snapshot_vdi["uuid"], - TestVMSnapshots._snapshot_vdis_should_be_the_same_err_msg - ) - - self.assertEqual( - root_volume_vdis_after_create.base_vdi["uuid"], - root_volume_vdis_after_revert.base_vdi["uuid"], - TestVMSnapshots._base_vdis_should_be_the_same_err_msg - ) - - data_volume_path_3 = self._get_path(data_volume_id) - - self.assertNotEqual( - data_volume_path_1, - data_volume_path_3, - TestVMSnapshots._path_should_have_changed_err_msg - ) - - data_volume_xen_vdis = self.xen_session.xenapi.SR.get_VDIs(data_volume_xen_sr) - - sf_util.check_list(data_volume_xen_vdis, 3, self, TestVMSnapshots._should_be_three_vdis_err_msg) - - data_volume_vdis_after_revert = self._get_vdis(data_volume_xen_vdis) - - self.assertNotEqual( - data_volume_vdis_after_create.active_vdi["uuid"], - data_volume_vdis_after_revert.active_vdi["uuid"], - TestVMSnapshots._active_vdis_should_not_be_the_same_err_msg - ) - - self.assertEqual( - data_volume_vdis_after_create.snapshot_vdi["uuid"], - data_volume_vdis_after_revert.snapshot_vdi["uuid"], - TestVMSnapshots._snapshot_vdis_should_be_the_same_err_msg - ) - - self.assertEqual( - data_volume_vdis_after_create.base_vdi["uuid"], - data_volume_vdis_after_revert.base_vdi["uuid"], - TestVMSnapshots._base_vdis_should_be_the_same_err_msg - ) - - ####################################### - ####################################### - ##### STEP 3: Delete VM snapshot ##### - ####################################### - ####################################### - VmSnapshot.deleteVMSnapshot(self.apiClient, vmsnapshotid=vm_snapshot.id) - - list_vm_snapshots = VmSnapshot.list(self.apiClient, listAll="true") - - self.assertEqual( - list_vm_snapshots, - None, - TestVMSnapshots._should_be_no_vm_snapshots_err_msg - ) - - root_volume_path_4 = self._get_path(root_volume_id) - - self.assertEqual( - root_volume_path_3, - root_volume_path_4, - TestVMSnapshots._path_should_not_have_changed_err_msg - ) - - root_volume_xen_vdis = self.xen_session.xenapi.SR.get_VDIs(root_volume_xen_sr) - - sf_util.check_list(root_volume_xen_vdis, 1, self, TestVMSnapshots._should_only_be_one_vdi_err_msg) - - root_volume_vdis_after_delete = self._get_vdis(root_volume_xen_vdis, True) - - self.assertEqual( - root_volume_vdis_after_revert.active_vdi["uuid"], - root_volume_vdis_after_delete.active_vdi["uuid"], - TestVMSnapshots._active_vdis_should_be_the_same_err_msg - ) - - data_volume_path_4 = self._get_path(data_volume_id) - - self.assertEqual( - data_volume_path_3, - data_volume_path_4, - TestVMSnapshots._path_should_not_have_changed_err_msg - ) - - data_volume_xen_vdis = self.xen_session.xenapi.SR.get_VDIs(data_volume_xen_sr) - - sf_util.check_list(data_volume_xen_vdis, 1, self, TestVMSnapshots._should_only_be_one_vdi_err_msg) - - data_volume_vdis_after_delete = self._get_vdis(data_volume_xen_vdis, True) - - self.assertEqual( - data_volume_vdis_after_revert.active_vdi["uuid"], - data_volume_vdis_after_delete.active_vdi["uuid"], - TestVMSnapshots._active_vdis_should_be_the_same_err_msg - ) - - ####################################### - ####################################### - ##### STEP 4: Start VM ##### - ####################################### - ####################################### - self.virtual_machine.detach_volume(self.apiClient, data_volume) - - self.virtual_machine.start(self.apiClient) - - def _get_path(self, volume_id): - path_result = self.cs_api.getPathForVolume(volume_id) - - return path_result['apipathforvolume']['path'] - - def _verify_vm_snapshot(self, list_vm_snapshots, vm_snapshot): - sf_util.check_list(list_vm_snapshots, 1, self, TestVMSnapshots._should_only_be_one_vm_snapshot_err_msg) - - vm_snapshot_from_list = list_vm_snapshots[0] - - self.assertEqual( - vm_snapshot.id, - vm_snapshot_from_list.id, - "There is a problem with the VM snapshot ID." - ) - - self.assertEqual( - vm_snapshot.virtualmachineid, - self.virtual_machine.id, - "The ID of the snapshot's virtual machine does not match the expected virtual machine." - ) - - self.assertEqual( - vm_snapshot.state, - "Ready", - "The snapshot is not in the 'Ready' state." - ) - - def _get_vdis(self, xen_vdis, only_active_expected=False): - expected_number_of_vdis = 1 if only_active_expected else 3 - - self.assertEqual( - len(xen_vdis), - expected_number_of_vdis, - "The list had an unexpected number of items in it." - ) - - active_vdi = None - snapshot_vdi = None - base_vdi = None - - for temp_vdi in xen_vdis: - temp = self.xen_session.xenapi.VDI.get_record(temp_vdi) - - if temp["name_label"] == "base copy": - base_vdi = temp - else: - if temp["is_a_snapshot"] == True: - snapshot_vdi = temp - else: - active_vdi = temp - - self.assertNotEqual( - active_vdi, - None, - "The active VDI could not be located." - ) - - if only_active_expected: - self.assertEqual( - snapshot_vdi, - None, - "The snapshot VDI should not be present." - ) - - self.assertEqual( - base_vdi, - None, - "The base VDI should not be present." - ) - else: - self.assertNotEqual( - snapshot_vdi, - None, - "The snapshot VDI could not be located." - ) - - self.assertNotEqual( - base_vdi, - None, - "The base VDI could not be located." - ) - - class VdiCollection(object): - pass - - vdis = VdiCollection() - - vdis.active_vdi = active_vdi - vdis.snapshot_vdi = snapshot_vdi - vdis.base_vdi = base_vdi - - return vdis diff --git a/test/integration/plugins/solidfire/TestVolumes.py b/test/integration/plugins/solidfire/TestVolumes.py deleted file mode 100644 index 64a8eee0fe41..000000000000 --- a/test/integration/plugins/solidfire/TestVolumes.py +++ /dev/null @@ -1,2712 +0,0 @@ -# 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. - -import logging -import random -import SignedAPICall -import time -import XenAPI - -from solidfire.factory import ElementFactory - -from util import sf_util - -# All tests inherit from cloudstackTestCase -from marvin.cloudstackTestCase import cloudstackTestCase - -# Import Integration Libraries - -# base - contains all resources as entities and defines create, delete, list operations on them -from marvin.lib.base import Account, DiskOffering, ServiceOffering, Snapshot, StoragePool, Template, User, VirtualMachine, Volume - -# common - commonly used methods for all tests are listed here -from marvin.lib.common import get_domain, get_template, get_zone, list_clusters, list_hosts, list_virtual_machines, \ - list_volumes - -# utils - utility classes for common cleanup, external library wrappers, etc. -from marvin.lib.utils import cleanup_resources - -# Prerequisites: -# Only one zone -# Only one pod -# Only one cluster -# -# Running the tests: -# Change the "hypervisor_type" variable to control which hypervisor type to test. -# If using XenServer, verify the "xen_server_hostname" variable is correct. -# If using XenServer, change the "supports_cloning" variable to True or False as desired. -# -# Note: -# If you do have more than one cluster, you might need to change this line: cls.cluster = list_clusters(cls.apiClient)[0] and -# this variable's value: TestData.clusterId. - - -class TestData(): - # constants - account = "account" - capacityBytes = "capacitybytes" - capacityIops = "capacityiops" - clusterId = "clusterId" - computeOffering = "computeoffering" - diskName = "diskname" - diskOffering = "diskoffering" - domainId = "domainId" - hypervisor = "hypervisor" - kvm = "kvm" - login = "login" - mvip = "mvip" - one_GB_in_bytes = 1073741824 - password = "password" - port = "port" - primaryStorage = "primarystorage" - provider = "provider" - scope = "scope" - solidFire = "solidfire" - storageTag = "SolidFire_SAN_1" - tags = "tags" - templateCacheNameKvm = "centos55-x86-64" - templateCacheNameXenServer = "centos56-x86-64-xen" - # templateCacheNameXenServer = "centos65-x86-64-XenServer" - testAccount = "testaccount" - url = "url" - user = "user" - username = "username" - virtualMachine = "virtualmachine" - virtualMachine2 = "virtualmachine2" - volume_1 = "volume_1" - volume_2 = "volume_2" - xenServer = "xenserver" - zoneId = "zoneId" - - # modify to control which hypervisor type to test - hypervisor_type = xenServer - xen_server_hostname = "XenServer-6.5-1" - - def __init__(self): - self.testdata = { - TestData.solidFire: { - TestData.mvip: "10.117.78.225", - TestData.username: "admin", - TestData.password: "admin", - TestData.port: 443, - TestData.url: "https://10.117.78.225:443" - }, - TestData.kvm: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.xenServer: { - TestData.username: "root", - TestData.password: "solidfire" - }, - TestData.account: { - "email": "test@test.com", - "firstname": "John", - "lastname": "Doe", - "username": "test", - "password": "test" - }, - TestData.testAccount: { - "email": "test2@test2.com", - "firstname": "Jane", - "lastname": "Doe", - "username": "test2", - "password": "test" - }, - TestData.user: { - "email": "user@test.com", - "firstname": "Jane", - "lastname": "Doe", - "username": "testuser", - "password": "password" - }, - TestData.primaryStorage: { - "name": "SolidFire-%d" % random.randint(0, 100), - TestData.scope: "ZONE", - "url": "MVIP=10.117.78.225;SVIP=10.117.94.225;" + - "clusterAdminUsername=admin;clusterAdminPassword=admin;" + - "clusterDefaultMinIops=10000;clusterDefaultMaxIops=15000;" + - "clusterDefaultBurstIopsPercentOfMaxIops=1.5;", - TestData.provider: "SolidFire", - TestData.tags: TestData.storageTag, - TestData.capacityIops: 4500000, - TestData.capacityBytes: 2251799813685248, - TestData.hypervisor: "Any" - }, - TestData.virtualMachine: { - "name": "TestVM", - "displayname": "Test VM" - }, - TestData.virtualMachine2: { - "name": "TestVM2", - "displayname": "Test VM 2" - }, - TestData.computeOffering: { - "name": "SF_CO_1", - "displaytext": "SF_CO_1 (Min IOPS = 10,000; Max IOPS = 15,000)", - "cpunumber": 1, - "cpuspeed": 100, - "memory": 128, - "storagetype": "shared", - "customizediops": False, - "miniops": "10000", - "maxiops": "15000", - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag - }, - TestData.diskOffering: { - "name": "SF_DO_1", - "displaytext": "SF_DO_1 (Min IOPS = 300; Max IOPS = 500)", - "disksize": 128, - "customizediops": False, - "miniops": 300, - "maxiops": 500, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - }, - TestData.volume_1: { - TestData.diskName: "test-volume", - }, - TestData.volume_2: { - TestData.diskName: "test-volume-2", - }, - TestData.zoneId: 1, - TestData.clusterId: 1, - TestData.domainId: 1, - TestData.url: "10.117.40.114" - } - - -class TestVolumes(cloudstackTestCase): - _should_only_be_one_vm_in_list_err_msg = "There should only be one VM in this list." - _should_only_be_one_volume_in_list_err_msg = "There should only be one volume in this list." - _should_only_be_one_host_in_list_err_msg = "There should only be one host in this list." - _should_only_be_two_volumes_in_list_err_msg = "There should only be two volumes in this list." - _sf_account_id_should_be_non_zero_int_err_msg = "The SolidFire account ID should be a non-zero integer." - _volume_size_should_be_non_zero_int_err_msg = "The SolidFire volume size should be a non-zero integer." - _volume_vm_id_and_vm_id_do_not_match_err_msg = "The volume's VM ID and the VM's ID do not match." - _vm_not_in_running_state_err_msg = "The VM is not in the 'Running' state." - _vm_not_in_stopped_state_err_msg = "The VM is not in the 'Stopped' state." - _volume_response_should_not_be_zero_err_msg = "The length of the response for the SolidFire-volume query should not be zero." - _volume_should_not_be_in_a_vag = "The volume should not be in a volume access group." - _volume_size_not_an_int = "'volume_size_in_GB' is not of type 'int'" - _only_data_volumes_err_msg = "Only data volumes can be resized via a new disk offering." - _to_change_volume_size_err_msg = "To change a volume's size without providing a new disk offering, its current " \ - "disk offering must be customizable or it must be a root volume (if providing a disk offering, make sure it is " \ - "different from the current disk offering)." - _min_iops_err_msg = "The current disk offering does not support customization of the 'Min IOPS' parameter." - _this_kind_of_disk_err_msg = "This kind of KVM disk cannot be resized while it is connected to a VM that's not in the Stopped state." - _template_creation_did_not_fail_err_msg = "The template creation did not fail (as expected)." - _volume_resize_did_not_fail_err_msg = "The volume resize did not fail (as expected)." - _volume_attached_to_non_stopped_vm_err_msg = "volume is attached to a non-stopped VM" - - @classmethod - def setUpClass(cls): - # Set up API client - testclient = super(TestVolumes, cls).getClsTestClient() - - cls.apiClient = testclient.getApiClient() - cls.configData = testclient.getParsedTestDataConfig() - cls.dbConnection = testclient.getDbConnection() - - cls.testdata = TestData().testdata - - cls._handle_supports_cloning() - - cls._connect_to_hypervisor() - - # Set up SolidFire connection - solidfire = cls.testdata[TestData.solidFire] - - cls.sfe = ElementFactory.create(solidfire[TestData.mvip], solidfire[TestData.username], solidfire[TestData.password]) - - # Get Resources from Cloud Infrastructure - cls.zone = get_zone(cls.apiClient, zone_id=cls.testdata[TestData.zoneId]) - cls.cluster = list_clusters(cls.apiClient)[0] - cls.template = get_template(cls.apiClient, cls.zone.id, hypervisor=TestData.hypervisor_type) - cls.domain = get_domain(cls.apiClient, cls.testdata[TestData.domainId]) - - # Create test account - cls.account = Account.create( - cls.apiClient, - cls.testdata["account"], - admin=1 - ) - - # Set up connection to make customized API calls - cls.user = User.create( - cls.apiClient, - cls.testdata["user"], - account=cls.account.name, - domainid=cls.domain.id - ) - - url = cls.testdata[TestData.url] - - api_url = "http://" + url + ":8080/client/api" - userkeys = User.registerUserKeys(cls.apiClient, cls.user.id) - - cls.cs_api = SignedAPICall.CloudStack(api_url, userkeys.apikey, userkeys.secretkey) - - primarystorage = cls.testdata[TestData.primaryStorage] - - cls.primary_storage = StoragePool.create( - cls.apiClient, - primarystorage, - scope=primarystorage[TestData.scope], - zoneid=cls.zone.id, - provider=primarystorage[TestData.provider], - tags=primarystorage[TestData.tags], - capacityiops=primarystorage[TestData.capacityIops], - capacitybytes=primarystorage[TestData.capacityBytes], - hypervisor=primarystorage[TestData.hypervisor] - ) - - cls.compute_offering = ServiceOffering.create( - cls.apiClient, - cls.testdata[TestData.computeOffering] - ) - - cls.disk_offering = DiskOffering.create( - cls.apiClient, - cls.testdata[TestData.diskOffering] - ) - - # Create VM and volume for tests - cls.virtual_machine = VirtualMachine.create( - cls.apiClient, - cls.testdata[TestData.virtualMachine], - accountid=cls.account.name, - zoneid=cls.zone.id, - serviceofferingid=cls.compute_offering.id, - templateid=cls.template.id, - domainid=cls.domain.id, - startvm=False - ) - - TestVolumes._start_vm(cls.virtual_machine) - - cls.volume = Volume.create( - cls.apiClient, - cls.testdata[TestData.volume_1], - account=cls.account.name, - domainid=cls.domain.id, - zoneid=cls.zone.id, - diskofferingid=cls.disk_offering.id - ) - - # Resources that are to be destroyed - cls._cleanup = [ - cls.volume, - cls.virtual_machine, - cls.compute_offering, - cls.disk_offering, - cls.user, - cls.account - ] - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.apiClient, cls._cleanup) - - cls.primary_storage.delete(cls.apiClient) - - sf_util.purge_solidfire_volumes(cls.sfe) - except Exception as e: - logging.debug("Exception in tearDownClass(cls): %s" % e) - - def setUp(self): - self.attached = False - self.cleanup = [] - - def tearDown(self): - if self.attached: - self.virtual_machine.detach_volume(self.apiClient, self.volume) - - cleanup_resources(self.apiClient, self.cleanup) - - def test_00_check_template_cache(self): - if self._supports_cloning == False: - return - - sf_volumes = self._get_active_sf_volumes() - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, self._get_template_cache_name(), self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - "The volume should not be in a VAG." - ) - - sf_account_id = sf_volume.account_id - - sf_account = self.sfe.get_account_by_id(sf_account_id).account - - sf_account_name = sf_account.username - - self.assertEqual( - sf_account_name.endswith("_1"), - True, - "The template cache volume's account does not end with '_1'." - ) - - def test_01_attach_new_volume_to_stopped_VM(self): - '''Attach a volume to a stopped virtual machine, then start VM''' - - self.virtual_machine.stop(self.apiClient) - - new_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_2], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering.id - ) - - self.cleanup.append(new_volume) - - sf_util.check_and_get_cs_volume(self, new_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - new_volume = self.virtual_machine.attach_volume( - self.apiClient, - new_volume - ) - - newvolume = sf_util.check_and_get_cs_volume(self, new_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - TestVolumes._start_vm(self.virtual_machine) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - newvolume.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - "running", - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, new_volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, new_volume, self) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, newvolume.name, self) - - sf_util.check_size_and_iops(sf_volume, newvolume, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - # Detach volume - new_volume = self.virtual_machine.detach_volume( - self.apiClient, - new_volume - ) - - def test_02_attach_detach_attach_volume(self): - '''Attach, detach, and attach volume to a running VM''' - - TestVolumes._start_vm(self.virtual_machine) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - ####################################### - ####################################### - # STEP 1: Attach volume to running VM # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - ######################################### - ######################################### - # STEP 2: Detach volume from running VM # - ######################################### - ######################################### - - self.volume = self.virtual_machine.detach_volume( - self.apiClient, - self.volume - ) - - self.attached = False - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - None, - "The volume should not be attached to a VM." - ) - - self.assertEqual( - vm.state.lower(), - 'running', - str(vm.state) - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - "The volume should not be in a VAG." - ) - - self._check_host_side(sf_iscsi_name, vm.hostid, False) - - ####################################### - ####################################### - # STEP 3: Attach volume to running VM # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - def test_03_attached_volume_reboot_VM(self): - '''Attach volume to running VM, then reboot.''' - - TestVolumes._start_vm(self.virtual_machine) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - ####################################### - ####################################### - # STEP 1: Attach volume to running VM # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - ####################################### - ####################################### - # STEP 2: Reboot VM with attached vol # - ####################################### - ####################################### - TestVolumes._reboot_vm(self.virtual_machine) - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - def test_04_detach_volume_reboot(self): - '''Detach volume from a running VM, then reboot.''' - - TestVolumes._start_vm(self.virtual_machine) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - ####################################### - ####################################### - # STEP 1: Attach volume to running VM # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - ######################################### - ######################################### - # STEP 2: Detach volume from running VM # - ######################################### - ######################################### - - self.volume = self.virtual_machine.detach_volume( - self.apiClient, - self.volume - ) - - self.attached = False - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - None, - "The volume should not be attached to a VM." - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - TestVolumes._volume_should_not_be_in_a_vag - ) - - self._check_host_side(sf_iscsi_name, vm.hostid, False) - - ####################################### - ####################################### - # STEP 3: Reboot VM with detached vol # - ####################################### - ####################################### - - self.virtual_machine.reboot(self.apiClient) - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - TestVolumes._volume_should_not_be_in_a_vag - ) - - self._check_host_side(sf_iscsi_name, vm.hostid, False) - - def test_05_detach_vol_stopped_VM_start(self): - '''Detach volume from a stopped VM, then start.''' - - TestVolumes._start_vm(self.virtual_machine) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - ####################################### - ####################################### - # STEP 1: Attach volume to running VM # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - hostid = vm.hostid - - ######################################### - ######################################### - # STEP 2: Detach volume from stopped VM # - ######################################### - ######################################### - - self.virtual_machine.stop(self.apiClient) - - self.volume = self.virtual_machine.detach_volume( - self.apiClient, - self.volume - ) - - self.attached = False - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - None, - "The volume should not be attached to a VM." - ) - - self.assertEqual( - vm.state.lower(), - 'stopped', - TestVolumes._vm_not_in_stopped_state_err_msg - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - TestVolumes._volume_should_not_be_in_a_vag - ) - - self._check_host_side(sf_iscsi_name, hostid, False) - - ####################################### - ####################################### - # STEP 3: Start VM with detached vol # - ####################################### - ####################################### - - TestVolumes._start_vm(self.virtual_machine) - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - TestVolumes._volume_should_not_be_in_a_vag - ) - - self._check_host_side(sf_iscsi_name, vm.hostid, False) - - def test_06_attach_volume_to_stopped_VM(self): - '''Attach a volume to a stopped virtual machine, then start VM''' - - self.virtual_machine.stop(self.apiClient) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - ####################################### - ####################################### - # STEP 1: Attach volume to stopped VM # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'stopped', - TestVolumes._vm_not_in_stopped_state_err_msg - ) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - if TestData.hypervisor_type == TestData.kvm: - self._check_host_side(sf_iscsi_name, None, False) - elif TestData.hypervisor_type == TestData.xenServer: - self._check_host_side(sf_iscsi_name) - - TestVolumes._start_vm(self.virtual_machine) - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - def test_07_destroy_expunge_VM_with_volume(self): - '''Destroy and expunge VM with attached volume''' - - ####################################### - ####################################### - # STEP 1: Create VM and attach volume # - ####################################### - ####################################### - - test_virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine2], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=False - ) - - TestVolumes._start_vm(test_virtual_machine) - - self.volume = test_virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(test_virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - TestVolumes._volume_vm_id_and_vm_id_do_not_match_err_msg - ) - - self.assertEqual( - vm.state.lower(), - 'running', - TestVolumes._vm_not_in_running_state_err_msg - ) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - hostid = vm.hostid - - ####################################### - ####################################### - # STEP 2: Destroy and Expunge VM # - ####################################### - ####################################### - - test_virtual_machine.delete(self.apiClient, True) - - self.attached = False - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - self.assertEqual( - vol.virtualmachineid, - None, - "Check if attached to virtual machine" - ) - - self.assertEqual( - vol.vmname, - None, - "Check if VM was expunged" - ) - - list_virtual_machine_response = list_virtual_machines( - self.apiClient, - id=test_virtual_machine.id - ) - - self.assertEqual( - list_virtual_machine_response, - None, - "Check if VM was actually expunged" - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - TestVolumes._volume_should_not_be_in_a_vag - ) - - self._check_host_side(sf_iscsi_name, hostid, False) - - def test_08_delete_volume_was_attached(self): - '''Delete volume that was attached to a VM and is detached now''' - - TestVolumes._start_vm(self.virtual_machine) - - ####################################### - ####################################### - # STEP 1: Create vol and attach to VM # - ####################################### - ####################################### - - new_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_2], - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering.id - ) - - volume_to_delete_later = new_volume - - sf_util.check_and_get_cs_volume(self, new_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - new_volume = self.virtual_machine.attach_volume( - self.apiClient, - new_volume - ) - - vol = sf_util.check_and_get_cs_volume(self, new_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - "Check if attached to virtual machine" - ) - - self.assertEqual( - vm.state.lower(), - 'running', - str(vm.state) - ) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, new_volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, new_volume, self) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - ####################################### - ####################################### - # STEP 2: Detach and delete volume # - ####################################### - ####################################### - - new_volume = self.virtual_machine.detach_volume( - self.apiClient, - new_volume - ) - - vol = sf_util.check_and_get_cs_volume(self, new_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - None, - "Check if attached to virtual machine" - ) - - self.assertEqual( - vm.state.lower(), - 'running', - str(vm.state) - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - self.assertEqual( - len(sf_volume.volume_access_groups), - 0, - TestVolumes._volume_should_not_be_in_a_vag - ) - - self._check_host_side(sf_iscsi_name, vm.hostid, False) - - volume_to_delete_later.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=new_volume.id - ) - - self.assertEqual( - list_volumes_response, - None, - "Check volume was deleted" - ) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self, False) - - def test_09_attach_volumes_multiple_accounts(self): - '''Attach a data disk to a VM in one account and attach another data disk to a VM in another account''' - - TestVolumes._start_vm(self.virtual_machine) - - ####################################### - ####################################### - # STEP 1: Create account, VM, and vol # - ####################################### - ####################################### - - test_account = Account.create( - self.apiClient, - self.testdata[TestData.testAccount], - admin=1 - ) - - self.cleanup.append(test_account) - - test_virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine2], - accountid=test_account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=False - ) - - TestVolumes._start_vm(test_virtual_machine) - - test_volume = Volume.create( - self.apiClient, - self.testdata[TestData.volume_2], - zoneid=self.zone.id, - account=test_account.name, - domainid=self.domain.id, - diskofferingid=self.disk_offering.id - ) - - sf_util.check_and_get_cs_volume(self, test_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - ####################################### - ####################################### - # STEP 2: Attach volumes to VMs # - ####################################### - ####################################### - - self.volume = self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - vm = self._get_vm(self.virtual_machine.id) - - self.assertEqual( - vol.virtualmachineid, - vm.id, - "Check if attached to virtual machine" - ) - - self.assertEqual( - vm.state.lower(), - 'running', - str(vm.state) - ) - - test_volume = test_virtual_machine.attach_volume( - self.apiClient, - test_volume - ) - - test_vol = sf_util.check_and_get_cs_volume(self, test_volume.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - test_vm = self._get_vm(test_virtual_machine.id) - - self.assertEqual( - test_vol.virtualmachineid, - test_vm.id, - "Check if attached to virtual machine of other acct" - ) - - self.assertEqual( - test_vm.state.lower(), - 'running', - str(test_vm.state) - ) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, vol, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - sf_test_account_id = sf_util.get_sf_account_id(self.cs_api, test_account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_test_volumes = self._get_active_sf_volumes(sf_test_account_id) - - sf_test_volume = sf_util.check_and_get_sf_volume(sf_test_volumes, test_vol.name, self) - - sf_test_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, test_vol, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_test_volume_size) - - sf_util.check_size_and_iops(sf_test_volume, test_vol, sf_test_volume_size, self) - - sf_test_iscsi_name = sf_util.get_iqn(self.cs_api, test_volume, self) - - self._check_host_side(sf_test_iscsi_name, test_vm.hostid) - - sf_util.check_vag(sf_test_volume, sf_vag_id, self) - - def test_10_attach_more_than_one_disk_to_VM(self): - '''Attach more than one disk to a VM''' - - TestVolumes._start_vm(self.virtual_machine) - - volume_2 = Volume.create( - self.apiClient, - self.testdata[TestData.volume_2], - zoneid=self.zone.id, - account=self.account.name, - domainid=self.domain.id, - diskofferingid=self.disk_offering.id - ) - - self.cleanup.append(volume_2) - - sf_util.check_and_get_cs_volume(self, volume_2.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - ####################################### - ####################################### - # Step 1: Attach volumes to VM # - ####################################### - ####################################### - - self.virtual_machine.attach_volume( - self.apiClient, - self.volume - ) - - self.attached = True - - vol = sf_util.check_and_get_cs_volume(self, self.volume.id, self.testdata[TestData.volume_1][TestData.diskName], self) - - self.virtual_machine.attach_volume( - self.apiClient, - volume_2 - ) - - vol_2 = sf_util.check_and_get_cs_volume(self, volume_2.id, self.testdata[TestData.volume_2][TestData.diskName], self) - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, self.volume, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_size) - - sf_volume_2_size = sf_util.get_volume_size_with_hsr(self.cs_api, volume_2, self) - - self._verify_hsr(self.disk_offering.disksize, self.disk_offering.hypervisorsnapshotreserve, sf_volume_2_size) - - sf_vag_id = sf_util.get_vag_id(self.cs_api, self.cluster.id, self.primary_storage.id, self) - - sf_volumes = self._get_active_sf_volumes(sf_account_id) - - sf_volume = sf_util.check_and_get_sf_volume(sf_volumes, vol.name, self) - - sf_util.check_size_and_iops(sf_volume, vol, sf_volume_size, self) - - sf_iscsi_name = sf_util.get_iqn(self.cs_api, self.volume, self) - - vm = self._get_vm(self.virtual_machine.id) - - self._check_host_side(sf_iscsi_name, vm.hostid) - - sf_util.check_vag(sf_volume, sf_vag_id, self) - - sf_volume_2 = sf_util.check_and_get_sf_volume(sf_volumes, vol_2.name, self) - - sf_util.check_size_and_iops(sf_volume_2, vol_2, sf_volume_2_size, self) - - sf_iscsi_name_2 = sf_util.get_iqn(self.cs_api, volume_2, self) - - self._check_host_side(sf_iscsi_name_2, vm.hostid) - - sf_util.check_vag(sf_volume_2, sf_vag_id, self) - - self.virtual_machine.detach_volume(self.apiClient, volume_2) - - def test_11_template_from_volume(self): - if TestData.hypervisor_type != TestData.kvm: - return - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=self.virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - vm_1_root_volume = list_volumes_response[0] - - services = {"displaytext": "Template-1", "name": "Template-1-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - try: - Template.create_from_volume(self.apiClient, vm_1_root_volume, services) - - raise Exception(TestVolumes._template_creation_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._volume_attached_to_non_stopped_vm_err_msg not in e.errorMsg: - raise - - self.virtual_machine.stop(self.apiClient) - - template = Template.create_from_volume(self.apiClient, vm_1_root_volume, services) - - self.cleanup.append(template) - - vol_snap = Snapshot.create(self.apiClient, volume_id=vm_1_root_volume.id) - - self.cleanup.append(vol_snap) - - TestVolumes._start_vm(self.virtual_machine) - - self._create_vm_using_template_and_destroy_vm(template) - - services = {"diskname": "Vol-1", "zoneid": self.testdata[TestData.zoneId], "ispublic": True} - - volume_created_from_snapshot = Volume.create_from_snapshot(self.apiClient, vol_snap.id, services, account=self.account.name, domainid=self.domain.id) - - self.cleanup.append(volume_created_from_snapshot) - - services = {"displaytext": "Template-2", "name": "Template-2-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template = Template.create_from_volume(self.apiClient, volume_created_from_snapshot, services) - - self.cleanup.append(template) - - self._create_vm_using_template_and_destroy_vm(template) - - volume_created_from_snapshot = self.virtual_machine.attach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - services = {"displaytext": "Template-3", "name": "Template-3-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - try: - Template.create_from_volume(self.apiClient, volume_created_from_snapshot, services) - - raise Exception(TestVolumes._template_creation_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._volume_attached_to_non_stopped_vm_err_msg not in e.errorMsg: - raise - - self.virtual_machine.stop(self.apiClient) - - template = Template.create_from_volume(self.apiClient, volume_created_from_snapshot, services) - - self.cleanup.append(template) - - volume_created_from_snapshot = self.virtual_machine.detach_volume( - self.apiClient, - volume_created_from_snapshot - ) - - TestVolumes._start_vm(self.virtual_machine) - - self._create_vm_using_template_and_destroy_vm(template) - - services = {"displaytext": "Template-4", "name": "Template-4-name", "ostypeid": self.template.ostypeid, "ispublic": "true"} - - template = Template.create_from_volume(self.apiClient, volume_created_from_snapshot, services) - - self.cleanup.append(template) - - self._create_vm_using_template_and_destroy_vm(template) - - def test_12_resize_volume_on_running_vm(self): - if TestData.hypervisor_type != TestData.kvm: - return - - test_virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine2], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=True - ) - - self.cleanup.append(test_virtual_machine) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=test_virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - test_vm_root_volume = Volume(list_volumes_response[0].__dict__) - - self._handle_root_volume_with_started_vm(test_vm_root_volume) - - volume_name = { - TestData.diskName: "test-volume-a", - } - - test_vm_data_volume = Volume.create( - self.apiClient, - volume_name, - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering.id - ) - - self.cleanup.append(test_vm_data_volume) - - test_vm_data_volume = test_virtual_machine.attach_volume( - self.apiClient, - test_vm_data_volume - ) - - test_vm_data_volume = Volume(test_vm_data_volume.__dict__) - - self._handle_data_volume_with_started_vm(test_vm_data_volume) - - custom_disk_offering = { - "name": "SF_DO_A", - "displaytext": "SF_DO_A (Custom)", - "customized": True, - "customizediops": True, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - custom_disk_offering = DiskOffering.create( - self.apiClient, - custom_disk_offering, - custom=True - ) - - self.cleanup.append(custom_disk_offering) - - services = { - TestData.diskName: "test-volume-custom-a", - "customdisksize": 100, - "customminiops": 1000, - "custommaxiops": 2000, - "zoneid": self.testdata[TestData.zoneId] - } - - test_vm_data_volume = Volume.create_custom_disk( - self.apiClient, - services, - account=self.account.name, - domainid=self.domain.id, - diskofferingid=custom_disk_offering.id - ) - - self.cleanup.append(test_vm_data_volume) - - test_vm_data_volume = test_virtual_machine.attach_volume( - self.apiClient, - test_vm_data_volume - ) - - test_vm_data_volume = Volume(test_vm_data_volume.__dict__) - - self._handle_custom_data_volume_with_started_vm(test_vm_data_volume) - - def test_13_resize_volume_on_stopped_vm(self): - if TestData.hypervisor_type != TestData.kvm: - return - - test_virtual_machine = VirtualMachine.create( - self.apiClient, - self.testdata[TestData.virtualMachine2], - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=self.template.id, - domainid=self.domain.id, - startvm=False - ) - - self.cleanup.append(test_virtual_machine) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=test_virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - test_vm_root_volume = Volume(list_volumes_response[0].__dict__) - - err_msg = "Check if SF volume was created in correct account" - - try: - # This should fail because there should not be an equivalent SolidFire volume in the cluster yet. - self._verify_volume(test_vm_root_volume) - - raise Exception("The volume verification did not fail (as expected).") - except Exception as e: - if err_msg not in str(e): - raise - - # Starting the up the should create its root disk on the SolidFire cluster. - test_virtual_machine.start(self.apiClient) - - test_virtual_machine.stop(self.apiClient) - - self._handle_root_volume_with_stopped_vm(test_vm_root_volume) - - volume_name = { - TestData.diskName: "test-volume-a", - } - - test_vm_data_volume = Volume.create( - self.apiClient, - volume_name, - account=self.account.name, - domainid=self.domain.id, - zoneid=self.zone.id, - diskofferingid=self.disk_offering.id - ) - - self.cleanup.append(test_vm_data_volume) - - test_vm_data_volume = test_virtual_machine.attach_volume( - self.apiClient, - test_vm_data_volume - ) - - test_vm_data_volume = Volume(test_vm_data_volume.__dict__) - - self._handle_data_volume_with_stopped_vm(test_vm_data_volume) - - custom_disk_offering = { - "name": "SF_DO_A", - "displaytext": "SF_DO_A (Custom)", - "customized": True, - "customizediops": True, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - custom_disk_offering = DiskOffering.create( - self.apiClient, - custom_disk_offering, - custom=True - ) - - self.cleanup.append(custom_disk_offering) - - services = { - TestData.diskName: "test-volume-custom-a", - "customdisksize": 100, - "customminiops": 1000, - "custommaxiops": 2000, - "zoneid": self.testdata[TestData.zoneId] - } - - test_vm_data_volume = Volume.create_custom_disk( - self.apiClient, - services, - account=self.account.name, - domainid=self.domain.id, - diskofferingid=custom_disk_offering.id - ) - - self.cleanup.append(test_vm_data_volume) - - test_vm_data_volume = test_virtual_machine.attach_volume( - self.apiClient, - test_vm_data_volume - ) - - test_vm_data_volume = Volume(test_vm_data_volume.__dict__) - - self._handle_custom_data_volume_with_stopped_vm(test_vm_data_volume) - - test_vm_data_volume = test_virtual_machine.detach_volume( - self.apiClient, - test_vm_data_volume - ) - - test_vm_data_volume = Volume(test_vm_data_volume.__dict__) - - self._handle_custom_data_volume_with_stopped_vm(test_vm_data_volume) - - def _handle_root_volume_with_started_vm(self, volume): - self._verify_volume(volume) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_size = volume_size_in_GB + 10 - new_min_iops = volume.miniops + 100 - new_max_iops = volume.maxiops + 200 - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - try: - # Try to change the size and IOPS of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, size=new_size, miniops=new_min_iops, maxiops=new_max_iops) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._this_kind_of_disk_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - try: - # Try to change the size of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, size=new_size) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._this_kind_of_disk_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_A", - "displaytext": "SF_DO_A (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - try: - # Try to change the size and IOPS of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._only_data_volumes_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_B", - "displaytext": "SF_DO_B (Min IOPS = " + str(volume.miniops) + "; Max IOPS = " + str(volume.maxiops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": volume.miniops, - "maxiops": volume.maxiops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - try: - # Try to change the size of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._only_data_volumes_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_C", - "displaytext": "SF_DO_C (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": volume_size_in_GB, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - disk_offering.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - new_min_iops = new_min_iops + 10 - new_max_iops = new_max_iops + 20 - - volume.resize(self.apiClient, miniops=new_min_iops, maxiops=new_max_iops) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - def _handle_root_volume_with_stopped_vm(self, volume): - self._verify_volume(volume) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_size = volume_size_in_GB + 10 - new_min_iops = volume.miniops + 100 - new_max_iops = volume.maxiops + 200 - - volume.resize(self.apiClient, size=new_size, miniops=new_min_iops, maxiops=new_max_iops) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - new_size = new_size + 10 - - volume.resize(self.apiClient, size=new_size) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - new_min_iops = new_min_iops + 100 - new_max_iops = new_max_iops + 200 - - volume.resize(self.apiClient, miniops=new_min_iops, maxiops=new_max_iops) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - new_size = new_size + 10 - new_min_iops = new_min_iops + 100 - new_max_iops = new_max_iops + 200 - - disk_offering = { - "name": "SF_DO_A", - "displaytext": "SF_DO_A (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - try: - # Try to change the size and IOPS of a volume attached to a stopped VM (should fail). - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._only_data_volumes_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_B", - "displaytext": "SF_DO_B (Min IOPS = " + str(volume.miniops) + "; Max IOPS = " + str(volume.maxiops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": volume.miniops, - "maxiops": volume.maxiops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - try: - # Try to change the size of a volume attached to a stopped VM (should fail). - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._only_data_volumes_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - disk_offering = { - "name": "SF_DO_C", - "displaytext": "SF_DO_C (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": volume_size_in_GB, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - disk_offering.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - def _handle_data_volume_with_started_vm(self, volume): - self._verify_volume(volume) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_size = volume_size_in_GB + 10 - new_min_iops = volume.miniops + 100 - new_max_iops = volume.maxiops + 200 - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - try: - # Try to change the size and IOPS of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, size=new_size, miniops=new_min_iops, maxiops=new_max_iops) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._to_change_volume_size_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - try: - # Try to change the size of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, size=new_size) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._to_change_volume_size_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_A", - "displaytext": "SF_DO_A (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - try: - # Try to change the size and IOPS of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._this_kind_of_disk_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_B", - "displaytext": "SF_DO_B (Min IOPS = " + str(volume.miniops) + "; Max IOPS = " + str(volume.maxiops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": volume.miniops, - "maxiops": volume.maxiops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - try: - # Try to change the size of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._this_kind_of_disk_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - try: - # Try to change the IOPS of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, miniops=new_min_iops, maxiops=new_max_iops) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._min_iops_err_msg not in str(e): - raise - - disk_offering.delete(self.apiClient) - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_C", - "displaytext": "SF_DO_C (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": volume_size_in_GB, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - disk_offering.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - def _handle_data_volume_with_stopped_vm(self, volume): - self._verify_volume(volume) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_size = volume_size_in_GB + 10 - new_min_iops = volume.miniops + 100 - new_max_iops = volume.maxiops + 200 - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - try: - # Try to change the size and IOPS of a volume attached to a stopped VM (should fail). - volume.resize(self.apiClient, size=new_size, miniops=new_min_iops, maxiops=new_max_iops) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._to_change_volume_size_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - try: - # Try to change the size of a volume attached to a stopped VM (should fail). - volume.resize(self.apiClient, size=new_size) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._to_change_volume_size_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - try: - # Try to change the IOPS of a volume attached to a stopped VM (should fail). - volume.resize(self.apiClient, miniops=new_min_iops, maxiops=new_max_iops) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._min_iops_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - disk_offering = { - "name": "SF_DO_A", - "displaytext": "SF_DO_A (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - disk_offering.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - new_size = new_size + 10 - - disk_offering = { - "name": "SF_DO_B", - "displaytext": "SF_DO_B (Min IOPS = " + str(volume.miniops) + "; Max IOPS = " + str(volume.maxiops) + ")", - "disksize": new_size, - "customizediops": False, - "miniops": volume.miniops, - "maxiops": volume.maxiops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - disk_offering.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_min_iops = new_min_iops + 100 - new_max_iops = new_max_iops + 200 - - disk_offering = { - "name": "SF_DO_C", - "displaytext": "SF_DO_C (Min IOPS = " + str(new_min_iops) + "; Max IOPS = " + str(new_max_iops) + ")", - "disksize": volume_size_in_GB, - "customizediops": False, - "miniops": new_min_iops, - "maxiops": new_max_iops, - "hypervisorsnapshotreserve": 200, - TestData.tags: TestData.storageTag, - "storagetype": "shared" - } - - disk_offering = DiskOffering.create( - self.apiClient, - disk_offering - ) - - volume.resize(self.apiClient, diskofferingid=disk_offering.id) - - disk_offering.delete(self.apiClient) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - def _handle_custom_data_volume_with_started_vm(self, volume): - self._verify_volume(volume) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_size = volume_size_in_GB + 10 - new_min_iops = volume.miniops + 100 - new_max_iops = volume.maxiops + 200 - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - try: - # Try to change the size and IOPS of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, size=new_size, miniops=new_min_iops, maxiops=new_max_iops) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._this_kind_of_disk_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - try: - # Try to change the size of a volume attached to a running VM (should fail). - volume.resize(self.apiClient, size=new_size) - - raise Exception(TestVolumes._volume_resize_did_not_fail_err_msg) - except Exception as e: - if TestVolumes._this_kind_of_disk_err_msg not in str(e): - raise - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - volume.resize(self.apiClient, miniops=new_min_iops, maxiops=new_max_iops) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - def _handle_custom_data_volume_with_stopped_vm(self, volume): - self._verify_volume(volume) - - volume_size_in_GB = volume.size / TestData.one_GB_in_bytes - - self.assertTrue( - type(volume_size_in_GB) == int, - TestVolumes._volume_size_not_an_int - ) - - new_size = volume_size_in_GB + 10 - new_min_iops = volume.miniops + 100 - new_max_iops = volume.maxiops + 200 - - volume.resize(self.apiClient, size=new_size, miniops=new_min_iops, maxiops=new_max_iops) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - new_size = new_size + 10 - - volume.resize(self.apiClient, size=new_size) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - sf_volume_size = self._get_sf_volume(volume.name).total_size - - self._verify_volume(volume, volume.miniops, volume.maxiops, sf_volume_size) - - new_min_iops = volume.miniops + 10 - new_max_iops = volume.maxiops + 20 - - volume.resize(self.apiClient, miniops=new_min_iops, maxiops=new_max_iops) - - list_volumes_response = list_volumes( - self.apiClient, - id=volume.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - volume = Volume(list_volumes_response[0].__dict__) - - self._verify_volume(volume, new_min_iops, new_max_iops, sf_volume_size) - - def _get_sf_volume(self, volume_name): - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, "The SolidFire account ID should be a non-zero integer.") - - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - self.assertNotEqual( - len(sf_volumes), - 0, - "The length of the response for the SolidFire-volume query should not be zero." - ) - - return sf_util.check_and_get_sf_volume(sf_volumes, volume_name, self) - - def _verify_volume(self, cs_volume, expected_min_iops=None, expected_max_iops=None, expected_size=None): - sf_volume = self._get_sf_volume(cs_volume.name) - - sf_volume_size = sf_util.get_volume_size_with_hsr(self.cs_api, cs_volume, self) - - sf_util.check_size_and_iops(sf_volume, cs_volume, sf_volume_size, self) - - if expected_min_iops is not None: - self.assertEqual( - cs_volume.miniops, - expected_min_iops, - "Unexpected Min IOPS value (CloudStack volume has " + str(cs_volume.miniops) + "; expected " + str(expected_min_iops) + ")" - ) - - if expected_max_iops is not None: - self.assertEqual( - cs_volume.maxiops, - expected_max_iops, - "Unexpected Max IOPS value (CloudStack volume has " + str(cs_volume.maxiops) + "; expected " + str(expected_max_iops) + ")" - ) - - if expected_size is not None: - self.assertEqual( - sf_volume_size, - expected_size, - "Unexpected size value (CloudStack volume (with HSR) has " + str(sf_volume_size) + "; expected " + str(expected_size) + ")" - ) - - def _create_vm_using_template_and_destroy_vm(self, template): - vm_name = "VM-%d" % random.randint(0, 100) - - virtual_machine_dict = {"name": vm_name, "displayname": vm_name} - - virtual_machine = VirtualMachine.create( - self.apiClient, - virtual_machine_dict, - accountid=self.account.name, - zoneid=self.zone.id, - serviceofferingid=self.compute_offering.id, - templateid=template.id, - domainid=self.domain.id, - startvm=True - ) - - list_volumes_response = list_volumes( - self.apiClient, - virtualmachineid=virtual_machine.id, - listall=True - ) - - sf_util.check_list(list_volumes_response, 1, self, TestVolumes._should_only_be_one_volume_in_list_err_msg) - - vm_root_volume = list_volumes_response[0] - vm_root_volume_name = vm_root_volume.name - - sf_account_id = sf_util.get_sf_account_id(self.cs_api, self.account.id, self.primary_storage.id, self, TestVolumes._sf_account_id_should_be_non_zero_int_err_msg) - - # Get volume information from SolidFire cluster - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - sf_util.get_sf_volume_by_name(self, sf_volumes, vm_root_volume_name) - - virtual_machine.delete(self.apiClient, True) - - def _verify_hsr(self, cs_volume_size_in_gb, hsr, sf_volume_size_in_bytes): - cs_volume_size_including_hsr_in_bytes = self._get_cs_volume_size_including_hsr_in_bytes(cs_volume_size_in_gb, hsr) - - self.assertTrue( - cs_volume_size_including_hsr_in_bytes == sf_volume_size_in_bytes, - "HSR does not add up correctly." - ) - - def _get_cs_volume_size_including_hsr_in_bytes(self, cs_volume_size_in_gb, hsr): - if TestData.hypervisor_type == TestData.kvm: - return self._get_bytes_from_gb(cs_volume_size_in_gb) - - lowest_hsr = 10 - - if hsr < lowest_hsr: - hsr = lowest_hsr - - return self._get_bytes_from_gb(cs_volume_size_in_gb + (cs_volume_size_in_gb * (hsr / 100))) - - def _get_bytes_from_gb(self, number_in_gb): - return number_in_gb * 1024 * 1024 * 1024 - - def _get_vm(self, vm_id): - list_vms_response = list_virtual_machines(self.apiClient, id=vm_id) - - sf_util.check_list(list_vms_response, 1, self, TestVolumes._should_only_be_one_vm_in_list_err_msg) - - return list_vms_response[0] - - def _check_xen_sr(self, xen_sr_name, should_exist=True): - sf_util.check_xen_sr(xen_sr_name, self.xen_session, self, should_exist) - - def _get_active_sf_volumes(self, sf_account_id=None): - sf_volumes = sf_util.get_active_sf_volumes(self.sfe, sf_account_id) - - self.assertNotEqual( - len(sf_volumes), - 0, - TestVolumes._volume_response_should_not_be_zero_err_msg - ) - - return sf_volumes - - def _get_template_cache_name(self): - if TestData.hypervisor_type == TestData.kvm: - return TestData.templateCacheNameKvm - elif TestData.hypervisor_type == TestData.xenServer: - return TestData.templateCacheNameXenServer - - self.assertTrue(False, "Invalid hypervisor type") - - def _get_modified_iscsi_name(self, sf_iscsi_name): - sf_iscsi_name = sf_iscsi_name.replace("/", "") - - return sf_iscsi_name[:-1] - - def _check_host_side(self, sf_iscsi_name, vm_hostid=None, should_exist=True): - if TestData.hypervisor_type == TestData.kvm: - self._check_kvm_host_side(self._get_modified_iscsi_name(sf_iscsi_name), vm_hostid, should_exist) - elif TestData.hypervisor_type == TestData.xenServer: - self._check_xen_sr(sf_iscsi_name, should_exist) - - def _check_kvm_host_side(self, sf_iscsi_name, vm_hostid, should_exist=True): - if vm_hostid is None: - list_hosts_response = list_hosts( - self.apiClient, - type="Routing" - ) - else: - list_hosts_response = list_hosts( - self.apiClient, - id=vm_hostid - ) - - sf_util.check_list(list_hosts_response, 1, self, TestVolumes._should_only_be_one_host_in_list_err_msg) - - kvm_login = self.testdata[TestData.kvm] - - for cs_host in list_hosts_response: - ssh_connection = sf_util.get_ssh_connection(cs_host.ipaddress, kvm_login[TestData.username], kvm_login[TestData.password]) - - stdout = ssh_connection.exec_command("ls /dev/disk/by-path | grep " + sf_iscsi_name)[1] - - result = stdout.read() - - ssh_connection.close() - - if should_exist: - self.assertFalse(result is None, "Unable to locate 'by-path' field on the KVM host (None)") - self.assertFalse(len(result.strip()) <= len(sf_iscsi_name), "Unable to locate the 'by-path' field on the KVM host (Zero-length string)") - else: - self.assertTrue(result is None or len(result.strip()) == 0, "Found the 'by-path' field on the KVM host, but did not expect to") - - @classmethod - def _start_vm(cls, vm): - vm_for_check = list_virtual_machines( - cls.apiClient, - id=vm.id - )[0] - - if vm_for_check.state == VirtualMachine.STOPPED: - vm.start(cls.apiClient) - - # Libvirt appears to have an issue detaching a volume from a VM while the VM is booting up. - # The XML sent to update the VM seems correct, but it doesn't appear to update the XML that describes the VM. - # For KVM, just give it 90 seconds to boot up. - if TestData.hypervisor_type == TestData.kvm: - time.sleep(90) - - @classmethod - def _reboot_vm(cls, vm): - vm.reboot(cls.apiClient) - - # Libvirt appears to have an issue detaching a volume from a VM while the VM is booting up. - # The XML sent to update the VM seems correct, but it doesn't appear to update the XML that describes the VM. - # For KVM, just give it 90 seconds to boot up. - if TestData.hypervisor_type == TestData.kvm: - time.sleep(90) - - @classmethod - def _handle_supports_cloning(cls): - if TestData.hypervisor_type == TestData.kvm: - cls._supports_cloning = True - elif TestData.hypervisor_type == TestData.xenServer: - # For XenServer, it is OK to set this to True or False depending on what you'd like tested - cls._supports_cloning = True - - sf_util.set_supports_resign(cls._supports_cloning, cls.dbConnection) - - @classmethod - def _connect_to_hypervisor(cls): - if TestData.hypervisor_type == TestData.kvm: - pass - elif TestData.hypervisor_type == TestData.xenServer: - host_ip = "https://" + \ - list_hosts(cls.apiClient, clusterid=cls.testdata[TestData.clusterId], name=TestData.xen_server_hostname)[0].ipaddress - - cls.xen_session = XenAPI.Session(host_ip) - - xen_server = cls.testdata[TestData.xenServer] - - cls.xen_session.xenapi.login_with_password(xen_server[TestData.username], xen_server[TestData.password]) diff --git a/test/integration/plugins/solidfire/util/sf_util.py b/test/integration/plugins/solidfire/util/sf_util.py deleted file mode 100644 index e7adf113bd45..000000000000 --- a/test/integration/plugins/solidfire/util/sf_util.py +++ /dev/null @@ -1,331 +0,0 @@ -# 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. - -import paramiko - -from marvin.lib.common import list_volumes - -def check_list(in_list, expected_size_of_list, obj_assert, err_msg): - obj_assert.assertEqual( - isinstance(in_list, list), - True, - "'in_list' is not a list." - ) - - obj_assert.assertEqual( - len(in_list), - expected_size_of_list, - err_msg - ) - -def get_sf_account_id(cs_api, cs_account_id, primary_storage_id, obj_assert, err_msg): - sf_account_id_request = {'accountid': cs_account_id, 'storageid': primary_storage_id} - sf_account_id_result = cs_api.getSolidFireAccountId(sf_account_id_request) - sf_account_id = sf_account_id_result['apisolidfireaccountid']['solidFireAccountId'] - - obj_assert.assertEqual( - isinstance(sf_account_id, int), - True, - err_msg - ) - - return sf_account_id - -def get_iqn(cs_api, volume, obj_assert): - # Get volume IQN - sf_iscsi_name_request = {'volumeid': volume.id} - sf_iscsi_name_result = cs_api.getVolumeiScsiName(sf_iscsi_name_request) - sf_iscsi_name = sf_iscsi_name_result['apivolumeiscsiname']['volumeiScsiName'] - - check_iscsi_name(sf_iscsi_name, obj_assert) - - return sf_iscsi_name - -def check_iscsi_name(sf_iscsi_name, obj_assert): - obj_assert.assertEqual( - sf_iscsi_name[0], - "/", - "The iSCSI name needs to start with a forward slash." - ) - -def set_supports_resign(supports_resign, db_connection): - _set_supports_resign_for_table(supports_resign, db_connection, "host_details") - _set_supports_resign_for_table(supports_resign, db_connection, "cluster_details") - -def _set_supports_resign_for_table(supports_resign, db_connection, table): - sql_query = "Update " + str(table) + " Set value = '" + str(supports_resign) + "' Where name = 'supportsResign'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - db_connection.execute(sql_query) - -def purge_solidfire_volumes(sfe): - deleted_volumes = sfe.list_deleted_volumes() - - for deleted_volume in deleted_volumes.volumes: - sfe.purge_deleted_volume(deleted_volume.volume_id) - -def get_not_active_sf_volumes(sfe, sf_account_id=None): - if sf_account_id is not None: - sf_volumes = sfe.list_volumes_for_account(sf_account_id).volumes - - if sf_volumes is not None and len(sf_volumes) > 0: - sf_volumes = _get_not_active_sf_volumes_only(sf_volumes) - else: - sf_volumes = sfe.list_deleted_volumes().volumes - - return sf_volumes - -def _get_not_active_sf_volumes_only(sf_volumes): - not_active_sf_volumes_only = [] - - for sf_volume in sf_volumes: - if sf_volume.status != "active": - not_active_sf_volumes_only.append(sf_volume) - - return not_active_sf_volumes_only - -def get_active_sf_volumes(sfe, sf_account_id=None): - if sf_account_id is not None: - sf_volumes = sfe.list_volumes_for_account(sf_account_id).volumes - - if sf_volumes is not None and len(sf_volumes) > 0: - sf_volumes = _get_active_sf_volumes_only(sf_volumes) - else: - sf_volumes = sfe.list_active_volumes().volumes - - return sf_volumes - -def _get_active_sf_volumes_only(sf_volumes): - active_sf_volumes_only = [] - - for sf_volume in sf_volumes: - if sf_volume.status == "active": - active_sf_volumes_only.append(sf_volume) - - return active_sf_volumes_only - -def check_and_get_sf_volume(sf_volumes, sf_volume_name, obj_assert, should_exist=True): - sf_volume = None - - for volume in sf_volumes: - if volume.name == sf_volume_name: - sf_volume = volume - break - - if should_exist: - obj_assert.assertNotEqual( - sf_volume, - None, - "Check if SF volume was created in correct account: " + str(sf_volumes) - ) - else: - obj_assert.assertEqual( - sf_volume, - None, - "Check if SF volume was deleted: " + str(sf_volumes) - ) - - return sf_volume - -def check_xen_sr(xen_sr_name, xen_session, obj_assert, should_exist=True): - xen_sr = xen_session.xenapi.SR.get_by_name_label(xen_sr_name) - - if should_exist: - check_list(xen_sr, 1, obj_assert, "SR " + xen_sr_name + " doesn't exist, but should.") - - sr_shared = xen_session.xenapi.SR.get_shared(xen_sr[0]) - - obj_assert.assertEqual( - sr_shared, - True, - "SR " + xen_sr_name + " is not shared, but should be." - ) - else: - check_list(xen_sr, 0, obj_assert, "SR " + xen_sr_name + " exists, but shouldn't.") - -def check_kvm_access_to_volume(iscsi_name, kvm_hosts, username, password, obj_assert, should_exist=True): - count = 0 - - for kvm_host in kvm_hosts: - ssh_connection = get_ssh_connection(kvm_host.ipaddress, username, password) - - stdin, stdout, stderr = ssh_connection.exec_command("ls /dev/disk/by-path | grep " + iscsi_name) - - result = stdout.read() - - ssh_connection.close() - - if result is not None and len(result.strip()) > len(iscsi_name): - count = count + 1 - - if should_exist: - obj_assert.assertTrue(count == 1, "Only one KVM host should be connected to the following IQN: " + iscsi_name) - else: - obj_assert.assertTrue(count == 0, "No KVM host should be connected to the following IQN: " + iscsi_name) - -def check_vag(sf_volume, sf_vag_id, obj_assert): - obj_assert.assertEqual( - len(sf_volume.volume_access_groups), - 1, - "The volume should only be in one VAG." - ) - - obj_assert.assertEqual( - sf_volume.volume_access_groups[0], - sf_vag_id, - "The volume is not in the VAG with the following ID: " + str(sf_vag_id) + "." - ) - -def get_vag_id(cs_api, cluster_id, primary_storage_id, obj_assert): - # Get SF Volume Access Group ID - sf_vag_id_request = {'clusterid': cluster_id, 'storageid': primary_storage_id} - sf_vag_id_result = cs_api.getSolidFireVolumeAccessGroupId(sf_vag_id_request) - sf_vag_id = sf_vag_id_result['apisolidfirevolumeaccessgroupid']['solidFireVolumeAccessGroupId'] - - obj_assert.assertEqual( - isinstance(sf_vag_id, int), - True, - "The SolidFire VAG ID should be a non-zero integer." - ) - - return sf_vag_id - -def format_iqn(iqn): - return "/" + iqn + "/0" - -def check_size_and_iops(sf_volume, cs_volume, size, obj_assert): - obj_assert.assertEqual( - sf_volume.qos.min_iops, - cs_volume.miniops, - "Check QoS - Min IOPS: " + str(sf_volume.qos.min_iops) - ) - - obj_assert.assertEqual( - sf_volume.qos.max_iops, - cs_volume.maxiops, - "Check QoS - Max IOPS: " + str(sf_volume.qos.max_iops) - ) - - obj_assert.assertEqual( - sf_volume.total_size, - size, - "Check SolidFire volume size: " + str(sf_volume.total_size) - ) - -def get_volume_size_with_hsr(cs_api, cs_volume, obj_assert): - # Get underlying SF volume size with hypervisor snapshot reserve - sf_volume_size_request = {'volumeid': cs_volume.id} - sf_volume_size_result = cs_api.getSolidFireVolumeSize(sf_volume_size_request) - sf_volume_size = sf_volume_size_result['apisolidfirevolumesize']['solidFireVolumeSize'] - - obj_assert.assertEqual( - isinstance(sf_volume_size, int), - True, - "The SolidFire volume size should be a non-zero integer." - ) - - return sf_volume_size - -def get_ssh_connection(ip_address, username, password): - ssh_client = paramiko.SSHClient() - - ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) - - ssh_client.connect(ip_address, username=username, password=password) - - return ssh_client - -def get_sf_volume_by_name(obj_assert, sf_volumes, sf_volume_name): - check_list_not_empty(obj_assert, sf_volumes) - - sf_volume = None - - for volume in sf_volumes: - if volume.name == sf_volume_name: - sf_volume = volume - - break - - obj_assert.assertNotEqual( - sf_volume, - None, - "The SolidFire volume could not be found in the expected list." - ) - - return sf_volume - -def check_list_not_empty(obj_assert, in_list): - obj_assert.assertEqual( - isinstance(in_list, list), - True, - "'in_list' is not a list." - ) - - obj_assert.assertGreater( - len(in_list), - 0, - "The size of 'in_list' must be greater than zero." - ) - -def check_and_get_cs_volume(obj_test, volume_id, volume_name, obj_assert): - list_volumes_response = list_volumes( - obj_test.apiClient, - id=volume_id - ) - - check_list(list_volumes_response, 1, obj_assert, "There should only be one volume in this list.") - - cs_volume = list_volumes_response[0] - - check_volume(obj_test, cs_volume, volume_name, obj_assert) - - return cs_volume - -def check_volume(obj_test, cs_volume, volume_name, obj_assert): - obj_assert.assertTrue( - cs_volume.name.startswith(volume_name), - "The volume name is incorrect." - ) - - obj_assert.assertEqual( - cs_volume.zoneid, - obj_test.zone.id, - "The zone is incorrect." - ) - - obj_assert.assertEqual( - cs_volume.diskofferingid, - obj_test.disk_offering.id, - "The disk offering is incorrect." - ) - - obj_assert.assertEqual( - cs_volume.storagetype, - obj_test.disk_offering.storagetype, - "The storage type is incorrect." - ) - -def get_cs_volume_db_id(dbConnection, vol): - return get_db_id(dbConnection, "volumes", vol) - -def get_db_id(dbConnection, table, db_obj): - sql_query = "Select id From " + table + " Where uuid = '" + str(db_obj.id) + "'" - - # make sure you can connect to MySQL: https://teamtreehouse.com/community/cant-connect-remotely-to-mysql-server-with-mysql-workbench - sql_result = dbConnection.execute(sql_query) - - return sql_result[0][0] diff --git a/test/integration/plugins/test_nicira_controller.py b/test/integration/plugins/test_nicira_controller.py deleted file mode 100644 index aa3786679a51..000000000000 --- a/test/integration/plugins/test_nicira_controller.py +++ /dev/null @@ -1,584 +0,0 @@ -#!/usr/bin/env python -# 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. - -import requests -from marvin.cloudstackTestCase import cloudstackTestCase -from marvin.lib.utils import cleanup_resources -from marvin.lib.base import ( - PhysicalNetwork, - NetworkOffering, - NiciraNvp, - ServiceOffering, - NATRule, - PublicIPAddress, - Network, - VirtualMachine -) -from marvin.lib.common import ( - get_domain, - get_zone, - get_template, - list_routers, - list_hosts, - findSuitableHostForMigration, - migrate_router -) -from nose.plugins.attrib import attr -from marvin.codes import (FAILED, PASS) -import time -import logging - -class TestNiciraContoller(cloudstackTestCase): - - ''' - Example of marvin config with NSX specific values - "niciraNvp": { - "hosts": [ "nsxcon1.cloud.lan", "nsxcon2.cloud.lan", "nsxcon3.cloud.lan" ], - "shared_network": { - "l2gatewayserviceuuid": "3595ca67-959f-47d4-8f01-0492a8e96205", - "iprange" : { - "startip": "192.168.26.2", - "endip": "192.168.26.20", - "netmask": "255.255.255.0", - "gateway": "192.168.26.1", - "vlan": "50", - "vlan_uuid": "5cdaa49d-06cd-488a-9ca4-e954a3181f54" - } - } - } - ''' - @classmethod - def setUpClass(cls): - test_case = super(TestNiciraContoller, cls) - - test_client = test_case.getClsTestClient() - cls.config = test_case.getClsConfig() - cls.api_client = test_client.getApiClient() - - cls.physical_networks = cls.config.zones[0].physical_networks - cls.nicira_hosts = cls.config.niciraNvp.hosts - - cls.nicira_shared_network_iprange = cls.config.niciraNvp.shared_network.iprange - cls.l2gatewayserviceuuid = cls.config.niciraNvp.shared_network.l2gatewayserviceuuid - - cls.physical_network_id = cls.get_nicira_enabled_physical_network_id(cls.physical_networks) - - cls.network_offerring_services = [ - { - 'name': 'NiciraEnabledIsolatedNetwork', - 'displaytext': 'NiciraEnabledIsolatedNetwork', - 'guestiptype': 'Isolated', - 'supportedservices': 'SourceNat,Dhcp,Dns,Firewall,PortForwarding,Connectivity', - 'traffictype': 'GUEST', - 'availability': 'Optional', - 'serviceProviderList': { - 'SourceNat': 'VirtualRouter', - 'Dhcp': 'VirtualRouter', - 'Dns': 'VirtualRouter', - 'Firewall': 'VirtualRouter', - 'PortForwarding': 'VirtualRouter', - 'Connectivity': 'NiciraNvp' - } - }, - { - 'name': 'NiciraEnabledSharedNetwork', - 'displaytext': 'NiciraEnabledSharedNetwork', - 'guestiptype': 'Shared', - 'supportedservices': 'Connectivity,Dhcp,UserData,SourceNat,StaticNat,Lb,PortForwarding', - 'traffictype': 'GUEST', - 'availability': 'Optional', - 'specifyVlan': 'true', - 'specifyIpRanges': 'true', - 'serviceProviderList': { - 'Connectivity': 'NiciraNvp', - 'Dhcp': 'VirtualRouter', - 'SourceNat': 'VirtualRouter', - 'StaticNat': 'VirtualRouter', - 'Lb': 'VirtualRouter', - 'PortForwarding': 'VirtualRouter', - 'UserData': 'VirtualRouter' - } - } - ] - - cls.network_offering_isolated = NetworkOffering.create(cls.api_client, cls.network_offerring_services[0]) - cls.network_offering_isolated.update(cls.api_client, state='Enabled') - - cls.network_offering_shared = NetworkOffering.create(cls.api_client, cls.network_offerring_services[1]) - cls.network_offering_shared.update(cls.api_client, state='Enabled') - - cls.nicira_credentials = { - 'username': 'admin', - 'password': 'admin' - } - - cls.nicira_primary_controller = cls.determine_primary_controller( - cls.nicira_hosts, - cls.nicira_credentials - ) - - cls.transport_zone_uuid = cls.get_transport_zone_from_controller( - cls.nicira_primary_controller, - cls.nicira_credentials - ) - - cls.admin_account = 'admin' - cls.admin_domain = get_domain(cls.api_client) - - cls.zone = get_zone(cls.api_client, test_client.getZoneForTests()) - - template = get_template( - cls.api_client, - cls.zone.id - ) - if template == FAILED: - raise Exception("get_template() failed to return template with description %s" % cls.services['ostype']) - - cls.vm_services = { - 'mode': cls.zone.networktype, - 'small': { - 'zoneid': cls.zone.id, - 'template': template.id, - 'displayname': 'testserver', - 'username': cls.config.zones[0].pods[0].clusters[0].hosts[0].username, - 'password': cls.config.zones[0].pods[0].clusters[0].hosts[0].password, - 'ssh_port': 22, - 'hypervisor': cls.config.zones[0].pods[0].clusters[0].hypervisor, - 'privateport': 22, - 'publicport': 22, - 'protocol': 'TCP', - }, - 'service_offerings': { - 'tiny': { - 'name': 'Tiny Instance', - 'displaytext': 'Tiny Instance', - 'cpunumber': 1, - 'cpuspeed': 100, - 'memory': 64, - 'offerha': 'true' - } - } - } - - if cls.zone.localstorageenabled == True: - cls.vm_services['service_offerings']['tiny']['storagetype'] = 'local' - - cls.service_offering = ServiceOffering.create( - cls.api_client, - cls.vm_services['service_offerings']['tiny'] - ) - - cls.cleanup = [ - cls.network_offering_isolated, - cls.service_offering, - cls.network_offering_shared - ] - - cls.logger = logging.getLogger('TestNiciraContoller') - cls.stream_handler = logging.StreamHandler() - cls.logger.setLevel(logging.DEBUG) - cls.logger.addHandler(cls.stream_handler) - - - @classmethod - def tearDownClass(cls): - try: - cleanup_resources(cls.api_client, reversed(cls.cleanup)) - except Exception as e: - raise Exception("Warning: Exception during class cleanup : %s" % e) - - def setUp(self): - self.test_cleanup = [] - - def tearDown(self): - try: - cleanup_resources(self.api_client, reversed(self.test_cleanup)) - except Exception as e: - raise Exception("Warning: Exception during test cleanup : %s" % e) - - - @classmethod - def determine_primary_controller(cls, hosts, credentials): - for host in hosts: - r1 = requests.post("https://%s/ws.v1/login" % host, credentials, verify=False) - r2 = requests.get("https://%s/ws.v1/control-cluster/status" % host, verify=False, cookies=r1.cookies) - status_code = r2.status_code - if status_code == 401: - continue - elif status_code == 200: - return host - raise Exception("None of the supplied hosts (%s) is a Nicira controller" % hosts) - - - @classmethod - def get_transport_zone_from_controller(cls, controller_host, credentials): - r1 = requests.post("https://%s/ws.v1/login" % controller_host, credentials, verify=False) - r2 = requests.get("https://%s/ws.v1/transport-zone" % controller_host, verify=False, cookies=r1.cookies) - status_code = r2.status_code - if status_code == 200: - list_transport_zone_response = r2.json() - result_count = list_transport_zone_response['result_count'] - if result_count == 0: - raise Exception('Nicira controller did not return any Transport Zones') - elif result_count > 1: - cls.logger.debug("Nicira controller returned %s Transport Zones, picking first one" % resultCount) - transport_zone_api_url = list_transport_zone_response['results'][0]['_href'] - r3 = requests.get( - "https://%s%s" % (controller_host, transport_zone_api_url), - verify=False, - cookies=r1.cookies - ) - return r3.json()['uuid'] - else: - raise Exception("Unexpected response from Nicira controller. Status code = %s, content = %s" % status_code) - - - @classmethod - def get_nicira_enabled_physical_network_id(cls, physical_networks): - nicira_physical_network_name = None - for physical_network in physical_networks: - for provider in physical_network.providers: - if provider.name == 'NiciraNvp': - nicira_physical_network_name = physical_network.name - if nicira_physical_network_name is None: - raise Exception('Did not find a Nicira enabled physical network in configuration') - return PhysicalNetwork.list(cls.api_client, name=nicira_physical_network_name)[0].id - - - def determine_secondary_conroller(self, hosts, primary_controller): - secondary = [ s for s in hosts if s != primary_controller ] - if len(secondary) > 0: - return secondary[0] - else: - raise Exception("None of the supplied hosts (%s) is a Nicira secondary" % hosts) - - - def add_nicira_device(self, hostname, l2gatewayserviceuuid=None): - nicira_device = NiciraNvp.add( - self.api_client, - None, - self.physical_network_id, - hostname=hostname, - username=self.nicira_credentials['username'], - password=self.nicira_credentials['password'], - transportzoneuuid=self.transport_zone_uuid, - l2gatewayserviceuuid=l2gatewayserviceuuid - ) - self.test_cleanup.append(nicira_device) - - def create_guest_isolated_network(self): - network_services = { - 'name' : 'nicira_enabled_network_isolated', - 'displaytext' : 'nicira_enabled_network_isolated', - 'zoneid' : self.zone.id, - 'networkoffering' : self.network_offering_isolated.id - } - network = Network.create( - self.api_client, - network_services, - accountid=self.admin_account, - domainid=self.admin_domain.id - ) - self.test_cleanup.append(network) - return network - - def create_guest_shared_network_numerical_vlanid(self): - network_services = { - 'name' : 'nicira_enabled_network_shared', - 'displaytext' : 'nicira_enabled_network_shared', - 'zoneid' : self.zone.id, - 'networkoffering' : self.network_offering_shared.id, - 'startip' : self.nicira_shared_network_iprange.startip, - 'endip' : self.nicira_shared_network_iprange.endip, - 'netmask' : self.nicira_shared_network_iprange.netmask, - 'gateway' : self.nicira_shared_network_iprange.gateway, - 'vlan' : self.nicira_shared_network_iprange.vlan - } - network = Network.create( - self.api_client, - network_services, - accountid=self.admin_account, - domainid=self.admin_domain.id - ) - self.test_cleanup.append(network) - return network - - def create_guest_shared_network_uuid_vlanid(self): - network_services = { - 'name' : 'nicira_enabled_network_shared', - 'displaytext' : 'nicira_enabled_network_shared', - 'zoneid' : self.zone.id, - 'networkoffering' : self.network_offering_shared.id, - 'startip' : self.nicira_shared_network_iprange.startip, - 'endip' : self.nicira_shared_network_iprange.endip, - 'netmask' : self.nicira_shared_network_iprange.netmask, - 'gateway' : self.nicira_shared_network_iprange.gateway, - 'vlan' : self.nicira_shared_network_iprange.vlan_uuid - } - network = Network.create( - self.api_client, - network_services, - accountid=self.admin_account, - domainid=self.admin_domain.id - ) - self.test_cleanup.append(network) - return network - - def create_guest_shared_network_services(self): - network_services = { - 'name' : 'nicira_enabled_network_shared', - 'displaytext' : 'nicira_enabled_network_shared', - 'zoneid' : self.zone.id, - 'networkoffering' : self.network_offering_shared.id, - 'startip' : self.nicira_shared_network_iprange.startip, - 'endip' : self.nicira_shared_network_iprange.endip, - 'netmask' : self.nicira_shared_network_iprange.netmask, - 'gateway' : self.nicira_shared_network_iprange.gateway - } - network = Network.create( - self.api_client, - network_services, - accountid=self.admin_account, - domainid=self.admin_domain.id, - ) - self.test_cleanup.append(network) - return network - - - def create_virtual_machine(self, network): - virtual_machine = VirtualMachine.create( - self.api_client, - self.vm_services['small'], - accountid=self.admin_account, - domainid=self.admin_domain.id, - serviceofferingid=self.service_offering.id, - networkids=[network.id], - mode=self.vm_services['mode'] - ) - self.test_cleanup.append(virtual_machine) - return virtual_machine - - def create_virtual_machine_shared_networks(self, network): - virtual_machine = VirtualMachine.create( - self.api_client, - self.vm_services['small'], - accountid=self.admin_account, - domainid=self.admin_domain.id, - serviceofferingid=self.service_offering.id, - networkids=[network.id], - mode='BASIC' - ) - self.test_cleanup.append(virtual_machine) - return virtual_machine - - - def get_routers_for_network(self, network): - return list_routers( - self.api_client, - accountid=self.admin_account, - domainid=self.admin_domain.id, - networkid=network.id - ) - - - def get_hosts(self): - return list_hosts( - self.api_client, - accountid=self.admin_account, - domainid=self.admin_domain.id - ) - - - def get_primary_router(self, routers): - primary = [r for r in routers if r.redundantstate == 'PRIMARY'] - self.logger.debug("Found %s primary router(s): %s" % (primary.size(), primary)) - return primary[0] - - - def distribute_vm_and_routers_by_hosts(self, virtual_machine, routers): - if len(routers) > 1: - router = self.get_router(routers) - self.logger.debug("Primary Router VM is %s" % router) - else: - router = routers[0] - - if router.hostid == virtual_machine.hostid: - self.logger.debug("Primary Router VM is on the same host as VM") - host = findSuitableHostForMigration(self.api_client, router.id) - if host is not None: - migrate_router(self.api_client, router.id, host.id) - self.logger.debug("Migrated Primary Router VM to host %s" % host.name) - else: - self.fail('No suitable host to migrate Primary Router VM to') - else: - self.logger.debug("Primary Router VM is not on the same host as VM: %s, %s" % (router.hostid, virtual_machine.hostid)) - - - def acquire_publicip(self, network): - self.logger.debug("Associating public IP for network: %s" % network.name) - public_ip = PublicIPAddress.create( - self.api_client, - accountid=self.admin_account, - zoneid=self.zone.id, - domainid=self.admin_domain.id, - networkid=network.id - ) - self.logger.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress, network.id)) - self.test_cleanup.append(public_ip) - return public_ip - - - def create_natrule(self, vm, public_ip, network): - self.logger.debug("Creating NAT rule in network for vm with public IP") - nat_rule = NATRule.create( - self.api_client, - vm, - self.vm_services['small'], - ipaddressid=public_ip.ipaddress.id, - openfirewall=True, - networkid=network.id - ) - self.test_cleanup.append(nat_rule) - return nat_rule - - - @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") - def test_01_nicira_controller(self): - self.add_nicira_device(self.nicira_primary_controller) - - network = self.create_guest_isolated_network() - virtual_machine = self.create_virtual_machine(network) - - list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) - self.logger.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) - - self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') - self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') - - vm_response = list_vm_response[0] - self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') - self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') - - - @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") - def test_02_nicira_controller_redirect(self): - """ - Nicira clusters will redirect clients (in this case ACS) to the primary node. - This test assumes that a Nicira cluster is present and configured properly, and - that it has at least two controller nodes. The test will check that ASC follows - redirects by: - - adding a Nicira Nvp device that points to one of the cluster's secondary controllers, - - create a VM in a Nicira backed network - If all is well, no matter what controller is specified (secondary or primary), the vm (and respective router VM) - should be created without issues. - """ - nicira_secondary = self.determine_secondary_conroller(self.nicira_hosts, self.nicira_primary_controller) - self.logger.debug("Nicira secondary controller is: %s " % nicira_secondary) - - self.add_nicira_device(nicira_secondary) - - network = self.create_guest_isolated_network() - virtual_machine = self.create_virtual_machine(network) - - list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) - self.logger.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) - - self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') - self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') - - vm_response = list_vm_response[0] - self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') - self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') - - - @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") - def test_03_nicira_tunnel_guest_network(self): - self.add_nicira_device(self.nicira_primary_controller) - network = self.create_guest_isolated_network() - virtual_machine = self.create_virtual_machine(network) - public_ip = self.acquire_publicip(network) - nat_rule = self.create_natrule(virtual_machine, public_ip, network) - - list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) - self.logger.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) - - self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') - self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') - - vm_response = list_vm_response[0] - self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') - self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') - - routers = self.get_routers_for_network(network) - - self.distribute_vm_and_routers_by_hosts(virtual_machine, routers) - - ssh_command = 'ping -c 3 google.com' - result = 'failed' - try: - self.logger.debug("SSH into VM: %s" % public_ip.ipaddress.ipaddress) - ssh = virtual_machine.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress) - self.logger.debug('Ping to google.com from VM') - result = str(ssh.execute(ssh_command)) - self.logger.debug("SSH result: %s; COUNT is ==> %s" % (result, result.count("3 packets received"))) - except Exception as e: - self.fail("SSH Access failed for %s: %s" % (virtual_machine.get_ip(), e)) - - self.assertEqual(result.count('3 packets received'), 1, 'Ping to outside world from VM should be successful') - - @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") - def test_04_nicira_shared_networks_numerical_vlanid(self): - """ - Shared Networks Support - CASE 1) Numerical VLAN_ID provided in network creation - """ - self.debug("Starting test case 1 for Shared Networks") - self.add_nicira_device(self.nicira_primary_controller, self.l2gatewayserviceuuid) - network = self.create_guest_shared_network_numerical_vlanid() - virtual_machine = self.create_virtual_machine_shared_networks(network) - - list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) - self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) - - self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') - self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') - - vm_response = list_vm_response[0] - self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') - self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') - - @attr(tags = ["advanced", "smoke", "nicira"], required_hardware="true") - def test_05_nicira_shared_networks_lrouter_uuid_vlan_id(self): - """ - Shared Networks Support - CASE 2) Logical Router's UUID as VLAN_ID provided in network creation - """ - self.debug("Starting test case 2 for Shared Networks") - self.add_nicira_device(self.nicira_primary_controller, self.l2gatewayserviceuuid) - network = self.create_guest_shared_network_uuid_vlanid() - virtual_machine = self.create_virtual_machine_shared_networks(network) - - list_vm_response = VirtualMachine.list(self.api_client, id=virtual_machine.id) - self.debug("Verify listVirtualMachines response for virtual machine: %s" % virtual_machine.id) - - self.assertEqual(isinstance(list_vm_response, list), True, 'Response did not return a valid list') - self.assertNotEqual(len(list_vm_response), 0, 'List of VMs is empty') - - vm_response = list_vm_response[0] - self.assertEqual(vm_response.id, virtual_machine.id, 'Virtual machine in response does not match request') - self.assertEqual(vm_response.state, 'Running', 'VM is not in Running state') diff --git a/tools/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py index 292f52d809bf..7787f6ea4ab3 100644 --- a/tools/apidoc/gen_toc.py +++ b/tools/apidoc/gen_toc.py @@ -104,7 +104,6 @@ 'Netscaler': 'Netscaler', 'NetscalerControlCenter': 'Netscaler', 'NetscalerLoadBalancer': 'Netscaler', - 'SolidFire': 'SolidFire', 'PaloAlto': 'Palo Alto', 'ResourceCount': 'Limit', 'CloudIdentifier': 'Cloud Identifier', @@ -160,9 +159,6 @@ 'StaticRoute': 'VPC', 'Tags': 'Resource tags', 'Icon': 'Resource Icon', - 'NiciraNvpDevice': 'Nicira NVP', - 'BrocadeVcsDevice': 'Brocade VCS', - 'BigSwitchBcfDevice': 'BigSwitch BCF', 'AutoScale': 'AutoScale', 'Counter': 'AutoScale', 'Condition': 'AutoScale', @@ -192,12 +188,9 @@ 'dedicateHost': 'Dedicate Resources', 'releaseDedicatedHost': 'Dedicate Resources', 'Baremetal' : 'Baremetal', - 'UCS' : 'UCS', - 'Ucs' : 'UCS', 'CacheStores' : 'Cache Stores', 'CacheStore' : 'Cache Store', 'OvsElement' : 'Ovs Element', - 'StratosphereSsp' : 'Misc Network Service Providers', 'Metrics' : 'Metrics', 'listClustersMetrics': 'Cluster', 'VpnUser': 'VPN', diff --git a/tools/marvin/marvin/deployDataCenter.py b/tools/marvin/marvin/deployDataCenter.py index db88f7627881..57acf31100a3 100644 --- a/tools/marvin/marvin/deployDataCenter.py +++ b/tools/marvin/marvin/deployDataCenter.py @@ -557,15 +557,7 @@ def configureProviders(self, phynetwrk, providers): self.enableProvider(pnetprovres[0].id) elif provider.name == 'SecurityGroupProvider': self.enableProvider(pnetprovres[0].id) - elif provider.name in ['JuniperContrailRouter', - 'JuniperContrailVpcRouter']: - netprov = addNetworkServiceProvider.\ - addNetworkServiceProviderCmd() - netprov.name = provider.name - netprov.physicalnetworkid = phynetwrk.id - result = self.__apiClient.addNetworkServiceProvider(netprov) - self.enableProvider(result.id) - elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp', 'NiciraNvp']: + elif provider.name in ['Netscaler', 'JuniperSRX', 'F5BigIp']: netprov = addNetworkServiceProvider.\ addNetworkServiceProviderCmd() netprov.name = provider.name @@ -624,17 +616,6 @@ def configureProviders(self, phynetwrk, providers): debug("==== AddF5 " "Successful=====") self.__addToCleanUp("F5LoadBalancer", ret.id) - elif provider.name == 'NiciraNvp': - cmd = addNiciraNvpDevice.addNiciraNvpDeviceCmd() - cmd.hostname = device.hostname - cmd.username = device.username - cmd.password = device.password - cmd.transportzoneuuid = device.transportzoneuuid - cmd.physicalnetworkid = phynetwrk.id - ret = self.__apiClient.addNiciraNvpDevice(cmd) - self.__tcRunLogger.\ - debug("==== AddNiciraNvp Successful =====") - self.__addToCleanUp("NiciraNvp", ret.id) else: raise InvalidParameterException( "Device %s doesn't match " diff --git a/tools/marvin/marvin/lib/base.py b/tools/marvin/marvin/lib/base.py index 636c73209a3f..b44b763c1382 100755 --- a/tools/marvin/marvin/lib/base.py +++ b/tools/marvin/marvin/lib/base.py @@ -4975,57 +4975,6 @@ def list(cls, apiclient, **kwargs): return (apiclient.listNetscalerLoadBalancers(cmd)) -class NiciraNvp: - - def __init__(self, items): - self.__dict__.update(items) - - @classmethod - def add(cls, apiclient, services, physicalnetworkid, - hostname=None, username=None, password=None, transportzoneuuid=None, l2gatewayserviceuuid=None): - cmd = addNiciraNvpDevice.addNiciraNvpDeviceCmd() - cmd.physicalnetworkid = physicalnetworkid - if hostname: - cmd.hostname = hostname - else: - cmd.hostname = services['hostname'] - - if username: - cmd.username = username - else: - cmd.username = services['username'] - - if password: - cmd.password = password - else: - cmd.password = services['password'] - - if transportzoneuuid: - cmd.transportzoneuuid = transportzoneuuid - else: - cmd.transportzoneuuid = services['transportZoneUuid'] - - if l2gatewayserviceuuid: - cmd.l2gatewayserviceuuid = l2gatewayserviceuuid - elif services and 'l2gatewayserviceuuid' in services: - cmd.l2gatewayserviceuuid = services['l2gatewayserviceuuid'] - - return NiciraNvp(apiclient.addNiciraNvpDevice(cmd).__dict__) - - def delete(self, apiclient): - cmd = deleteNiciraNvpDevice.deleteNiciraNvpDeviceCmd() - cmd.nvpdeviceid = self.nvpdeviceid - apiclient.deleteNiciraNvpDevice(cmd) - return - - @classmethod - def list(cls, apiclient, **kwargs): - cmd = listNiciraNvpDevices.listNiciraNvpDevicesCmd() - [setattr(cmd, k, v) for k, v in list(kwargs.items())] - if 'account' in list(kwargs.keys()) and 'domainid' in list(kwargs.keys()): - cmd.listall = True - return (apiclient.listNiciraNvpDevices(cmd)) - class NetworkServiceProvider: """Manage network service providers for CloudStack""" @@ -5462,41 +5411,6 @@ def list(cls, apiclient, **kwargs): return (apiclient.listStaticRoutes(cmd)) -class VNMC: - """Manage VNMC lifecycle""" - - def __init__(self, items): - self.__dict__.update(items) - - def create(cls, apiclient, hostname, username, password, - physicalnetworkid): - """Registers VNMC appliance""" - - cmd = addCiscoVnmcResource.addCiscoVnmcResourceCmd() - cmd.hostname = hostname - cmd.username = username - cmd.password = password - cmd.physicalnetworkid = physicalnetworkid - return VNMC(apiclient.addCiscoVnmcResource(cmd)) - - def delete(self, apiclient): - """Removes VNMC appliance""" - - cmd = deleteCiscoVnmcResource.deleteCiscoVnmcResourceCmd() - cmd.resourceid = self.resourceid - return apiclient.deleteCiscoVnmcResource(cmd) - - @classmethod - def list(cls, apiclient, **kwargs): - """List VNMC appliances""" - - cmd = listCiscoVnmcResources.listCiscoVnmcResourcesCmd() - [setattr(cmd, k, v) for k, v in list(kwargs.items())] - if 'account' in list(kwargs.keys()) and 'domainid' in list(kwargs.keys()): - cmd.listall = True - return (apiclient.listCiscoVnmcResources(cmd)) - - class SSHKeyPair: """Manage SSH Key pairs""" diff --git a/tools/ngui/README.md b/tools/ngui/README.md deleted file mode 100644 index f7664bb5daa5..000000000000 --- a/tools/ngui/README.md +++ /dev/null @@ -1,21 +0,0 @@ - - -# UI for CloudStack using Angular.js -And a flask wrapper on top CloudStack API to make things easy on the client side. diff --git a/tools/ngui/api.py b/tools/ngui/api.py deleted file mode 100644 index 3860a217430a..000000000000 --- a/tools/ngui/api.py +++ /dev/null @@ -1,37 +0,0 @@ -#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. - -from requester import make_request -from precache import apicache -from config import * -import re - -def get_error_code(error): - return int(re.findall("\d{3}",error)[0]) #Find the error code by regular expression - # return int(error[11:14]) #Ugly - -def get_command(verb, subject): - commandlist = apicache.get(verb, None) - if commandlist is not None: - command = commandlist.get(subject, None) - if command is not None: - return command["name"] - return None - -def apicall(command, data ): - response, error = make_request(command, data, None, host, port, apikey, secretkey, protocol, path) - if error is not None: - return error, get_error_code(error) - return response diff --git a/tools/ngui/app.py b/tools/ngui/app.py deleted file mode 100644 index 8bc21d5af435..000000000000 --- a/tools/ngui/app.py +++ /dev/null @@ -1,38 +0,0 @@ -#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. - -from flask import Flask, url_for, render_template, request, json, abort, send_from_directory -from api import apicall - -app = Flask(__name__) - -def get_args(multidict): - """Default type of request.args or request.json is multidict. Converts it to dict so that can be passed to make_request""" - data = {} - for key in multidict.keys(): - data[key] = multidict.get(key) - return data - -@app.route('/api/', methods=['GET']) -def rawapi(command): - if request.method == 'GET': - return apicall(command, get_args(request.args)) - -@app.route('/') -def index(): - return send_from_directory("templates", "index.html") - -if __name__ == '__main__': - app.run(debug=True) diff --git a/tools/ngui/config.py b/tools/ngui/config.py deleted file mode 100644 index 2bed68185d1e..000000000000 --- a/tools/ngui/config.py +++ /dev/null @@ -1,21 +0,0 @@ -#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. - -apikey='DNi_vTVLPNfTEFuqu5F9MrPI3iecf8iRQ3QtGUH1IM2Nd96wNwNlf7BzmF1W8aw6cE2ejZCgyE53wT5VpzauuA' -secretkey='x4jM12uE4LNho3ZNJa8J-Ve6WsgEXd8df1mGGfeuJHMtolkaSBkD5pLX0tvj8YrWhBgtZbKgYsTB00kb7z_3BA' -path='/client/api' -host='localhost' -port='8080' -protocol='http' diff --git a/tools/ngui/precache.py b/tools/ngui/precache.py deleted file mode 100644 index fe63fdc93a96..000000000000 --- a/tools/ngui/precache.py +++ /dev/null @@ -1,19 +0,0 @@ -# -*- coding: utf-8 -*- -# Auto-generated code by cachemaker.py -# 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. -apicache = {u'authorize': {u'securitygroupingress': {u'name': u'authorizeSecurityGroupIngress', u'related': [u'authorizeSecurityGroupEgress'], u'isasync': True, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the security group. If the account parameter is used, domainId must also be used.'}, {u'name': u'startport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'start port for this ingress rule'}, {u'name': u'securitygroupid', u'required': False, u'related': [u'createSecurityGroup', u'listSecurityGroups'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the security group. Mutually exclusive with securityGroupName parameter'}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list associated'}, {u'name': u'usersecuritygrouplist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'user to security group mapping'}, {u'name': u'securitygroupname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The name of the security group. Mutually exclusive with securityGroupName parameter'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the security group. Must be used with domainId.'}, {u'name': u'icmpcode', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'error code for this icmp message'}, {u'name': u'protocol', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'TCP is default. UDP is the other supported protocol'}, {u'name': u'icmptype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'type of the icmp message being sent'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'an optional project of the security group'}, {u'name': u'endport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'end port for this ingress rule'}], u'requiredparams': [], u'description': u'Authorizes a particular ingress rule for this security group'}, u'securitygroupegress': {u'name': u'authorizeSecurityGroupEgress', u'related': [], u'isasync': True, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the security group. Must be used with domainId.'}, {u'name': u'securitygroupname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The name of the security group. Mutually exclusive with securityGroupName parameter'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the security group. If the account parameter is used, domainId must also be used.'}, {u'name': u'icmpcode', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'error code for this icmp message'}, {u'name': u'securitygroupid', u'required': False, u'related': [u'createSecurityGroup', u'listSecurityGroups'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the security group. Mutually exclusive with securityGroupName parameter'}, {u'name': u'icmptype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'type of the icmp message being sent'}, {u'name': u'protocol', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'TCP is default. UDP is the other supported protocol'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'an optional project of the security group'}, {u'name': u'endport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'end port for this egress rule'}, {u'name': u'usersecuritygrouplist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'user to security group mapping'}, {u'name': u'startport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'start port for this egress rule'}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list associated'}], u'requiredparams': [], u'description': u'Authorizes a particular egress rule for this security group'}}, u'restore': {u'virtualmachine': {u'name': u'restoreVirtualMachine', u'related': [u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine'], u'isasync': True, u'params': [{u'name': u'virtualmachineid', u'required': True, u'related': [u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'Virtual Machine ID'}], u'requiredparams': [u'virtualmachineid'], u'description': u'Restore a VM to original template or specific snapshot'}}, u'suspend': {u'project': {u'name': u'suspendProject', u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'suspendProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to be suspended'}], u'requiredparams': [u'id'], u'description': u'Suspends a project'}}, u'revoke': {u'securitygroupingress': {u'name': u'revokeSecurityGroupIngress', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'The ID of the ingress rule'}], u'requiredparams': [u'id'], u'description': u'Deletes a particular ingress rule from this security group'}, u'securitygroupegress': {u'name': u'revokeSecurityGroupEgress', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'The ID of the egress rule'}], u'requiredparams': [u'id'], u'description': u'Deletes a particular egress rule from this security group'}}, u'disassociate': {u'ipaddress': {u'name': u'disassociateIpAddress', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'the id of the public ip address to disassociate'}], u'requiredparams': [u'id'], u'description': u'Disassociates an ip address from the account.'}}, u'migrate': {u'volume': {u'name': u'migrateVolume', u'related': [u'detachVolume', u'resizeVolume', u'attachVolume', u'uploadVolume', u'createVolume'], u'isasync': True, u'params': [{u'name': u'volumeid', u'required': True, u'related': [u'migrateVolume', u'detachVolume', u'resizeVolume', u'attachVolume', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the volume'}, {u'name': u'storageid', u'required': True, u'related': [u'cancelStorageMaintenance', u'enableStorageMaintenance', u'updateStoragePool', u'createStoragePool', u'listStoragePools'], u'length': 255, u'type': u'uuid', u'description': u'destination storage pool ID to migrate the volume to'}], u'requiredparams': [u'volumeid', u'storageid'], u'description': u'Migrate volume'}, u'systemvm': {u'name': u'migrateSystemVm', u'related': [], u'isasync': True, u'params': [{u'name': u'virtualmachineid', u'required': True, u'related': [u'rebootSystemVm', u'listSystemVms'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine'}, {u'name': u'hostid', u'required': True, u'related': [u'addHost', u'updateHost', u'listHosts', u'listExternalLoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'destination Host ID to migrate VM to'}], u'requiredparams': [u'virtualmachineid', u'hostid'], u'description': u'Attempts Migration of a system virtual machine to the host specified.'}, u'virtualmachine': {u'name': u'migrateVirtualMachine', u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'deployVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'storageid', u'required': False, u'related': [u'cancelStorageMaintenance'], u'length': 255, u'type': u'long', u'description': u'Destination storage pool ID to migrate VM volumes to. Required for migrating the root disk volume'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine'}, {u'name': u'hostid', u'required': False, u'related': [u'addHost', u'updateHost', u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'Destination Host ID to migrate VM to. Required for live migrating a VM from host to host'}], u'requiredparams': [u'virtualmachineid'], u'description': u'Attempts Migration of a VM to a different host or Root volume of the vm to a different storage pool'}}, u'lock': {u'account': {u'name': u'lockAccount', u'related': [u'markDefaultZoneForAccount'], u'isasync': False, u'params': [{u'name': u'domainid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Locks the specified account on this domain.'}, {u'name': u'account', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Locks the specified account.'}], u'requiredparams': [u'domainid', u'account'], u'description': u'Locks an account'}, u'user': {u'name': u'lockUser', u'related': [u'listUsers'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'lockUser', u'listUsers'], u'length': 255, u'type': u'uuid', u'description': u'Locks user by user ID.'}], u'requiredparams': [u'id'], u'description': u'Locks a user account'}}, u'dissociate': {u'lun': {u'name': u'dissociateLun', u'related': [], u'isasync': False, u'params': [{u'name': u'iqn', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Guest IQN.'}, {u'name': u'path', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'LUN path.'}], u'requiredparams': [u'iqn', u'path'], u'description': u'Dissociate a LUN'}}, u'activate': {u'project': {u'name': u'activateProject', u'related': [u'createProject', u'listProjectAccounts'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to be modified'}], u'requiredparams': [u'id'], u'description': u'Activates a project'}}, u'reconnect': {u'host': {u'name': u'reconnectHost', u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addSecondaryStorage', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers', u'prepareHostForMaintenance'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addSecondaryStorage', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'reconnectHost', u'listExternalLoadBalancers', u'prepareHostForMaintenance'], u'length': 255, u'type': u'uuid', u'description': u'the host ID'}], u'requiredparams': [u'id'], u'description': u'Reconnects a host.'}}, u'cancel': {u'hostmaintenance': {u'name': u'cancelHostMaintenance', u'related': [u'listSwifts', u'addHost', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'the host ID'}], u'requiredparams': [u'id'], u'description': u'Cancels host maintenance.'}, u'storagemaintenance': {u'name': u'cancelStorageMaintenance', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'cancelStorageMaintenance'], u'length': 255, u'type': u'uuid', u'description': u'the primary storage ID'}], u'requiredparams': [u'id'], u'description': u'Cancels maintenance for primary storage'}}, u'query': {u'asyncjobresult': {u'name': u'queryAsyncJobResult', u'related': [], u'isasync': False, u'params': [{u'name': u'jobid', u'required': True, u'related': [u'queryAsyncJobResult'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the asynchronous job'}], u'requiredparams': [u'jobid'], u'description': u'Retrieves the current status of asynchronous job.'}}, u'recover': {u'virtualmachine': {u'name': u'recoverVirtualMachine', u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}], u'requiredparams': [u'id'], u'description': u'Recovers a virtual machine.'}}, u'extract': {u'volume': {u'name': u'extractVolume', u'related': [u'extractTemplate', u'extractIso'], u'isasync': True, u'params': [{u'name': u'url', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the url to which the volume would be extracted'}, {u'name': u'id', u'required': True, u'related': [u'migrateVolume', u'detachVolume', u'resizeVolume', u'attachVolume', u'listVolumes', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the volume'}, {u'name': u'mode', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone where the volume is located'}], u'requiredparams': [u'id', u'mode', u'zoneid'], u'description': u'Extracts volume'}, u'iso': {u'name': u'extractIso', u'related': [u'extractTemplate'], u'isasync': True, u'params': [{u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone where the ISO is originally located'}, {u'name': u'url', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the url to which the ISO would be extracted'}, {u'name': u'mode', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD'}, {u'name': u'id', u'required': True, u'related': [u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the ISO file'}], u'requiredparams': [u'mode', u'id'], u'description': u'Extracts an ISO'}, u'template': {u'name': u'extractTemplate', u'related': [], u'isasync': True, u'params': [{u'name': u'mode', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD'}, {u'name': u'id', u'required': True, u'related': [u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the template'}, {u'name': u'url', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the url to which the ISO would be extracted'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone where the ISO is originally located'}], u'requiredparams': [u'mode', u'id'], u'description': u'Extracts a template'}}, u'copy': {u'iso': {u'name': u'copyIso', u'related': [u'updateIso', u'listIsos'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'Template ID.'}, {u'name': u'destzoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'ID of the zone the template is being copied to.'}, {u'name': u'sourcezoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'ID of the zone the template is currently hosted on.'}], u'requiredparams': [u'id', u'destzoneid', u'sourcezoneid'], u'description': u'Copies an iso from one zone to another.'}, u'template': {u'name': u'copyTemplate', u'related': [u'listTemplates', u'registerIso', u'updateTemplate', u'prepareTemplate', u'registerTemplate', u'copyIso', u'updateIso', u'listIsos'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'copyTemplate', u'listTemplates', u'registerIso', u'updateTemplate', u'prepareTemplate', u'registerTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'Template ID.'}, {u'name': u'destzoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'ID of the zone the template is being copied to.'}, {u'name': u'sourcezoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'ID of the zone the template is currently hosted on.'}], u'requiredparams': [u'id', u'destzoneid', u'sourcezoneid'], u'description': u'Copies a template from one zone to another.'}}, u'prepare': {u'hostformaintenance': {u'name': u'prepareHostForMaintenance', u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addSecondaryStorage', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addSecondaryStorage', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers', u'prepareHostForMaintenance'], u'length': 255, u'type': u'uuid', u'description': u'the host ID'}], u'requiredparams': [u'id'], u'description': u'Prepares a host for maintenance.'}, u'template': {u'name': u'prepareTemplate', u'related': [u'registerIso', u'updateTemplate', u'copyIso', u'updateIso', u'listIsos'], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'zone ID of the template to be prepared in primary storage(s).'}, {u'name': u'templateid', u'required': True, u'related': [u'registerIso', u'updateTemplate', u'prepareTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'template ID of the template to be prepared in primary storage(s).'}], u'requiredparams': [u'zoneid', u'templateid'], u'description': u'load template into primary storage'}}, u'attach': {u'volume': {u'name': u'attachVolume', u'related': [u'detachVolume', u'resizeVolume', u'uploadVolume', u'createVolume'], u'isasync': True, u'params': [{u'name': u'deviceid', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'the ID of the device to map the volume to within the guest OS. If no deviceId is passed in, the next available deviceId will be chosen. Possible values for a Linux OS are:* 1 - /dev/xvdb* 2 - /dev/xvdc* 4 - /dev/xvde* 5 - /dev/xvdf* 6 - /dev/xvdg* 7 - /dev/xvdh* 8 - /dev/xvdi* 9 - /dev/xvdj'}, {u'name': u'id', u'required': True, u'related': [u'detachVolume', u'resizeVolume', u'attachVolume', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u' the ID of the virtual machine'}], u'requiredparams': [u'id', u'virtualmachineid'], u'description': u'Attaches a disk volume to a virtual machine.'}, u'iso': {u'name': u'attachIso', u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'virtualmachineid', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine'}, {u'name': u'id', u'required': True, u'related': [u'listTemplates', u'registerIso', u'updateTemplate', u'prepareTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the ISO file'}], u'requiredparams': [u'virtualmachineid', u'id'], u'description': u'Attaches an ISO to a virtual machine.'}}, u'create': {u'loadbalancerrule': {u'name': u'createLoadBalancerRule', u'related': [u'updateLoadBalancerRule'], u'isasync': True, u'params': [{u'name': u'openfirewall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, firewall rule for source/end public port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB rule is being created for VPC guest network 2) in all other cases defaulted to true'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account associated with the load balancer. Must be used with the domainId parameter.'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the domain ID associated with the load balancer'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm'}, {u'name': u'publicipid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'public ip address id from where the network traffic will be load balanced from'}, {u'name': u'algorithm', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'load balancer algorithm (source, roundrobin, leastconn)'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the load balancer rule'}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list to forward traffic from'}, {u'name': u'publicport', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the public port from where the network traffic will be load balanced from'}, {u'name': u'description', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the description of the load balancer rule'}, {u'name': u'privateport', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the private port of the private ip address/virtual machine where the network traffic will be load balanced to'}, {u'name': u'networkid', u'required': False, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'The guest network this rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)'}], u'requiredparams': [u'algorithm', u'name', u'publicport', u'privateport'], u'description': u'Creates a load balancer rule'}, u'domain': {u'name': u'createDomain', u'related': [], u'isasync': False, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'creates domain with this name'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Domain UUID, required for adding domain from another Region'}, {u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Network domain for networks in the domain'}, {u'name': u'parentdomainid', u'required': False, u'related': [u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'assigns new domain a parent domain by domain ID of the parent. If no parent domain is specied, the ROOT domain is assumed.'}], u'requiredparams': [u'name'], u'description': u'Creates a domain'}, u'snapshotpolicy': {u'name': u'createSnapshotPolicy', u'related': [u'listSnapshotPolicies'], u'isasync': False, u'params': [{u'name': u'intervaltype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'valid values are HOURLY, DAILY, WEEKLY, and MONTHLY'}, {u'name': u'maxsnaps', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'maximum number of snapshots to retain'}, {u'name': u'schedule', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'time the snapshot is scheduled to be taken. Format is:* if HOURLY, MM* if DAILY, MM:HH* if WEEKLY, MM:HH:DD (1-7)* if MONTHLY, MM:HH:DD (1-28)'}, {u'name': u'timezone', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.'}, {u'name': u'volumeid', u'required': True, u'related': [u'detachVolume', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}], u'requiredparams': [u'intervaltype', u'maxsnaps', u'schedule', u'timezone', u'volumeid'], u'description': u'Creates a snapshot policy for the account.'}, u'diskoffering': {u'name': u'createDiskOffering', u'related': [u'listDiskOfferings'], u'isasync': False, u'params': [{u'name': u'customized', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'whether disk offering is custom or not'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 4096, u'type': u'string', u'description': u'alternate display text of the disk offering'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the containing domain, null for public offerings'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the disk offering'}, {u'name': u'disksize', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'size of the disk offering in GB'}, {u'name': u'storagetype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the storage type of the disk offering. Values are local and shared.'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'tags for the disk offering'}], u'requiredparams': [u'displaytext', u'name'], u'description': u'Creates a disk offering.'}, u'securitygroup': {u'name': u'createSecurityGroup', u'related': [u'listSecurityGroups'], u'isasync': False, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the security group. Must be used with domainId.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the security group. If the account parameter is used, domainId must also be used.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the security group'}, {u'name': u'description', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the description of the security group'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Deploy vm for the project'}], u'requiredparams': [u'name'], u'description': u'Creates a security group'}, u'portforwardingrule': {u'name': u'createPortForwardingRule', u'related': [u'listIpForwardingRules'], u'isasync': True, u'params': [{u'name': u'privateport', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u"the starting port of port forwarding rule's private port range"}, {u'name': u'ipaddressid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the IP address id of the port forwarding rule'}, {u'name': u'protocol', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the protocol for the port fowarding rule. Valid values are TCP or UDP.'}, {u'name': u'openfirewall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF rule is being created for VPC guest network 2) in all other cases defaulted to true'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine for the port forwarding rule'}, {u'name': u'privateendport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u"the ending port of port forwarding rule's private port range"}, {u'name': u'networkid', u'required': False, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'The network of the vm the Port Forwarding rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)'}, {u'name': u'publicendport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u"the ending port of port forwarding rule's private port range"}, {u'name': u'publicport', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u"the starting port of port forwarding rule's public port range"}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list to forward traffic from'}], u'requiredparams': [u'privateport', u'ipaddressid', u'protocol', u'virtualmachineid', u'publicport'], u'description': u'Creates a port forwarding rule'}, u'pod': {u'name': u'createPod', u'related': [u'updatePod', u'listPods'], u'isasync': False, u'params': [{u'name': u'startip', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the starting IP address for the Pod'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the Pod'}, {u'name': u'zoneid', u'required': True, u'related': [u'listZones'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID in which the Pod will be created'}, {u'name': u'endip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IP address for the Pod'}, {u'name': u'netmask', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask for the Pod'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this Pod for allocation of new resources'}, {u'name': u'gateway', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway for the Pod'}], u'requiredparams': [u'startip', u'name', u'zoneid', u'netmask', u'gateway'], u'description': u'Creates a new Pod.'}, u'ipforwardingrule': {u'name': u'createIpForwardingRule', u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'listPortForwardingRules', u'createPortForwardingRule'], u'isasync': True, u'params': [{u'name': u'endport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the end port for the rule'}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list to forward traffic from'}, {u'name': u'ipaddressid', u'required': True, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'the public IP address id of the forwarding rule, already associated via associateIp'}, {u'name': u'openfirewall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default'}, {u'name': u'startport', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the start port for the rule'}, {u'name': u'protocol', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the protocol for the rule. Valid values are TCP or UDP.'}], u'requiredparams': [u'ipaddressid', u'startport', u'protocol'], u'description': u'Creates an ip forwarding rule'}, u'vpnconnection': {u'name': u'createVpnConnection', u'related': [u'listVpnConnections', u'resetVpnConnection'], u'isasync': True, u'params': [{u'name': u's2svpngatewayid', u'required': True, u'related': [u'createVpnGateway', u'listVpnGateways'], u'length': 255, u'type': u'uuid', u'description': u'id of the vpn gateway'}, {u'name': u's2scustomergatewayid', u'required': True, u'related': [u'updateVpnCustomerGateway', u'createVpnCustomerGateway', u'listVpnCustomerGateways'], u'length': 255, u'type': u'uuid', u'description': u'id of the customer gateway'}], u'requiredparams': [u's2svpngatewayid', u's2scustomergatewayid'], u'description': u'Create site to site vpn connection'}, u'vpncustomergateway': {u'name': u'createVpnCustomerGateway', u'related': [], u'isasync': True, u'params': [{u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the domain ID associated with the gateway. If used with the account parameter returns the gateway associated with the account for the specified domain.'}, {u'name': u'gateway', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'public ip address id of the customer gateway'}, {u'name': u'esplifetime', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'Lifetime of phase 2 VPN connection to the customer gateway, in seconds'}, {u'name': u'esppolicy', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'ESP policy of the customer gateway'}, {u'name': u'ikepolicy', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'IKE policy of the customer gateway'}, {u'name': u'cidrlist', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'guest cidr list of the customer gateway'}, {u'name': u'dpd', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'If DPD is enabled for VPN connection'}, {u'name': u'ipsecpsk', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'IPsec Preshared-Key of the customer gateway'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account associated with the gateway. Must be used with the domainId parameter.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of this customer gateway'}, {u'name': u'ikelifetime', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'Lifetime of phase 1 VPN connection to the customer gateway, in seconds'}], u'requiredparams': [u'gateway', u'esppolicy', u'ikepolicy', u'cidrlist', u'ipsecpsk'], u'description': u'Creates site to site vpn customer gateway'}, u'lbstickinesspolicy': {u'name': u'createLBStickinessPolicy', u'related': [], u'isasync': True, u'params': [{u'name': u'lbruleid', u'required': True, u'related': [u'listIpForwardingRules'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the LB Stickiness policy'}, {u'name': u'methodname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the LB Stickiness policy method, possible values can be obtained from ListNetworks API '}, {u'name': u'description', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the description of the LB Stickiness policy'}, {u'name': u'param', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'param list. Example: param[0].name=cookiename¶m[0].value=LBCookie '}], u'requiredparams': [u'lbruleid', u'name', u'methodname'], u'description': u'Creates a Load Balancer stickiness policy '}, u'vpcoffering': {u'name': u'createVPCOffering', u'related': [u'listVPCOfferings'], u'isasync': True, u'params': [{u'name': u'displaytext', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the vpc offering'}, {u'name': u'supportedservices', u'required': True, u'related': [], u'length': 255, u'type': u'list', u'description': u'services supported by the vpc offering'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the vpc offering'}], u'requiredparams': [u'displaytext', u'supportedservices', u'name'], u'description': u'Creates VPC offering'}, u'network': {u'name': u'createNetwork', u'related': [u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'isasync': False, u'params': [{u'name': u'endipv6', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IPv6 address in the IPv6 network range'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'an optional project for the ssh key'}, {u'name': u'ip6cidr', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the CIDR of IPv6 network, must be at least /64'}, {u'name': u'acltype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Access control type; supported values are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network'}, {u'name': u'gateway', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway of the network. Required for Shared networks and Isolated networks when it belongs to VPC'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the network'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID the network belongs to'}, {u'name': u'subdomainaccess', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Defines whether to allow subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified'}, {u'name': u'startip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the beginning IP address in the network IP range'}, {u'name': u'netmask', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask of the network. Required for Shared networks and Isolated networks when it belongs to VPC'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'domain ID of the account owning a network'}, {u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'network domain'}, {u'name': u'ip6gateway', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway of the IPv6 network. Required for Shared networks and Isolated networks when it belongs to VPC'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'account who will own the network'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the network'}, {u'name': u'startipv6', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the beginning IPv6 address in the IPv6 network range'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the network'}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'the VPC network belongs to'}, {u'name': u'endip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IP address in the network IP range. If not specified, will be defaulted to startIP'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ID or VID of the network'}, {u'name': u'networkofferingid', u'required': True, u'related': [u'createNetworkOffering', u'updateNetworkOffering'], u'length': 255, u'type': u'uuid', u'description': u'the network offering id'}], u'requiredparams': [u'displaytext', u'zoneid', u'name', u'networkofferingid'], u'description': u'Creates a network'}, u'zone': {u'name': u'createZone', u'related': [u'listZones'], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the containing domain, null for public zones'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the Zone'}, {u'name': u'ip6dns2', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the second DNS for IPv6 network in the Zone'}, {u'name': u'domain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Network domain name for the networks in the zone'}, {u'name': u'internaldns1', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the first internal DNS for the Zone'}, {u'name': u'localstorageenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if local storage offering enabled, false otherwise'}, {u'name': u'securitygroupenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if network is security group enabled, false otherwise'}, {u'name': u'networktype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'network type of the zone, can be Basic or Advanced'}, {u'name': u'internaldns2', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the second internal DNS for the Zone'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this Zone for allocation of new resources'}, {u'name': u'guestcidraddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the guest CIDR address for the Zone'}, {u'name': u'dns1', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the first DNS for the Zone'}, {u'name': u'ip6dns1', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the first DNS for IPv6 network in the Zone'}, {u'name': u'dns2', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the second DNS for the Zone'}], u'requiredparams': [u'name', u'internaldns1', u'networktype', u'dns1'], u'description': u'Creates a Zone.'}, u'remoteaccessvpn': {u'name': u'createRemoteAccessVpn', u'related': [], u'isasync': True, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the VPN. Must be used with domainId.'}, {u'name': u'openfirewall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default'}, {u'name': u'publicipid', u'required': True, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'public ip address id of the vpn server'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the VPN. If the account parameter is used, domainId must also be used.'}, {u'name': u'iprange', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the range of ip addresses to allocate to vpn clients. The first ip in the range will be taken by the vpn server'}], u'requiredparams': [u'publicipid'], u'description': u'Creates a l2tp/ipsec remote access vpn'}, u'instancegroup': {u'name': u'createInstanceGroup', u'related': [], u'isasync': False, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account of the instance group. The account parameter must be used with the domainId parameter.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'The project of the instance group'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the instance group'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the domain ID of account owning the instance group'}], u'requiredparams': [u'name'], u'description': u'Creates a vm group'}, u'autoscalepolicy': {u'name': u'createAutoScalePolicy', u'related': [u'updateAutoScalePolicy'], u'isasync': True, u'params': [{u'name': u'action', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the action to be executed if all the conditions evaluate to true for the specified duration.'}, {u'name': u'quiettime', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the cool down period for which the policy should not be evaluated after the action has been taken'}, {u'name': u'conditionids', u'required': True, u'related': [], u'length': 255, u'type': u'list', u'description': u'the list of IDs of the conditions that are being evaluated on every interval'}, {u'name': u'duration', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the duration for which the conditions have to be true before action is taken'}], u'requiredparams': [u'action', u'conditionids', u'duration'], u'description': u'Creates an autoscale policy for a provision or deprovision action, the action is taken when the all the conditions evaluates to true for the specified duration. The policy is in effect once it is attached to a autscale vm group.'}, u'tags': {u'name': u'createTags', u'related': [], u'isasync': True, u'params': [{u'name': u'tags', u'required': True, u'related': [], u'length': 255, u'type': u'map', u'description': u'Map of tags (key/value pairs)'}, {u'name': u'resourcetype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'type of the resource'}, {u'name': u'customer', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"identifies client specific tag. When the value is not null, the tag can't be used by cloudStack code internally"}, {u'name': u'resourceids', u'required': True, u'related': [], u'length': 255, u'type': u'list', u'description': u'list of resources to create the tags for'}], u'requiredparams': [u'tags', u'resourcetype', u'resourceids'], u'description': u'Creates resource tag(s)'}, u'serviceoffering': {u'name': u'createServiceOffering', u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings'], u'isasync': False, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the service offering'}, {u'name': u'storagetype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the storage type of the service offering. Values are local and shared.'}, {u'name': u'issystem', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'is this a system vm offering'}, {u'name': u'cpunumber', u'required': True, u'related': [], u'length': 255, u'type': u'long', u'description': u'the CPU number of the service offering'}, {u'name': u'systemvmtype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the system VM type. Possible types are "domainrouter", "consoleproxy" and "secondarystoragevm".'}, {u'name': u'limitcpuuse', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'restrict the CPU usage to committed service offering'}, {u'name': u'hosttags', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the host tag for this service offering.'}, {u'name': u'offerha', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'the HA for the service offering'}, {u'name': u'memory', u'required': True, u'related': [], u'length': 255, u'type': u'long', u'description': u'the total memory of the service offering in MB'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the containing domain, null for public offerings'}, {u'name': u'cpuspeed', u'required': True, u'related': [], u'length': 255, u'type': u'long', u'description': u'the CPU speed of the service offering in MHz.'}, {u'name': u'networkrate', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'data transfer rate in megabits per second allowed. Supported only for non-System offering and system offerings having "domainrouter" systemvmtype'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the service offering'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the tags for this service offering.'}], u'requiredparams': [u'name', u'cpunumber', u'memory', u'cpuspeed', u'displaytext'], u'description': u'Creates a service offering.'}, u'condition': {u'name': u'createCondition', u'related': [], u'isasync': True, u'params': [{u'name': u'threshold', u'required': True, u'related': [], u'length': 255, u'type': u'long', u'description': u'Threshold value.'}, {u'name': u'counterid', u'required': True, u'related': [u'listConditions', u'listCounters', u'createCounter'], u'length': 255, u'type': u'uuid', u'description': u'ID of the Counter.'}, {u'name': u'relationaloperator', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Relational Operator to be used with threshold.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account of the condition. Must be used with the domainId parameter.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the domain ID of the account.'}], u'requiredparams': [u'threshold', u'counterid', u'relationaloperator'], u'description': u'Creates a condition'}, u'storagepool': {u'name': u'createStoragePool', u'related': [u'cancelStorageMaintenance', u'listStoragePools'], u'isasync': False, u'params': [{u'name': u'clusterid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the cluster ID for the storage pool'}, {u'name': u'zoneid', u'required': True, u'related': [u'listZones'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the storage pool'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name for the storage pool'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the tags for the storage pool'}, {u'name': u'podid', u'required': True, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID for the storage pool'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL of the storage pool'}, {u'name': u'details', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'the details for the storage pool'}], u'requiredparams': [u'clusterid', u'zoneid', u'name', u'podid', u'url'], u'description': u'Creates a storage pool.'}, u'vpngateway': {u'name': u'createVpnGateway', u'related': [], u'isasync': True, u'params': [{u'name': u'vpcid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'public ip address id of the vpn gateway'}], u'requiredparams': [u'vpcid'], u'description': u'Creates site to site vpn local gateway'}, u'autoscalevmgroup': {u'name': u'createAutoScaleVmGroup', u'related': [u'updateAutoScaleVmGroup'], u'isasync': True, u'params': [{u'name': u'vmprofileid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the autoscale profile that contains information about the vms in the vm group.'}, {u'name': u'scaledownpolicyids', u'required': True, u'related': [u'updateAutoScalePolicy'], u'length': 255, u'type': u'list', u'description': u'list of scaledown autoscale policies'}, {u'name': u'scaleuppolicyids', u'required': True, u'related': [u'updateAutoScalePolicy'], u'length': 255, u'type': u'list', u'description': u'list of scaleup autoscale policies'}, {u'name': u'interval', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the frequency at which the conditions have to be evaluated'}, {u'name': u'minmembers', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.'}, {u'name': u'maxmembers', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the maximum number of members in the vmgroup, The number of instances in the vm group will be equal to or less than this number.'}, {u'name': u'lbruleid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}], u'requiredparams': [u'vmprofileid', u'scaledownpolicyids', u'scaleuppolicyids', u'minmembers', u'maxmembers', u'lbruleid'], u'description': u'Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.'}, u'networkacl': {u'name': u'createNetworkACL', u'related': [], u'isasync': True, u'params': [{u'name': u'icmpcode', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'error code for this icmp message'}, {u'name': u'endport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the ending port of ACL'}, {u'name': u'traffictype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the traffic type for the ACL,can be Ingress or Egress, defaulted to Ingress if not specified'}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list to allow traffic from/to'}, {u'name': u'networkid', u'required': True, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'The network of the vm the ACL will be created for'}, {u'name': u'protocol', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the protocol for the ACL rule. Valid values are TCP/UDP/ICMP.'}, {u'name': u'startport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the starting port of ACL'}, {u'name': u'icmptype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'type of the icmp message being sent'}], u'requiredparams': [u'networkid', u'protocol'], u'description': u'Creates a ACL rule the given network (the network has to belong to VPC)'}, u'template': {u'name': u'createTemplate', u'related': [u'cancelStorageMaintenance', u'enableStorageMaintenance', u'updateStoragePool', u'createStoragePool', u'listStoragePools'], u'isasync': True, u'params': [{u'name': u'ostypeid', u'required': True, u'related': [u'listOsTypes'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the OS Type that best represents the OS of this template.'}, {u'name': u'templatetag', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the tag for this template.'}, {u'name': u'bits', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'32 or 64 bit'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this template is a public template, false otherwise'}, {u'name': u'volumeid', u'required': False, u'related': [u'migrateVolume', u'detachVolume', u'resizeVolume', u'attachVolume', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in'}, {u'name': u'passwordenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template supports the password reset feature; default is false'}, {u'name': u'snapshotid', u'required': False, u'related': [u'createSnapshot', u'listSnapshots'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'listLoadBalancerRuleInstances', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM whose hypervisor type is BareMetal'}, {u'name': u'url', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Optional, only for baremetal hypervisor. The directory name where template stored on CIFS server'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the display text of the template. This is usually used for display purposes.'}, {u'name': u'details', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'Template details in key/value pairs.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the template'}, {u'name': u'isfeatured', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this template is a featured template, false otherwise'}, {u'name': u'requireshvm', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template requires HVM, false otherwise'}], u'requiredparams': [u'ostypeid', u'displaytext', u'name'], u'description': u'Creates a template of a virtual machine. The virtual machine must be in a STOPPED state. A template created from this command is automatically designated as a private template visible to the account that created it.'}, u'privategateway': {u'name': u'createPrivateGateway', u'related': [], u'isasync': True, u'params': [{u'name': u'vlan', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the Vlan for the private gateway'}, {u'name': u'gateway', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway of the Private gateway'}, {u'name': u'netmask', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask of the Private gateway'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID the network belongs to'}, {u'name': u'vpcid', u'required': True, u'related': [u'restartVPC'], u'length': 255, u'type': u'uuid', u'description': u'the VPC network belongs to'}, {u'name': u'ipaddress', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the IP address of the Private gateaway'}], u'requiredparams': [u'vlan', u'gateway', u'netmask', u'vpcid', u'ipaddress'], u'description': u'Creates a private gateway'}, u'volumeonfiler': {u'name': u'createVolumeOnFiler', u'related': [], u'isasync': False, u'params': [{u'name': u'volumename', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'volume name.'}, {u'name': u'aggregatename', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'aggregate name.'}, {u'name': u'poolname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}, {u'name': u'snapshotpolicy', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'snapshot policy.'}, {u'name': u'ipaddress', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'ip address.'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'password.'}, {u'name': u'size', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'volume size.'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'user name.'}, {u'name': u'snapshotreservation', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'snapshot reservation.'}], u'requiredparams': [u'volumename', u'aggregatename', u'poolname', u'ipaddress', u'password', u'size', u'username'], u'description': u'Create a volume'}, u'staticroute': {u'name': u'createStaticRoute', u'related': [], u'isasync': True, u'params': [{u'name': u'gatewayid', u'required': True, u'related': [u'createPrivateGateway'], u'length': 255, u'type': u'uuid', u'description': u'the gateway id we are creating static route for'}, {u'name': u'cidr', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'static route cidr'}], u'requiredparams': [u'gatewayid', u'cidr'], u'description': u'Creates a static route'}, u'volume': {u'name': u'createVolume', u'related': [u'detachVolume', u'uploadVolume'], u'isasync': True, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the disk volume'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the availability zone'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts'], u'length': 255, u'type': u'uuid', u'description': u'the project associated with the volume. Mutually exclusive with account parameter'}, {u'name': u'diskofferingid', u'required': False, u'related': [u'updateDiskOffering', u'createDiskOffering', u'listDiskOfferings'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk offering. Either diskOfferingId or snapshotId must be passed in.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account associated with the disk volume. Must be used with the domainId parameter.'}, {u'name': u'size', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'Arbitrary volume size'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the domain ID associated with the disk offering. If used with the account parameter returns the disk volume associated with the account for the specified domain.'}, {u'name': u'snapshotid', u'required': False, u'related': [u'createSnapshot', u'listSnapshots'], u'length': 255, u'type': u'uuid', u'description': u'the snapshot ID for the disk volume. Either diskOfferingId or snapshotId must be passed in.'}], u'requiredparams': [u'name'], u'description': u'Creates a disk volume from a disk offering. This disk volume must still be attached to a virtual machine to make use of it.'}, u'user': {u'name': u'createUser', u'related': [u'lockUser', u'listUsers'], u'isasync': False, u'params': [{u'name': u'account', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Creates the user under the specified account. If no account is specified, the username will be used as the account name.'}, {u'name': u'userid', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'User UUID, required for adding account from external provisioning system'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Unique username.'}, {u'name': u'timezone', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Creates the user under the specified domain. Has to be accompanied with the account parameter'}, {u'name': u'email', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'email'}, {u'name': u'lastname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'lastname'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Hashed password (Default is MD5). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.'}, {u'name': u'firstname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'firstname'}], u'requiredparams': [u'account', u'username', u'email', u'lastname', u'password', u'firstname'], u'description': u'Creates a user for an account that already exists'}, u'vpc': {u'name': u'createVPC', u'related': [u'updateVPC', u'restartVPC', u'listVPCs'], u'isasync': True, u'params': [{u'name': u'displaytext', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the VPC'}, {u'name': u'zoneid', u'required': True, u'related': [u'listZones'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the availability zone'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the VPC'}, {u'name': u'vpcofferingid', u'required': True, u'related': [u'listVPCOfferings', u'createVPCOffering'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the VPC offering'}, {u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'VPC network domain. All networks inside the VPC will belong to this domain'}, {u'name': u'cidr', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u"the cidr of the VPC. All VPC guest networks' cidrs should be within this CIDR"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account associated with the VPC. Must be used with the domainId parameter.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the domain ID associated with the VPC. If used with the account parameter returns the VPC associated with the account for the specified domain.'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts'], u'length': 255, u'type': u'uuid', u'description': u'create VPC for the project'}], u'requiredparams': [u'displaytext', u'zoneid', u'name', u'vpcofferingid', u'cidr'], u'description': u'Creates a VPC'}, u'storagenetworkiprange': {u'name': u'createStorageNetworkIpRange', u'related': [u'listStorageNetworkIpRange', u'updateStorageNetworkIpRange'], u'isasync': True, u'params': [{u'name': u'startip', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the beginning IP address'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Optional. The vlan the ip range sits on, default to Null when it is not specified which means you network is not on any Vlan. This is mainly for Vmware as other hypervisors can directly reterive bridge from pyhsical network traffic type table'}, {u'name': u'podid', u'required': True, u'related': [u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'UUID of pod where the ip range belongs to'}, {u'name': u'netmask', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask for storage network'}, {u'name': u'endip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IP address'}, {u'name': u'gateway', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway for storage network'}], u'requiredparams': [u'startip', u'podid', u'netmask', u'gateway'], u'description': u'Creates a Storage network IP range.'}, u'pool': {u'name': u'createPool', u'related': [], u'isasync': False, u'params': [{u'name': u'algorithm', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'algorithm.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}], u'requiredparams': [u'algorithm', u'name'], u'description': u'Create a pool'}, u'autoscalevmprofile': {u'name': u'createAutoScaleVmProfile', u'related': [u'updateAutoScaleVmProfile', u'listAutoScaleVmProfiles'], u'isasync': True, u'params': [{u'name': u'otherdeployparams', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'parameters other than zoneId/serviceOfferringId/templateId of the auto deployed virtual machine'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'availability zone for the auto deployed virtual machine'}, {u'name': u'serviceofferingid', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings', u'createServiceOffering', u'updateServiceOffering'], u'length': 255, u'type': u'uuid', u'description': u'the service offering of the auto deployed virtual machine'}, {u'name': u'expungevmgraceperiod', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the time allowed for existing connections to get closed before a vm is destroyed'}, {u'name': u'counterparam', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161'}, {u'name': u'templateid', u'required': True, u'related': [u'registerIso', u'updateTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the template of the auto deployed virtual machine'}, {u'name': u'autoscaleuserid', u'required': False, u'related': [u'disableUser', u'lockUser', u'listUsers', u'enableUser', u'createUser', u'updateUser'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the user used to launch and destroy the VMs'}], u'requiredparams': [u'zoneid', u'serviceofferingid', u'templateid'], u'description': u'Creates a profile that contains information about the virtual machine which will be provisioned automatically by autoscale feature.'}, u'account': {u'name': u'createAccount', u'related': [u'disableUser', u'lockUser', u'listUsers', u'enableUser', u'createUser', u'getUser', u'updateUser'], u'isasync': False, u'params': [{u'name': u'lastname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'lastname'}, {u'name': u'accounttype', u'required': True, u'related': [], u'length': 255, u'type': u'short', u'description': u'Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Unique username.'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Hashed password (Default is MD5). If you wish to use any other hashing algorithm, you would need to write a custom authentication adapter See Docs section.'}, {u'name': u'firstname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'firstname'}, {u'name': u'userid', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'User UUID, required for adding account from external provisioning system'}, {u'name': u'timezone', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Creates the user under the specified account. If no account is specified, the username will be used as the account name.'}, {u'name': u'accountdetails', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'details for account used to store specific parameters'}, {u'name': u'email', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'email'}, {u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"Network domain for the account's networks"}, {u'name': u'accountid', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Account UUID, required for adding account from external provisioning system'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'Creates the user under the specified domain.'}], u'requiredparams': [u'lastname', u'accounttype', u'username', u'password', u'firstname', u'email'], u'description': u'Creates an account'}, u'firewallrule': {u'name': u'createFirewallRule', u'related': [u'listEgressFirewallRules'], u'isasync': True, u'params': [{u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list to forward traffic from'}, {u'name': u'protocol', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the protocol for the firewall rule. Valid values are TCP/UDP/ICMP.'}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'type of firewallrule: system/user'}, {u'name': u'ipaddressid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the IP address id of the port forwarding rule'}, {u'name': u'startport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the starting port of firewall rule'}, {u'name': u'icmptype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'type of the icmp message being sent'}, {u'name': u'icmpcode', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'error code for this icmp message'}, {u'name': u'endport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the ending port of firewall rule'}], u'requiredparams': [u'protocol', u'ipaddressid'], u'description': u'Creates a firewall rule for a given ip address'}, u'networkoffering': {u'name': u'createNetworkOffering', u'related': [u'updateNetworkOffering'], u'isasync': False, u'params': [{u'name': u'serviceproviderlist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network'}, {u'name': u'serviceofferingid', u'required': False, u'related': [u'updateHypervisorCapabilities'], u'length': 255, u'type': u'uuid', u'description': u'the service offering ID used by virtual router provider'}, {u'name': u'supportedservices', u'required': True, u'related': [], u'length': 255, u'type': u'list', u'description': u'services supported by the network offering'}, {u'name': u'networkrate', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'data transfer rate in megabits per second allowed'}, {u'name': u'ispersistent', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if network offering supports persistent networks; defaulted to false if not specified'}, {u'name': u'servicecapabilitylist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'desired service capabilities as part of network offering'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the network offering'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the tags for the network offering.'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the network offering'}, {u'name': u'conservemode', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the network offering is IP conserve mode enabled'}, {u'name': u'guestiptype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'guest type of the network offering: Shared or Isolated'}, {u'name': u'traffictype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the traffic type for the network offering. Supported type in current release is GUEST only'}, {u'name': u'specifyvlan', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if network offering supports vlans'}, {u'name': u'availability', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the availability of network offering. Default value is Optional'}, {u'name': u'specifyipranges', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if network offering supports specifying ip ranges; defaulted to false if not specified'}], u'requiredparams': [u'supportedservices', u'name', u'displaytext', u'guestiptype', u'traffictype'], u'description': u'Creates a network offering.'}, u'vlaniprange': {u'name': u'createVlanIpRange', u'related': [u'listVlanIpRanges'], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'domain ID of the account owning a VLAN'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'suspendProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'project who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ID or VID of the VLAN. If not specified, will be defaulted to the vlan of the network or if vlan of the network is null - to Untagged'}, {u'name': u'networkid', u'required': False, u'related': [u'createNetwork', u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'the network id'}, {u'name': u'forvirtualnetwork', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if VLAN is of Virtual type, false if Direct'}, {u'name': u'podid', u'required': False, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'optional parameter. Have to be specified for Direct Untagged vlan only.'}, {u'name': u'ip6cidr', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the CIDR of IPv6 network, must be at least /64'}, {u'name': u'endipv6', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IPv6 address in the IPv6 network range'}, {u'name': u'startip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the beginning IP address in the VLAN IP range'}, {u'name': u'startipv6', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the beginning IPv6 address in the IPv6 network range'}, {u'name': u'gateway', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway of the VLAN IP range'}, {u'name': u'netmask', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask of the VLAN IP range'}, {u'name': u'endip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IP address in the VLAN IP range'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'account who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited'}, {u'name': u'ip6gateway', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway of the IPv6 network. Required for Shared networks and Isolated networks when it belongs to VPC'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'updatePhysicalNetwork', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the physical network id'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID of the VLAN IP range'}], u'requiredparams': [], u'description': u'Creates a VLAN IP range.'}, u'counter': {u'name': u'createCounter', u'related': [u'listCounters'], u'isasync': True, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Name of the counter.'}, {u'name': u'source', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Source of the counter.'}, {u'name': u'value', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Value of the counter e.g. oid in case of snmp.'}], u'requiredparams': [u'name', u'source', u'value'], u'description': u'Adds metric counter'}, u'lunonfiler': {u'name': u'createLunOnFiler', u'related': [], u'isasync': False, u'params': [{u'name': u'size', u'required': True, u'related': [], u'length': 255, u'type': u'long', u'description': u'LUN size.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}], u'requiredparams': [u'size', u'name'], u'description': u'Create a LUN from a pool'}, u'project': {u'name': u'createProject', u'related': [], u'isasync': True, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'account who will be Admin for the project'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the project'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'domain ID of the account owning a project'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'display text of the project'}], u'requiredparams': [u'name', u'displaytext'], u'description': u'Creates a project'}, u'physicalnetwork': {u'name': u'createPhysicalNetwork', u'related': [u'listPhysicalNetworks'], u'isasync': True, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the physical network'}, {u'name': u'zoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the physical network'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'Tag the physical network'}, {u'name': u'networkspeed', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the speed for the physical network[1G/10G]'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the VLAN for the physical network'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'domain ID of the account owning a physical network'}, {u'name': u'broadcastdomainrange', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the broadcast domain range for the physical network[Pod or Zone]. In Acton release it can be Zone only in Advance zone, and Pod in Basic'}, {u'name': u'isolationmethods', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the isolation method for the physical network[VLAN/L3/GRE]'}], u'requiredparams': [u'name', u'zoneid'], u'description': u'Creates a physical network'}, u'snapshot': {u'name': u'createSnapshot', u'related': [u'listSnapshots'], u'isasync': True, u'params': [{u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The account of the snapshot. The account parameter must be used with the domainId parameter.'}, {u'name': u'volumeid', u'required': True, u'related': [u'detachVolume'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the disk volume'}, {u'name': u'policyid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'policy id of the snapshot, if this is null, then use MANUAL_POLICY.'}], u'requiredparams': [u'volumeid'], u'description': u'Creates an instant snapshot of a volume.'}, u'virtualrouterelement': {u'name': u'createVirtualRouterElement', u'related': [], u'isasync': True, u'params': [{u'name': u'nspid', u'required': True, u'related': [u'updateNetworkServiceProvider'], u'length': 255, u'type': u'uuid', u'description': u'the network service provider ID of the virtual router element'}], u'requiredparams': [u'nspid'], u'description': u'Create a virtual router element.'}, u'egressfirewallrule': {u'name': u'createEgressFirewallRule', u'related': [u'createFirewallRule', u'listEgressFirewallRules'], u'isasync': True, u'params': [{u'name': u'networkid', u'required': True, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'the network id of the port forwarding rule'}, {u'name': u'startport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the starting port of firewall rule'}, {u'name': u'icmpcode', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'error code for this icmp message'}, {u'name': u'icmptype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'type of the icmp message being sent'}, {u'name': u'cidrlist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the cidr list to forward traffic from'}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'type of firewallrule: system/user'}, {u'name': u'protocol', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the protocol for the firewall rule. Valid values are TCP/UDP/ICMP.'}, {u'name': u'endport', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the ending port of firewall rule'}], u'requiredparams': [u'networkid', u'protocol'], u'description': u'Creates a egress firewall rule for a given network '}, u'sshkeypair': {u'name': u'createSSHKeyPair', u'related': [u'listSSHKeyPairs'], u'isasync': False, u'params': [{u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'an optional project for the ssh key'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Name of the keypair'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the ssh key. Must be used with domainId.'}], u'requiredparams': [u'name'], u'description': u'Create a new keypair and returns the private key'}}, u'deploy': {u'virtualmachine': {u'name': u'deployVirtualMachine', u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'keypair', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the ssh key pair used to login to the virtual machine'}, {u'name': u'userdata', u'required': False, u'related': [], u'length': 2048, u'type': u'string', u'description': u'an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding.'}, {u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the hypervisor on which to deploy the virtual machine'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.'}, {u'name': u'size', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId'}, {u'name': u'diskofferingid', u'required': False, u'related': [u'createDiskOffering', u'listDiskOfferings'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.'}, {u'name': u'securitygroupids', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter'}, {u'name': u'serviceofferingid', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the service offering for the virtual machine'}, {u'name': u'ipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"the ip address for default vm's network"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the virtual machine. Must be used with domainId.'}, {u'name': u'hostid', u'required': False, u'related': [u'addHost', u'updateHost', u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'destination Host ID to deploy the VM to - parameter available for root admin only'}, {u'name': u'iptonetworklist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u"ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid"}, {u'name': u'ip6address', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"the ipv6 address for default vm's network"}, {u'name': u'keyboard', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject'], u'length': 255, u'type': u'uuid', u'description': u'Deploy vm for the project'}, {u'name': u'networkids', u'required': False, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'list', u'description': u"list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter"}, {u'name': u'displayname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional user generated name for the virtual machine'}, {u'name': u'securitygroupnames', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter'}, {u'name': u'templateid', u'required': True, u'related': [u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the template for the virtual machine'}, {u'name': u'zoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'availability zone for the virtual machine'}, {u'name': u'group', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional group for the virtual machine'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'host name for the virtual machine'}, {u'name': u'startvm', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if network offering supports specifying ip ranges; defaulted to true if not specified'}], u'requiredparams': [u'serviceofferingid', u'templateid', u'zoneid'], u'description': u'Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.'}}, u'restart': {u'network': {u'name': u'restartNetwork', u'related': [u'associateIpAddress'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'The id of the network to restart.'}, {u'name': u'cleanup', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'If cleanup old network elements'}], u'requiredparams': [u'id'], u'description': u'Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules'}, u'vpc': {u'name': u'restartVPC', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': False, u'related': [u'restartVPC'], u'length': 255, u'type': u'uuid', u'description': u'the id of the VPC'}], u'requiredparams': [], u'description': u'Restarts a VPC'}}, u'reboot': {u'systemvm': {u'name': u'rebootSystemVm', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'rebootSystemVm'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the system virtual machine'}], u'requiredparams': [u'id'], u'description': u'Reboots a system VM.'}, u'router': {u'name': u'rebootRouter', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'rebootRouter'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the router'}], u'requiredparams': [u'id'], u'description': u'Starts a router.'}, u'virtualmachine': {u'name': u'rebootVirtualMachine', u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}], u'requiredparams': [u'id'], u'description': u'Reboots a virtual machine.'}}, u'mark': {u'defaultzoneforaccount': {u'name': u'markDefaultZoneForAccount', u'related': [], u'isasync': True, u'params': [{u'name': u'account', u'required': True, u'related': [u'markDefaultZoneForAccount'], u'length': 255, u'type': u'string', u'description': u'Name of the account that is to be marked.'}, {u'name': u'domainid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Marks the account that belongs to the specified domain.'}, {u'name': u'zoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'The Zone ID with which the account is to be marked.'}], u'requiredparams': [u'account', u'domainid', u'zoneid'], u'description': u'Marks a default zone for this account'}}, u'start': {u'systemvm': {u'name': u'startSystemVm', u'related': [u'rebootSystemVm', u'listSystemVms', u'changeServiceForSystemVm'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'startSystemVm', u'rebootSystemVm', u'listSystemVms', u'changeServiceForSystemVm'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the system virtual machine'}], u'requiredparams': [u'id'], u'description': u'Starts a system virtual machine.'}, u'router': {u'name': u'startRouter', u'related': [u'destroyRouter', u'rebootRouter'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'destroyRouter', u'rebootRouter', u'startRouter'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the router'}], u'requiredparams': [u'id'], u'description': u'Starts a router.'}, u'virtualmachine': {u'name': u'startVirtualMachine', u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}, {u'name': u'hostid', u'required': False, u'related': [u'addHost', u'updateHost', u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'destination Host ID to deploy the VM to - parameter available for root admin only'}], u'requiredparams': [u'id'], u'description': u'Starts a virtual machine.'}}, u'add': {u'trafficmonitor': {u'name': u'addTrafficMonitor', u'related': [u'listTrafficMonitors'], u'isasync': False, u'params': [{u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'URL of the traffic monitor Host'}, {u'name': u'includezones', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Traffic going into the listed zones will be metered'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'Zone in which to add the external firewall appliance.'}, {u'name': u'excludezones', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Traffic going into the listed zones will not be metered'}], u'requiredparams': [u'url', u'zoneid'], u'description': u'Adds Traffic Monitor Host for Direct Network Usage'}, u'secondarystorage': {u'name': u'addSecondaryStorage', u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the secondary storage'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL for the secondary storage'}], u'requiredparams': [u'url'], u'description': u'Adds secondary storage.'}, u'nictovirtualmachine': {u'name': u'addNicToVirtualMachine', u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'listLoadBalancerRuleInstances', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'networkid', u'required': True, u'related': [u'createNetwork', u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'Network ID'}, {u'name': u'ipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'IP Address for the new network'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'addNicToVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'listLoadBalancerRuleInstances', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'Virtual Machine ID'}], u'requiredparams': [u'networkid', u'virtualmachineid'], u'description': u'Adds VM to specified network by creating a NIC'}, u'netscalerloadbalancer': {u'name': u'addNetscalerLoadBalancer', u'related': [u'listNetscalerLoadBalancers', u'configureNetscalerLoadBalancer'], u'isasync': True, u'params': [{u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to reach netscaler load balancer device'}, {u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'updatePhysicalNetwork', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to reach netscaler load balancer device'}, {u'name': u'networkdevicetype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Netscaler device type supports NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'URL of the netscaler load balancer appliance.'}], u'requiredparams': [u'password', u'physicalnetworkid', u'username', u'networkdevicetype', u'url'], u'description': u'Adds a netscaler load balancer device'}, u'cluster': {u'name': u'addCluster', u'related': [u'listClusters', u'updateCluster'], u'isasync': False, u'params': [{u'name': u'url', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this cluster for allocation of new resources'}, {u'name': u'vsmpassword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the password for the VSM associated with this cluster'}, {u'name': u'podid', u'required': True, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID for the host'}, {u'name': u'vsmipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ipaddress of the VSM associated with this cluster'}, {u'name': u'hypervisor', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator'}, {u'name': u'vsmusername', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username for the VSM associated with this cluster'}, {u'name': u'username', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username for the cluster'}, {u'name': u'clustertype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'type of the cluster: CloudManaged, ExternalManaged'}, {u'name': u'clustername', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the cluster name'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the cluster'}, {u'name': u'password', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the password for the host'}], u'requiredparams': [u'podid', u'hypervisor', u'clustertype', u'clustername', u'zoneid'], u'description': u'Adds a new cluster'}, u's3': {u'name': u'addS3', u'related': [], u'isasync': False, u'params': [{u'name': u'connectiontimeout', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'connection timeout (milliseconds)'}, {u'name': u'accesskey', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'S3 access key'}, {u'name': u'bucket', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the template storage bucket'}, {u'name': u'endpoint', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'S3 host name'}, {u'name': u'secretkey', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'S3 secret key'}, {u'name': u'sockettimeout', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'socket timeout (milliseconds)'}, {u'name': u'maxerrorretry', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'maximum number of times to retry on error'}, {u'name': u'usehttps', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'connect to the S3 endpoint via HTTPS?'}], u'requiredparams': [u'accesskey', u'bucket', u'secretkey'], u'description': u'Adds S3'}, u'accounttoproject': {u'name': u'addAccountToProject', u'related': [], u'isasync': True, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the account to be added to the project'}, {u'name': u'email', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'email to which invitation to the project is going to be sent'}, {u'name': u'projectid', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'suspendProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to add the account to'}], u'requiredparams': [u'projectid'], u'description': u'Adds account to a project'}, u'region': {u'name': u'addRegion', u'related': [], u'isasync': False, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Name of the region'}, {u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Id of the Region'}, {u'name': u'endpoint', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Region service endpoint'}], u'requiredparams': [u'name', u'id', u'endpoint'], u'description': u'Adds a Region'}, u'externalloadbalancer': {u'name': u'addExternalLoadBalancer', u'related': [], u'isasync': False, u'params': [{u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Username of the external load balancer appliance.'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'URL of the external load balancer appliance.'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Password of the external load balancer appliance.'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'Zone in which to add the external load balancer appliance.'}], u'requiredparams': [u'username', u'url', u'password', u'zoneid'], u'description': u'Adds F5 external load balancer appliance.'}, u'vpnuser': {u'name': u'addVpnUser', u'related': [u'listVpnUsers'], u'isasync': True, u'params': [{u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'password for the username'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'username for the vpn user'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the vpn user. Must be used with domainId.'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject'], u'length': 255, u'type': u'uuid', u'description': u'add vpn user to the specific project'}], u'requiredparams': [u'password', u'username'], u'description': u'Adds vpn users'}, u'baremetalhost': {u'name': u'addBaremetalHost', u'related': [u'listSwifts', u'addHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'isasync': False, u'params': [{u'name': u'ipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'ip address intentionally allocated to this host after provisioning'}, {u'name': u'hosttags', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list of tags to be added to the host'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the host URL'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username for the host'}, {u'name': u'zoneid', u'required': True, u'related': [u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the host'}, {u'name': u'clustername', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the cluster name for the host'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the cluster ID for the host'}, {u'name': u'hypervisor', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'hypervisor type of the host'}, {u'name': u'podid', u'required': True, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID for the host'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the password for the host'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this Host for allocation of new resources'}], u'requiredparams': [u'url', u'username', u'zoneid', u'hypervisor', u'podid', u'password'], u'description': u'add a baremetal host'}, u'traffictype': {u'name': u'addTrafficType', u'related': [u'updateTrafficType'], u'isasync': True, u'params': [{u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The VLAN id to be used for Management traffic by VMware host'}, {u'name': u'kvmnetworklabel', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The network name label of the physical device dedicated to this traffic on a KVM host'}, {u'name': u'traffictype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the trafficType to be added to the physical network'}, {u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'vmwarenetworklabel', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The network name label of the physical device dedicated to this traffic on a VMware host'}, {u'name': u'xennetworklabel', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The network name label of the physical device dedicated to this traffic on a XenServer host'}], u'requiredparams': [u'traffictype', u'physicalnetworkid'], u'description': u'Adds traffic type to a physical network'}, u'niciranvpdevice': {u'name': u'addNiciraNvpDevice', u'related': [], u'isasync': True, u'params': [{u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'hostname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Hostname of ip address of the Nicira NVP Controller.'}, {u'name': u'l3gatewayserviceuuid', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The L3 Gateway Service UUID configured on the Nicira Controller'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to access the Nicira Controller API'}, {u'name': u'transportzoneuuid', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'The Transportzone UUID configured on the Nicira Controller'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to access the Nicira Controller API'}], u'requiredparams': [u'physicalnetworkid', u'hostname', u'username', u'transportzoneuuid', u'password'], u'description': u'Adds a Nicira NVP device'}, u'host': {u'name': u'addHost', u'related': [u'updateHost', u'listHosts'], u'isasync': False, u'params': [{u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username for the host'}, {u'name': u'podid', u'required': True, u'related': [u'updatePod'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID for the host'}, {u'name': u'clustername', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the cluster name for the host'}, {u'name': u'zoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the host'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the host URL'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the cluster ID for the host'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the password for the host'}, {u'name': u'hosttags', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list of tags to be added to the host'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this Host for allocation of new resources'}, {u'name': u'hypervisor', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'hypervisor type of the host'}], u'requiredparams': [u'username', u'podid', u'zoneid', u'url', u'password', u'hypervisor'], u'description': u'Adds a new host.'}, u'f5loadbalancer': {u'name': u'addF5LoadBalancer', u'related': [u'configureF5LoadBalancer', u'listF5LoadBalancers'], u'isasync': True, u'params': [{u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to reach F5 BigIP load balancer device'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to reach F5 BigIP load balancer device'}, {u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'updatePhysicalNetwork', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'networkdevicetype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'supports only F5BigIpLoadBalancer'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'URL of the F5 load balancer appliance.'}], u'requiredparams': [u'password', u'username', u'physicalnetworkid', u'networkdevicetype', u'url'], u'description': u'Adds a F5 BigIP load balancer device'}, u'networkdevice': {u'name': u'addNetworkDevice', u'related': [], u'isasync': False, u'params': [{u'name': u'networkdevicetype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall'}, {u'name': u'networkdeviceparameterlist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'parameters for network device'}], u'requiredparams': [], u'description': u'Adds a network device of one of the following types: ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer'}, u'bigswitchvnsdevice': {u'name': u'addBigSwitchVnsDevice', u'related': [], u'isasync': True, u'params': [{u'name': u'physicalnetworkid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'hostname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Hostname of ip address of the BigSwitch VNS Controller.'}], u'requiredparams': [u'physicalnetworkid', u'hostname'], u'description': u'Adds a BigSwitch VNS device'}, u'srxfirewall': {u'name': u'addSrxFirewall', u'related': [], u'isasync': True, u'params': [{u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to reach SRX firewall device'}, {u'name': u'networkdevicetype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'supports only JuniperSRXFirewall'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Credentials to reach SRX firewall device'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'URL of the SRX appliance.'}, {u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}], u'requiredparams': [u'password', u'networkdevicetype', u'username', u'url', u'physicalnetworkid'], u'description': u'Adds a SRX firewall device'}, u'swift': {u'name': u'addSwift', u'related': [u'listSwifts', u'addHost', u'updateHost', u'listHosts', u'listExternalLoadBalancers'], u'isasync': False, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account for swift'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL for swift'}, {u'name': u'username', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username for swift'}, {u'name': u'key', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u' key for the user for swift'}], u'requiredparams': [u'url'], u'description': u'Adds Swift.'}, u'externalfirewall': {u'name': u'addExternalFirewall', u'related': [], u'isasync': False, u'params': [{u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'URL of the external firewall appliance.'}, {u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Password of the external firewall appliance.'}, {u'name': u'zoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Zone in which to add the external firewall appliance.'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Username of the external firewall appliance.'}], u'requiredparams': [u'url', u'password', u'zoneid', u'username'], u'description': u'Adds an external firewall appliance'}, u'networkserviceprovider': {u'name': u'addNetworkServiceProvider', u'related': [u'updateNetworkServiceProvider'], u'isasync': True, u'params': [{u'name': u'destinationphysicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the destination Physical Network ID to bridge to'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name for the physical network service provider'}, {u'name': u'servicelist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the list of services to be enabled for this physical network service provider'}, {u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID to add the provider to'}], u'requiredparams': [u'name', u'physicalnetworkid'], u'description': u'Adds a network serviceProvider to a physical network'}}, u'verbs': [u'authorize', u'restore', u'suspend', u'revoke', u'disassociate', u'migrate', u'lock', u'dissociate', u'activate', u'reconnect', u'cancel', u'query', u'recover', u'extract', u'detach', u'prepare', u'start', u'create', u'associate', u'reboot', u'mark', u'attach', u'add', u'change', u'deploy', u'ldap', u'destroy', u'enable', u'configure', u'get', u'modify', u'stop', u'update', u'disable', u'resize', u'copy', u'generate', u'restart', u'reset', u'register', u'list', u'upload', u'remove', u'assign', u'delete'], u'resize': {u'volume': {u'name': u'resizeVolume', u'related': [u'detachVolume', u'uploadVolume', u'createVolume'], u'isasync': True, u'params': [{u'name': u'diskofferingid', u'required': False, u'related': [u'updateDiskOffering', u'createDiskOffering', u'listDiskOfferings'], u'length': 255, u'type': u'uuid', u'description': u'new disk offering id'}, {u'name': u'id', u'required': False, u'related': [u'detachVolume', u'resizeVolume', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}, {u'name': u'shrinkok', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Verify OK to Shrink'}, {u'name': u'size', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'New volume size in G'}], u'requiredparams': [], u'description': u'Resizes a volume'}}, u'ldap': {u'config': {u'name': u'ldapConfig', u'related': [u'ldapRemove'], u'isasync': False, u'params': [{u'name': u'hostname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Hostname or ip address of the ldap server eg: my.ldap.com'}, {u'name': u'ssl', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Check Use SSL if the external LDAP server is configured for LDAP over SSL.'}, {u'name': u'truststore', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Enter the path to trust certificates store.'}, {u'name': u'queryfilter', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'You specify a query filter here, which narrows down the users, who can be part of this domain.'}, {u'name': u'searchbase', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'The search base defines the starting point for the search in the directory tree Example: dc=cloud,dc=com.'}, {u'name': u'port', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Specify the LDAP port if required, default is 389.'}, {u'name': u'binddn', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Specify the distinguished name of a user with the search permission on the directory.'}, {u'name': u'truststorepass', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Enter the password for trust store.'}, {u'name': u'bindpass', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Enter the password.'}], u'requiredparams': [u'hostname', u'queryfilter', u'searchbase'], u'description': u'Configure the LDAP context for this site.'}, u'remove': {u'name': u'ldapRemove', u'related': [], u'isasync': False, u'params': [], u'requiredparams': [], u'description': u'Remove the LDAP context for this site.'}}, u'destroy': {u'systemvm': {u'name': u'destroySystemVm', u'related': [u'startSystemVm', u'rebootSystemVm', u'listSystemVms', u'stopSystemVm', u'changeServiceForSystemVm'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'startSystemVm', u'destroySystemVm', u'rebootSystemVm', u'listSystemVms', u'stopSystemVm', u'changeServiceForSystemVm'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the system virtual machine'}], u'requiredparams': [u'id'], u'description': u'Destroyes a system virtual machine.'}, u'router': {u'name': u'destroyRouter', u'related': [u'rebootRouter'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'destroyRouter', u'rebootRouter'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the router'}], u'requiredparams': [u'id'], u'description': u'Destroys a router.'}, u'volumeonfiler': {u'name': u'destroyVolumeOnFiler', u'related': [], u'isasync': False, u'params': [{u'name': u'volumename', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'volume name.'}, {u'name': u'ipaddress', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'ip address.'}, {u'name': u'aggregatename', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'aggregate name.'}], u'requiredparams': [u'volumename', u'ipaddress', u'aggregatename'], u'description': u'Destroy a Volume'}, u'lunonfiler': {u'name': u'destroyLunOnFiler', u'related': [], u'isasync': False, u'params': [{u'name': u'path', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'LUN path.'}], u'requiredparams': [u'path'], u'description': u'Destroy a LUN'}, u'virtualmachine': {u'name': u'destroyVirtualMachine', u'related': [u'listVirtualMachines'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listVirtualMachines', u'destroyVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}], u'requiredparams': [u'id'], u'description': u'Destroys a virtual machine. Once destroyed, only the administrator can recover it.'}}, u'get': {u'apilimit': {u'name': u'getApiLimit', u'related': [u'resetApiLimit'], u'isasync': False, u'params': [], u'requiredparams': [], u'description': u'Get API limit count for the caller'}, u'vmpassword': {u'name': u'getVMPassword', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}], u'requiredparams': [u'id'], u'description': u'Returns an encrypted password for the VM'}, u'user': {u'name': u'getUser', u'related': [u'disableUser', u'lockUser', u'listUsers', u'enableUser', u'createUser', u'updateUser'], u'isasync': False, u'params': [{u'name': u'userapikey', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'API key of the user'}], u'requiredparams': [u'userapikey'], u'description': u'Find user account by API key'}, u'cloudidentifier': {u'name': u'getCloudIdentifier', u'related': [], u'isasync': False, u'params': [{u'name': u'userid', u'required': True, u'related': [u'lockUser', u'listUsers', u'createUser'], u'length': 255, u'type': u'uuid', u'description': u'the user ID for the cloud identifier'}], u'requiredparams': [u'userid'], u'description': u'Retrieves a cloud identifier.'}}, u'count': 355, u'enable': {u'account': {u'name': u'enableAccount', u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount', u'disableAccount'], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'Enables specified account in this domain.'}, {u'name': u'id', u'required': False, u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount', u'enableAccount', u'disableAccount'], u'length': 255, u'type': u'uuid', u'description': u'Account id'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Enables specified account.'}], u'requiredparams': [], u'description': u'Enables an account'}, u'storagemaintenance': {u'name': u'enableStorageMaintenance', u'related': [u'cancelStorageMaintenance', u'updateStoragePool', u'createStoragePool', u'listStoragePools'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'cancelStorageMaintenance', u'enableStorageMaintenance', u'updateStoragePool', u'createStoragePool', u'listStoragePools'], u'length': 255, u'type': u'uuid', u'description': u'Primary storage ID'}], u'requiredparams': [u'id'], u'description': u'Puts storage pool into maintenance state'}, u'cisconexusvsm': {u'name': u'enableCiscoNexusVSM', u'related': [u'disableCiscoNexusVSM'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'disableCiscoNexusVSM', u'enableCiscoNexusVSM'], u'length': 255, u'type': u'uuid', u'description': u'Id of the Cisco Nexus 1000v VSM device to be enabled'}], u'requiredparams': [u'id'], u'description': u'Enable a Cisco Nexus VSM device'}, u'staticnat': {u'name': u'enableStaticNat', u'related': [], u'isasync': False, u'params': [{u'name': u'ipaddressid', u'required': True, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'the public IP address id for which static nat feature is being enabled'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine for enabling static nat feature'}, {u'name': u'networkid', u'required': False, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'The network of the vm the static nat will be enabled for. Required when public Ip address is not associated with any Guest network yet (VPC case)'}], u'requiredparams': [u'ipaddressid', u'virtualmachineid'], u'description': u'Enables static nat for given ip address'}, u'user': {u'name': u'enableUser', u'related': [u'lockUser', u'listUsers', u'createUser'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'lockUser', u'listUsers', u'enableUser', u'createUser'], u'length': 255, u'type': u'uuid', u'description': u'Enables user by user ID.'}], u'requiredparams': [u'id'], u'description': u'Enables a user account'}, u'autoscalevmgroup': {u'name': u'enableAutoScaleVmGroup', u'related': [u'createAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale group'}], u'requiredparams': [u'id'], u'description': u'Enables an AutoScale Vm Group'}}, u'configure': {u'srxfirewall': {u'name': u'configureSrxFirewall', u'related': [u'listSrxFirewalls', u'addSrxFirewall'], u'isasync': True, u'params': [{u'name': u'fwdeviceid', u'required': True, u'related': [u'listSrxFirewalls', u'configureSrxFirewall', u'addSrxFirewall'], u'length': 255, u'type': u'uuid', u'description': u'SRX firewall device ID'}, {u'name': u'fwdevicecapacity', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'capacity of the firewall device, Capacity will be interpreted as number of networks device can handle'}], u'requiredparams': [u'fwdeviceid'], u'description': u'Configures a SRX firewall device'}, u'f5loadbalancer': {u'name': u'configureF5LoadBalancer', u'related': [], u'isasync': True, u'params': [{u'name': u'lbdeviceid', u'required': True, u'related': [u'configureF5LoadBalancer'], u'length': 255, u'type': u'uuid', u'description': u'F5 load balancer device ID'}, {u'name': u'lbdevicecapacity', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'capacity of the device, Capacity will be interpreted as number of networks device can handle'}], u'requiredparams': [u'lbdeviceid'], u'description': u'configures a F5 load balancer device'}, u'netscalerloadbalancer': {u'name': u'configureNetscalerLoadBalancer', u'related': [u'listNetscalerLoadBalancers'], u'isasync': True, u'params': [{u'name': u'podids', u'required': False, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'list', u'description': u"Used when NetScaler device is provider of EIP service. This parameter represents the list of pod's, for which there exists a policy based route on datacenter L3 router to route pod's subnet IP to a NetScaler device."}, {u'name': u'lbdevicecapacity', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'capacity of the device, Capacity will be interpreted as number of networks device can handle'}, {u'name': u'lbdeviceid', u'required': True, u'related': [u'listNetscalerLoadBalancers', u'configureNetscalerLoadBalancer'], u'length': 255, u'type': u'uuid', u'description': u'Netscaler load balancer device ID'}, {u'name': u'inline', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if netscaler load balancer is intended to be used in in-line with firewall, false if netscaler load balancer will side-by-side with firewall'}, {u'name': u'lbdevicededicated', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this netscaler device to dedicated for a account, false if the netscaler device will be shared by multiple accounts'}], u'requiredparams': [u'lbdeviceid'], u'description': u'configures a netscaler load balancer device'}, u'virtualrouterelement': {u'name': u'configureVirtualRouterElement', u'related': [u'createVirtualRouterElement'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createVirtualRouterElement', u'configureVirtualRouterElement'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual router provider'}, {u'name': u'enabled', u'required': True, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Enabled/Disabled the service provider'}], u'requiredparams': [u'id', u'enabled'], u'description': u'Configures a virtual router element.'}}, u'associate': {u'ipaddress': {u'name': u'associateIpAddress', u'related': [], u'isasync': True, u'params': [{u'name': u'networkid', u'required': False, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'The network this ip address should be associated to.'}, {u'name': u'vpcid', u'required': False, u'related': [u'restartVPC', u'listVPCs'], u'length': 255, u'type': u'uuid', u'description': u'the VPC you want the ip address to be associated with'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account to associate with this IP address'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the availability zone you want to acquire an public IP address from'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts'], u'length': 255, u'type': u'uuid', u'description': u'Deploy vm for the project'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the domain to associate with this IP address'}], u'requiredparams': [], u'description': u'Acquires and associates a public IP to an account.'}, u'lun': {u'name': u'associateLun', u'related': [], u'isasync': False, u'params': [{u'name': u'iqn', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Guest IQN to which the LUN associate.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'LUN name.'}], u'requiredparams': [u'iqn', u'name'], u'description': u'Associate a LUN with a guest IQN'}}, u'stop': {u'systemvm': {u'name': u'stopSystemVm', u'related': [u'startSystemVm', u'rebootSystemVm', u'listSystemVms', u'changeServiceForSystemVm'], u'isasync': True, u'params': [{u'name': u'forced', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force stop the VM. The caller knows the VM is stopped.'}, {u'name': u'id', u'required': True, u'related': [u'startSystemVm', u'rebootSystemVm', u'listSystemVms', u'stopSystemVm', u'changeServiceForSystemVm'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the system virtual machine'}], u'requiredparams': [u'id'], u'description': u'Stops a system VM.'}, u'router': {u'name': u'stopRouter', u'related': [u'changeServiceForRouter', u'destroyRouter', u'rebootRouter', u'startRouter'], u'isasync': True, u'params': [{u'name': u'forced', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force stop the VM. The caller knows the VM is stopped.'}, {u'name': u'id', u'required': True, u'related': [u'changeServiceForRouter', u'stopRouter', u'destroyRouter', u'rebootRouter', u'startRouter'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the router'}], u'requiredparams': [u'id'], u'description': u'Stops a router.'}, u'virtualmachine': {u'name': u'stopVirtualMachine', u'related': [u'listVirtualMachines', u'destroyVirtualMachine'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}, {u'name': u'forced', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force stop the VM (vm is marked as Stopped even when command fails to be send to the backend). The caller knows the VM is stopped.'}], u'requiredparams': [u'id'], u'description': u'Stops a virtual machine.'}}, u'modify': {u'pool': {u'name': u'modifyPool', u'related': [], u'isasync': False, u'params': [{u'name': u'algorithm', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'algorithm.'}, {u'name': u'poolname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}], u'requiredparams': [u'algorithm', u'poolname'], u'description': u'Modify pool'}}, u'update': {u'loadbalancerrule': {u'name': u'updateLoadBalancerRule', u'related': [], u'isasync': True, u'params': [{u'name': u'description', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the description of the load balancer rule'}, {u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the id of the load balancer rule to update'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the load balancer rule'}, {u'name': u'algorithm', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'load balancer algorithm (source, roundrobin, leastconn)'}], u'requiredparams': [u'id'], u'description': u'Updates load balancer'}, u'domain': {u'name': u'updateDomain', u'related': [u'listDomainChildren', u'createDomain'], u'isasync': False, u'params': [{u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"Network domain for the domain's networks; empty string will update domainName with NULL value"}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'updates domain with this name'}, {u'name': u'id', u'required': True, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'ID of domain to update'}], u'requiredparams': [u'id'], u'description': u'Updates a domain with a new name'}, u'projectinvitation': {u'name': u'updateProjectInvitation', u'related': [], u'isasync': True, u'params': [{u'name': u'accept', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, accept the invitation, decline if false. True by default'}, {u'name': u'projectid', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to join'}, {u'name': u'token', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list invitations for specified account; this parameter has to be specified with domainId'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'account that is joining the project'}], u'requiredparams': [u'projectid'], u'description': u'Accepts or declines project invitation'}, u'diskoffering': {u'name': u'updateDiskOffering', u'related': [u'createDiskOffering', u'listDiskOfferings'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateDiskOffering', u'createDiskOffering', u'listDiskOfferings'], u'length': 255, u'type': u'uuid', u'description': u'ID of the disk offering'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'updates alternate display text of the disk offering with this value'}, {u'name': u'sortkey', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'sort key of the disk offering, integer'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'updates name of the disk offering with this value'}], u'requiredparams': [u'id'], u'description': u'Updates a disk offering.'}, u'virtualmachine': {u'name': u'updateVirtualMachine', u'related': [u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': False, u'params': [{u'name': u'displayname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'user generated name'}, {u'name': u'group', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'group of the virtual machine'}, {u'name': u'haenable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if high-availability is enabled for the virtual machine, false otherwise'}, {u'name': u'id', u'required': True, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}, {u'name': u'ostypeid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the OS type that best represents this VM.'}, {u'name': u'userdata', u'required': False, u'related': [], u'length': 2048, u'type': u'string', u'description': u'an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding.'}], u'requiredparams': [u'id'], u'description': u'Updates properties of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. Therefore, stop the VM manually before issuing this call.'}, u'portforwardingrule': {u'name': u'updatePortForwardingRule', u'related': [u'listIpForwardingRules', u'listPortForwardingRules', u'createPortForwardingRule'], u'isasync': True, u'params': [{u'name': u'privateport', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the private port of the port forwarding rule'}, {u'name': u'publicport', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the public port of the port forwarding rule'}, {u'name': u'privateip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the private IP address of the port forwarding rule'}, {u'name': u'ipaddressid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the IP address id of the port forwarding rule'}, {u'name': u'protocol', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the protocol for the port fowarding rule. Valid values are TCP or UDP.'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine for the port forwarding rule'}], u'requiredparams': [u'privateport', u'publicport', u'ipaddressid', u'protocol'], u'description': u'Updates a port forwarding rule. Only the private port and the virtual machine can be updated.'}, u'cluster': {u'name': u'updateCluster', u'related': [], u'isasync': False, u'params': [{u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'hypervisor type of the cluster'}, {u'name': u'id', u'required': True, u'related': [u'updateCluster'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the Cluster'}, {u'name': u'managedstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'whether this cluster is managed by cloudstack'}, {u'name': u'clustername', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the cluster name'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this cluster for allocation of new resources'}, {u'name': u'clustertype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'hypervisor type of the cluster'}], u'requiredparams': [u'id'], u'description': u'Updates an existing cluster'}, u'hostpassword': {u'name': u'updateHostPassword', u'related': [], u'isasync': False, u'params': [{u'name': u'password', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the new password for the host/cluster'}, {u'name': u'hostid', u'required': False, u'related': [u'listSwifts', u'addHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'the host ID'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the cluster ID'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username for the host/cluster'}], u'requiredparams': [u'password', u'username'], u'description': u'Update password of a host/pool on management server.'}, u'pod': {u'name': u'updatePod', u'related': [], u'isasync': False, u'params': [{u'name': u'endip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IP address for the Pod'}, {u'name': u'gateway', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the gateway for the Pod'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this cluster for allocation of new resources'}, {u'name': u'id', u'required': True, u'related': [u'updatePod'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the Pod'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the Pod'}, {u'name': u'startip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the starting IP address for the Pod'}, {u'name': u'netmask', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask of the Pod'}], u'requiredparams': [u'id'], u'description': u'Updates a Pod.'}, u'isopermissions': {u'name': u'updateIsoPermissions', u'related': [], u'isasync': False, u'params': [{u'name': u'isextractable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template/iso is extractable, false other wise. Can be set only by root admin'}, {u'name': u'isfeatured', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true for featured template/iso, false otherwise'}, {u'name': u'accounts', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'a comma delimited list of accounts. If specified, "op" parameter has to be passed in.'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true for public template/iso, false for private templates/isos'}, {u'name': u'projectids', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'list', u'description': u'a comma delimited list of projects. If specified, "op" parameter has to be passed in.'}, {u'name': u'op', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'permission operator (add, remove, reset)'}, {u'name': u'id', u'required': True, u'related': [u'registerIso', u'updateTemplate', u'prepareTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the template ID'}], u'requiredparams': [u'id'], u'description': u'Updates iso permissions'}, u'resourcelimit': {u'name': u'updateResourceLimit', u'related': [], u'isasync': False, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Update resource for a specified account. Must be used with the domainId parameter.'}, {u'name': u'resourcetype', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Type of resource to update. Values are 0, 1, 2, 3, and 4. 0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses a user can own. 2 - Volume. Number of disk volumes a user can create.3 - Snapshot. Number of snapshots a user can create.4 - Template. Number of templates that a user can register/create.'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Update resource limits for all accounts in specified domain. If used with the account parameter, updates resource limits for a specified account in specified domain.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Update resource limits for project'}, {u'name': u'max', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u' Maximum resource limit.'}], u'requiredparams': [u'resourcetype'], u'description': u'Updates resource limits for an account or domain.'}, u'vpcoffering': {u'name': u'updateVPCOffering', u'related': [u'listVPCOfferings', u'createVPCOffering'], u'isasync': True, u'params': [{u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the VPC offering'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'update state for the VPC offering; supported states - Enabled/Disabled'}, {u'name': u'id', u'required': False, u'related': [u'listVPCOfferings', u'createVPCOffering', u'updateVPCOffering'], u'length': 255, u'type': u'uuid', u'description': u'the id of the VPC offering'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the VPC offering'}], u'requiredparams': [], u'description': u'Updates VPC offering'}, u'network': {u'name': u'updateNetwork', u'related': [u'listNetscalerLoadBalancerNetworks'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the network'}, {u'name': u'networkofferingid', u'required': False, u'related': [u'updateNetworkOffering'], u'length': 255, u'type': u'uuid', u'description': u'network offering ID'}, {u'name': u'changecidr', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force update even if cidr type is different'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the new name for the network'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the new display text for the network'}, {u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'network domain'}], u'requiredparams': [u'id'], u'description': u'Updates a network'}, u'zone': {u'name': u'updateZone', u'related': [u'listZones', u'createZone'], u'isasync': False, u'params': [{u'name': u'internaldns1', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the first internal DNS for the Zone'}, {u'name': u'dnssearchorder', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the dns search order list'}, {u'name': u'internaldns2', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the second internal DNS for the Zone'}, {u'name': u'domain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Network domain name for the networks in the zone; empty string will update domain with NULL value'}, {u'name': u'details', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'the details for the Zone'}, {u'name': u'ip6dns1', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the first DNS for IPv6 network in the Zone'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Allocation state of this cluster for allocation of new resources'}, {u'name': u'ip6dns2', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the second DNS for IPv6 network in the Zone'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the Zone'}, {u'name': u'id', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the Zone'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'updates a private zone to public if set, but not vice-versa'}, {u'name': u'dns2', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the second DNS for the Zone'}, {u'name': u'guestcidraddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the guest CIDR address for the Zone'}, {u'name': u'dhcpprovider', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the dhcp Provider for the Zone'}, {u'name': u'dns1', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the first DNS for the Zone'}, {u'name': u'localstorageenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if local storage offering enabled, false otherwise'}], u'requiredparams': [u'id'], u'description': u'Updates a Zone.'}, u'instancegroup': {u'name': u'updateInstanceGroup', u'related': [u'createInstanceGroup'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateInstanceGroup', u'createInstanceGroup'], u'length': 255, u'type': u'uuid', u'description': u'Instance group ID'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'new instance group name'}], u'requiredparams': [u'id'], u'description': u'Updates a vm group'}, u'autoscalepolicy': {u'name': u'updateAutoScalePolicy', u'related': [], u'isasync': True, u'params': [{u'name': u'duration', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the duration for which the conditions have to be true before action is taken'}, {u'name': u'id', u'required': True, u'related': [u'updateAutoScalePolicy'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale policy'}, {u'name': u'quiettime', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the cool down period for which the policy should not be evaluated after the action has been taken'}, {u'name': u'conditionids', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the list of IDs of the conditions that are being evaluated on every interval'}], u'requiredparams': [u'id'], u'description': u'Updates an existing autoscale policy.'}, u'serviceoffering': {u'name': u'updateServiceOffering', u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings', u'createServiceOffering'], u'isasync': False, u'params': [{u'name': u'sortkey', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'sort key of the service offering, integer'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the service offering to be updated'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the service offering to be updated'}, {u'name': u'id', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings', u'createServiceOffering', u'updateServiceOffering'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the service offering to be updated'}], u'requiredparams': [u'id'], u'description': u'Updates a service offering.'}, u'storagepool': {u'name': u'updateStoragePool', u'related': [u'cancelStorageMaintenance', u'createStoragePool', u'listStoragePools'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'cancelStorageMaintenance', u'updateStoragePool', u'createStoragePool', u'listStoragePools'], u'length': 255, u'type': u'uuid', u'description': u'the Id of the storage pool'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'comma-separated list of tags for the storage pool'}], u'requiredparams': [u'id'], u'description': u'Updates a storage pool.'}, u'hypervisorcapabilities': {u'name': u'updateHypervisorCapabilities', u'related': [], u'isasync': False, u'params': [{u'name': u'securitygroupenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'set true to enable security group for this hypervisor.'}, {u'name': u'maxguestslimit', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'the max number of Guest VMs per host for this hypervisor.'}, {u'name': u'id', u'required': False, u'related': [u'listHypervisorCapabilities'], u'length': 255, u'type': u'uuid', u'description': u'ID of the hypervisor capability'}], u'requiredparams': [], u'description': u'Updates a hypervisor capabilities.'}, u'template': {u'name': u'updateTemplate', u'related': [u'registerIso', u'copyIso', u'updateIso', u'listIsos'], u'isasync': False, u'params': [{u'name': u'bootable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if image is bootable, false otherwise'}, {u'name': u'passwordenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the image supports the password reset feature; default is false'}, {u'name': u'format', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the format for the image'}, {u'name': u'ostypeid', u'required': False, u'related': [u'listOsTypes'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the OS type that best represents the OS of this image.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the image file'}, {u'name': u'id', u'required': True, u'related': [u'registerIso', u'updateTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the image file'}, {u'name': u'sortkey', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'sort key of the template, integer'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the display text of the image'}], u'requiredparams': [u'id'], u'description': u'Updates attributes of a template.'}, u'defaultnicforvirtualmachine': {u'name': u'updateDefaultNicForVirtualMachine', u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'nicid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'NIC ID'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'Virtual Machine ID'}], u'requiredparams': [u'nicid', u'virtualmachineid'], u'description': u'Changes the default NIC on a VM'}, u'traffictype': {u'name': u'updateTrafficType', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateTrafficType'], u'length': 255, u'type': u'uuid', u'description': u'traffic type id'}, {u'name': u'xennetworklabel', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The network name label of the physical device dedicated to this traffic on a XenServer host'}, {u'name': u'vmwarenetworklabel', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The network name label of the physical device dedicated to this traffic on a VMware host'}, {u'name': u'kvmnetworklabel', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The network name label of the physical device dedicated to this traffic on a KVM host'}], u'requiredparams': [u'id'], u'description': u'Updates traffic type of a physical network'}, u'host': {u'name': u'updateHost', u'related': [u'listHosts'], u'isasync': False, u'params': [{u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Change resource state of host, valid values are [Enable, Disable]. Operation may failed if host in states not allowing Enable/Disable'}, {u'name': u'oscategoryid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the id of Os category to update the host with'}, {u'name': u'hosttags', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list of tags to be added to the host'}, {u'name': u'id', u'required': True, u'related': [u'updateHost', u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the host to update'}, {u'name': u'url', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the new uri for the secondary storage: nfs://host/path'}], u'requiredparams': [u'id'], u'description': u'Updates a host.'}, u'user': {u'name': u'updateUser', u'related': [u'disableUser', u'lockUser', u'listUsers', u'enableUser', u'createUser'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'disableUser', u'lockUser', u'listUsers', u'enableUser', u'createUser', u'updateUser'], u'length': 255, u'type': u'uuid', u'description': u'User uuid'}, {u'name': u'timezone', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.'}, {u'name': u'email', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'email'}, {u'name': u'usersecretkey', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The secret key for the user. Must be specified with userApiKey'}, {u'name': u'username', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Unique username'}, {u'name': u'firstname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'first name'}, {u'name': u'lastname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'last name'}, {u'name': u'password', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Hashed password (default is MD5). If you wish to use any other hasing algorithm, you would need to write a custom authentication adapter'}, {u'name': u'userapikey', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The API key for the user. Must be specified with userSecretKey'}], u'requiredparams': [u'id'], u'description': u'Updates a user account'}, u'vpc': {u'name': u'updateVPC', u'related': [u'restartVPC', u'listVPCs'], u'isasync': True, u'params': [{u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the VPC'}, {u'name': u'id', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs'], u'length': 255, u'type': u'uuid', u'description': u'the id of the VPC'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the VPC'}], u'requiredparams': [], u'description': u'Updates a VPC'}, u'resourcecount': {u'name': u'updateResourceCount', u'related': [], u'isasync': False, u'params': [{u'name': u'resourcetype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Type of resource to update. If specifies valid values are 0, 1, 2, 3, and 4. If not specified will update all resource counts0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses a user can own. 2 - Volume. Number of disk volumes a user can create.3 - Snapshot. Number of snapshots a user can create.4 - Template. Number of templates that a user can register/create.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Update resource limits for project'}, {u'name': u'domainid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'If account parameter specified then updates resource counts for a specified account in this domain else update resource counts for all accounts & child domains in specified domain.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Update resource count for a specified account. Must be used with the domainId parameter.'}], u'requiredparams': [u'domainid'], u'description': u'Recalculate and update resource count for an account or domain.'}, u'storagenetworkiprange': {u'name': u'updateStorageNetworkIpRange', u'related': [], u'isasync': True, u'params': [{u'name': u'endip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ending IP address'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Optional. the vlan the ip range sits on'}, {u'name': u'netmask', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the netmask for storage network'}, {u'name': u'id', u'required': True, u'related': [u'updateStorageNetworkIpRange'], u'length': 255, u'type': u'uuid', u'description': u'UUID of storage network ip range'}, {u'name': u'startip', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the beginning IP address'}], u'requiredparams': [u'id'], u'description': u'Update a Storage network IP range, only allowed when no IPs in this range have been allocated.'}, u'configuration': {u'name': u'updateConfiguration', u'related': [u'listConfigurations'], u'isasync': False, u'params': [{u'name': u'value', u'required': False, u'related': [], u'length': 4095, u'type': u'string', u'description': u'the value of the configuration'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the configuration'}], u'requiredparams': [u'name'], u'description': u'Updates a configuration.'}, u'templatepermissions': {u'name': u'updateTemplatePermissions', u'related': [], u'isasync': False, u'params': [{u'name': u'isfeatured', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true for featured template/iso, false otherwise'}, {u'name': u'isextractable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template/iso is extractable, false other wise. Can be set only by root admin'}, {u'name': u'projectids', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'a comma delimited list of projects. If specified, "op" parameter has to be passed in.'}, {u'name': u'op', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'permission operator (add, remove, reset)'}, {u'name': u'id', u'required': True, u'related': [u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the template ID'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true for public template/iso, false for private templates/isos'}, {u'name': u'accounts', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'a comma delimited list of accounts. If specified, "op" parameter has to be passed in.'}], u'requiredparams': [u'id'], u'description': u'Updates a template visibility permissions. A public template is visible to all accounts within the same domain. A private template is visible only to the owner of the template. A priviledged template is a private template with account permissions added. Only accounts specified under the template permissions are visible to them.'}, u'autoscalevmprofile': {u'name': u'updateAutoScaleVmProfile', u'related': [u'listAutoScaleVmProfiles'], u'isasync': True, u'params': [{u'name': u'expungevmgraceperiod', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the time allowed for existing connections to get closed before a vm is destroyed'}, {u'name': u'autoscaleuserid', u'required': False, u'related': [u'lockUser', u'listUsers', u'enableUser', u'createUser'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the user used to launch and destroy the VMs'}, {u'name': u'templateid', u'required': False, u'related': [u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the template of the auto deployed virtual machine'}, {u'name': u'id', u'required': True, u'related': [u'updateAutoScaleVmProfile', u'listAutoScaleVmProfiles'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale vm profile'}, {u'name': u'counterparam', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161'}], u'requiredparams': [u'id'], u'description': u'Updates an existing autoscale vm profile.'}, u'account': {u'name': u'updateAccount', u'related': [u'markDefaultZoneForAccount', u'listAccounts', u'lockAccount'], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount'], u'length': 255, u'type': u'uuid', u'description': u'Account id'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the domain where the account exists'}, {u'name': u'networkdomain', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"Network domain for the account's networks; empty string will update domainName with NULL value"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the current account name'}, {u'name': u'accountdetails', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'details for account used to store specific parameters'}, {u'name': u'newname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'new name for the account'}], u'requiredparams': [u'newname'], u'description': u'Updates account information for the authenticated user'}, u'networkoffering': {u'name': u'updateNetworkOffering', u'related': [], u'isasync': False, u'params': [{u'name': u'sortkey', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'sort key of the network offering, integer'}, {u'name': u'id', u'required': False, u'related': [u'updateNetworkOffering'], u'length': 255, u'type': u'uuid', u'description': u'the id of the network offering'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the display text of the network offering'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the network offering'}, {u'name': u'availability', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the availability of network offering. Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'update state for the network offering'}], u'requiredparams': [], u'description': u'Updates a network offering.'}, u'vpncustomergateway': {u'name': u'updateVpnCustomerGateway', u'related': [u'createVpnCustomerGateway'], u'isasync': True, u'params': [{u'name': u'ikelifetime', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'Lifetime of phase 1 VPN connection to the customer gateway, in seconds'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the domain ID associated with the gateway. If used with the account parameter returns the gateway associated with the account for the specified domain.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of this customer gateway'}, {u'name': u'id', u'required': True, u'related': [u'updateVpnCustomerGateway', u'createVpnCustomerGateway'], u'length': 255, u'type': u'uuid', u'description': u'id of customer gateway'}, {u'name': u'esplifetime', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'Lifetime of phase 2 VPN connection to the customer gateway, in seconds'}, {u'name': u'ikepolicy', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'IKE policy of the customer gateway'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account associated with the gateway. Must be used with the domainId parameter.'}, {u'name': u'esppolicy', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'ESP policy of the customer gateway'}, {u'name': u'gateway', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'public ip address id of the customer gateway'}, {u'name': u'ipsecpsk', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'IPsec Preshared-Key of the customer gateway'}, {u'name': u'dpd', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'If DPD is enabled for VPN connection'}, {u'name': u'cidrlist', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'guest cidr of the customer gateway'}], u'requiredparams': [u'id', u'ikepolicy', u'esppolicy', u'gateway', u'ipsecpsk', u'cidrlist'], u'description': u'Update site to site vpn customer gateway'}, u'region': {u'name': u'updateRegion', u'related': [u'addRegion', u'listRegions'], u'isasync': False, u'params': [{u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'updates region with this name'}, {u'name': u'endpoint', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'updates region with this end point'}, {u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Id of region to update'}], u'requiredparams': [u'id'], u'description': u'Updates a region'}, u'project': {u'name': u'updateProject', u'related': [u'createProject', u'listProjectAccounts', u'activateProject'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to be modified'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'display text of the project'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'new Admin account for the project'}], u'requiredparams': [u'id'], u'description': u'Updates a project'}, u'physicalnetwork': {u'name': u'updatePhysicalNetwork', u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'isasync': True, u'params': [{u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the VLAN for the physical network'}, {u'name': u'id', u'required': True, u'related': [u'listPhysicalNetworks', u'updatePhysicalNetwork', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'physical network id'}, {u'name': u'networkspeed', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the speed for the physical network[1G/10G]'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'Tag the physical network'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Enabled/Disabled'}], u'requiredparams': [u'id'], u'description': u'Updates a physical network'}, u'iso': {u'name': u'updateIso', u'related': [u'listIsos'], u'isasync': False, u'params': [{u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the image file'}, {u'name': u'id', u'required': True, u'related': [u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the image file'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the display text of the image'}, {u'name': u'format', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the format for the image'}, {u'name': u'sortkey', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'sort key of the template, integer'}, {u'name': u'ostypeid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the OS type that best represents the OS of this image.'}, {u'name': u'passwordenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the image supports the password reset feature; default is false'}, {u'name': u'bootable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if image is bootable, false otherwise'}], u'requiredparams': [u'id'], u'description': u'Updates an ISO file.'}, u'networkserviceprovider': {u'name': u'updateNetworkServiceProvider', u'related': [], u'isasync': True, u'params': [{u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Enabled/Disabled/Shutdown the physical network service provider'}, {u'name': u'id', u'required': True, u'related': [u'updateNetworkServiceProvider'], u'length': 255, u'type': u'uuid', u'description': u'network service provider id'}, {u'name': u'servicelist', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'the list of services to be enabled for this physical network service provider'}], u'requiredparams': [u'id'], u'description': u'Updates a network serviceProvider of a physical network'}, u'autoscalevmgroup': {u'name': u'updateAutoScaleVmGroup', u'related': [], u'isasync': True, u'params': [{u'name': u'scaledownpolicyids', u'required': False, u'related': [u'updateAutoScalePolicy'], u'length': 255, u'type': u'list', u'description': u'list of scaledown autoscale policies'}, {u'name': u'interval', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the frequency at which the conditions have to be evaluated'}, {u'name': u'minmembers', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.'}, {u'name': u'maxmembers', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the maximum number of members in the vmgroup, The number of instances in the vm group will be equal to or less than this number.'}, {u'name': u'id', u'required': True, u'related': [u'updateAutoScaleVmGroup'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale group'}, {u'name': u'scaleuppolicyids', u'required': False, u'related': [u'updateAutoScalePolicy'], u'length': 255, u'type': u'list', u'description': u'list of scaleup autoscale policies'}], u'requiredparams': [u'id'], u'description': u'Updates an existing autoscale vm group.'}}, u'disable': {u'account': {u'name': u'disableAccount', u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount'], u'isasync': True, u'params': [{u'name': u'lock', u'required': True, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'If true, only lock the account; else disable the account'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Disables specified account.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'Disables specified account in this domain.'}, {u'name': u'id', u'required': False, u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount', u'disableAccount'], u'length': 255, u'type': u'uuid', u'description': u'Account id'}], u'requiredparams': [u'lock'], u'description': u'Disables an account'}, u'autoscalevmgroup': {u'name': u'disableAutoScaleVmGroup', u'related': [u'listAutoScaleVmGroups', u'createAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listAutoScaleVmGroups', u'createAutoScaleVmGroup', u'disableAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale group'}], u'requiredparams': [u'id'], u'description': u'Disables an AutoScale Vm Group'}, u'cisconexusvsm': {u'name': u'disableCiscoNexusVSM', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'disableCiscoNexusVSM'], u'length': 255, u'type': u'uuid', u'description': u'Id of the Cisco Nexus 1000v VSM device to be deleted'}], u'requiredparams': [u'id'], u'description': u'disable a Cisco Nexus VSM device'}, u'staticnat': {u'name': u'disableStaticNat', u'related': [], u'isasync': True, u'params': [{u'name': u'ipaddressid', u'required': True, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'the public IP address id for which static nat feature is being disableed'}], u'requiredparams': [u'ipaddressid'], u'description': u'Disables static rule for given ip address'}, u'user': {u'name': u'disableUser', u'related': [u'lockUser', u'listUsers', u'enableUser', u'createUser'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'disableUser', u'lockUser', u'listUsers', u'enableUser', u'createUser'], u'length': 255, u'type': u'uuid', u'description': u'Disables user by user ID.'}], u'requiredparams': [u'id'], u'description': u'Disables a user account'}}, u'detach': {u'volume': {u'name': u'detachVolume', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': False, u'related': [u'detachVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}, {u'name': u'deviceid', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'the device ID on the virtual machine where volume is detached from'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'listVirtualMachines'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine where the volume is detached from'}], u'requiredparams': [], u'description': u'Detaches a disk volume from a virtual machine.'}, u'iso': {u'name': u'detachIso', u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'virtualmachineid', u'required': True, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}], u'requiredparams': [u'virtualmachineid'], u'description': u'Detaches any ISO file (if any) currently attached to a virtual machine.'}}, u'generate': {u'usagerecords': {u'name': u'generateUsageRecords', u'related': [], u'isasync': False, u'params': [{u'name': u'enddate', u'required': True, u'related': [], u'length': 255, u'type': u'date', u'description': u'End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'List events for the specified domain.'}, {u'name': u'startdate', u'required': True, u'related': [], u'length': 255, u'type': u'date', u'description': u'Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.'}], u'requiredparams': [u'enddate', u'startdate'], u'description': u'Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed'}}, u'change': {u'serviceforvirtualmachine': {u'name': u'changeServiceForVirtualMachine', u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}, {u'name': u'serviceofferingid', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings'], u'length': 255, u'type': u'uuid', u'description': u'the service offering ID to apply to the virtual machine'}], u'requiredparams': [u'id', u'serviceofferingid'], u'description': u'Changes the service offering for a virtual machine. The virtual machine must be in a "Stopped" state for this command to take effect.'}, u'serviceforsystemvm': {u'name': u'changeServiceForSystemVm', u'related': [u'rebootSystemVm', u'listSystemVms'], u'isasync': False, u'params': [{u'name': u'serviceofferingid', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings', u'createServiceOffering'], u'length': 255, u'type': u'uuid', u'description': u'the service offering ID to apply to the system vm'}, {u'name': u'id', u'required': True, u'related': [u'rebootSystemVm', u'listSystemVms', u'changeServiceForSystemVm'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the system vm'}], u'requiredparams': [u'serviceofferingid', u'id'], u'description': u'Changes the service offering for a system vm (console proxy or secondary storage). The system vm must be in a "Stopped" state for this command to take effect.'}, u'serviceforrouter': {u'name': u'changeServiceForRouter', u'related': [u'destroyRouter', u'rebootRouter', u'startRouter'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'changeServiceForRouter', u'destroyRouter', u'rebootRouter', u'startRouter'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the router'}, {u'name': u'serviceofferingid', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings', u'createServiceOffering', u'updateServiceOffering'], u'length': 255, u'type': u'uuid', u'description': u'the service offering ID to apply to the domain router'}], u'requiredparams': [u'id', u'serviceofferingid'], u'description': u'Upgrades domain router to a new service offering'}}, u'reset': {u'apilimit': {u'name': u'resetApiLimit', u'related': [], u'isasync': False, u'params': [{u'name': u'account', u'required': False, u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the acount whose limit to be reset'}], u'requiredparams': [], u'description': u'Reset api count'}, u'sshkeyforvirtualmachine': {u'name': u'resetSSHKeyForVirtualMachine', u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'an optional project for the ssh key'}, {u'name': u'keypair', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the ssh key pair used to login to the virtual machine'}, {u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the ssh key. Must be used with domainId.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.'}], u'requiredparams': [u'keypair', u'id'], u'description': u'Resets the SSH Key for virtual machine. The virtual machine must be in a "Stopped" state. [async]'}, u'passwordforvirtualmachine': {u'name': u'resetPasswordForVirtualMachine', u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the virtual machine'}], u'requiredparams': [u'id'], u'description': u'Resets the password for virtual machine. The virtual machine must be in a "Stopped" state and the template must already support this feature for this command to take effect. [async]'}, u'vpnconnection': {u'name': u'resetVpnConnection', u'related': [u'listVpnConnections'], u'isasync': True, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for connection. Must be used with domainId.'}, {u'name': u'id', u'required': True, u'related': [u'listVpnConnections', u'resetVpnConnection'], u'length': 255, u'type': u'uuid', u'description': u'id of vpn connection'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for connection. If the account parameter is used, domainId must also be used.'}], u'requiredparams': [u'id'], u'description': u'Reset site to site vpn connection'}}, u'register': {u'userkeys': {u'name': u'registerUserKeys', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'lockUser', u'listUsers', u'enableUser', u'createUser'], u'length': 255, u'type': u'uuid', u'description': u'User id'}], u'requiredparams': [u'id'], u'description': u'This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user'}, u'iso': {u'name': u'registerIso', u'related': [u'copyIso', u'updateIso', u'listIsos'], u'isasync': False, u'params': [{u'name': u'ostypeid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the OS Type that best represents the OS of this ISO. If the iso is bootable this parameter needs to be passed'}, {u'name': u'checksum', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the MD5 checksum value of this ISO'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the ISO'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId. If the account parameter is used, domainId must also be used.'}, {u'name': u'bootable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this ISO is bootable. If not passed explicitly its assumed to be true'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts'], u'length': 255, u'type': u'uuid', u'description': u'Register iso for the project'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if you want to register the ISO to be publicly available to all users, false otherwise.'}, {u'name': u'zoneid', u'required': True, u'related': [u'listZones'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone you wish to register the ISO to.'}, {u'name': u'isextractable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the iso or its derivatives are extractable; default is false'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the display text of the ISO. This is usually used for display purposes.'}, {u'name': u'isfeatured', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if you want this ISO to be featured'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL to where the ISO is currently being hosted'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account name. Must be used with domainId.'}], u'requiredparams': [u'name', u'zoneid', u'displaytext', u'url'], u'description': u'Registers an existing ISO into the CloudStack Cloud.'}, u'sshkeypair': {u'name': u'registerSSHKeyPair', u'related': [u'createSSHKeyPair', u'listSSHKeyPairs'], u'isasync': False, u'params': [{u'name': u'publickey', u'required': True, u'related': [], u'length': 5120, u'type': u'string', u'description': u'Public key material of the keypair'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Name of the keypair'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'an optional project for the ssh key'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the ssh key. Must be used with domainId.'}], u'requiredparams': [u'publickey', u'name'], u'description': u'Register a public key in a keypair under a certain name'}, u'template': {u'name': u'registerTemplate', u'related': [u'listTemplates', u'registerIso', u'updateTemplate', u'prepareTemplate', u'copyIso', u'updateIso', u'listIsos'], u'isasync': False, u'params': [{u'name': u'isextractable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template or its derivatives are extractable; default is false'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone the template is to be hosted on'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId. If the account parameter is used, domainId must also be used.'}, {u'name': u'checksum', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the MD5 checksum value of this template'}, {u'name': u'templatetag', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the tag for this template.'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template is available to all accounts; default is true'}, {u'name': u'passwordenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template supports the password reset feature; default is false'}, {u'name': u'displaytext', u'required': True, u'related': [], u'length': 4096, u'type': u'string', u'description': u'the display text of the template. This is usually used for display purposes.'}, {u'name': u'sshkeyenabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the template supports the sshkey upload feature; default is false'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'Register template for the project'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the template'}, {u'name': u'isfeatured', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this template is a featured template, false otherwise'}, {u'name': u'format', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the format for the template. Possible values include QCOW2, RAW, and VHD.'}, {u'name': u'requireshvm', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this template requires HVM'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional accountName. Must be used with domainId.'}, {u'name': u'ostypeid', u'required': True, u'related': [u'listOsTypes'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the OS Type that best represents the OS of this template.'}, {u'name': u'hypervisor', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the target hypervisor for the template'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL of where the template is hosted. Possible URL include http:// and https://'}, {u'name': u'bits', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'32 or 64 bits support. 64 by default'}, {u'name': u'details', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'Template details in key/value pairs.'}], u'requiredparams': [u'zoneid', u'displaytext', u'name', u'format', u'ostypeid', u'hypervisor', u'url'], u'description': u'Registers an existing template into the CloudStack cloud. '}}, u'list': {u'instancegroups': {u'name': u'listInstanceGroups', u'related': [u'updateInstanceGroup', u'createInstanceGroup'], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listInstanceGroups', u'updateInstanceGroup', u'createInstanceGroup'], u'length': 255, u'type': u'uuid', u'description': u'list instance groups by ID'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list instance groups by name'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}], u'requiredparams': [], u'description': u'Lists vm groups'}, u'physicalnetworks': {u'name': u'listPhysicalNetworks', u'related': [], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the physical network'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listPhysicalNetworks'], u'length': 255, u'type': u'uuid', u'description': u'list physical network by id'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'search by name'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists physical networks'}, u'networks': {u'name': u'listNetworks', u'related': [u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks'], u'isasync': False, u'params': [{u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'issystem', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if network is system, false otherwise'}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'List networks by VPC'}, {u'name': u'acltype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list networks by ACL (access control list) type. Supported values are Account and Domain'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'specifyipranges', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if need to list only networks which support specifying ip ranges'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID of the network'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'restartrequired', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list networks by restartRequired'}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the type of the network. Supported values are: Isolated and Shared'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'list networks by physical network id'}, {u'name': u'supportedservices', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list networks supporting certain services'}, {u'name': u'traffictype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'type of the traffic'}, {u'name': u'id', u'required': False, u'related': [u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'list networks by id'}, {u'name': u'canusefordeploy', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list networks available for vm deployment'}, {u'name': u'forvpc', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'the network belongs to vpc'}], u'requiredparams': [], u'description': u'Lists all available networks.'}, u'capabilities': {u'name': u'listCapabilities', u'related': [], u'isasync': False, u'params': [], u'requiredparams': [], u'description': u'Lists capabilities'}, u'clusters': {u'name': u'listClusters', u'related': [u'updateCluster'], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'listClusters', u'updateCluster'], u'length': 255, u'type': u'uuid', u'description': u'lists clusters by the cluster ID'}, {u'name': u'managedstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'whether this cluster is managed by cloudstack'}, {u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists clusters by hypervisor type'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists clusters by allocation state'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'lists clusters by Zone ID'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists clusters by the cluster name'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'clustertype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists clusters by cluster type'}, {u'name': u'showcapacities', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'flag to display the capacity of the clusters'}, {u'name': u'podid', u'required': False, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'lists clusters by Pod ID'}], u'requiredparams': [], u'description': u'Lists clusters.'}, u'resourcelimits': {u'name': u'listResourceLimits', u'related': [u'updateResourceLimit'], u'isasync': False, u'params': [{u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'resourcetype', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'Type of resource to update. Values are 0, 1, 2, 3, and 4. 0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses a user can own. 2 - Volume. Number of disk volumes a user can create.3 - Snapshot. Number of snapshots a user can create.4 - Template. Number of templates that a user can register/create.'}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'Lists resource limits by ID.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}], u'requiredparams': [], u'description': u'Lists resource limits.'}, u'firewallrules': {u'name': u'listFirewallRules', u'related': [u'createEgressFirewallRule', u'createFirewallRule', u'listEgressFirewallRules'], u'isasync': False, u'params': [{u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'id', u'required': False, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'Lists rule with the specified ID.'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'ipaddressid', u'required': False, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'the id of IP address of the firwall services'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}], u'requiredparams': [], u'description': u'Lists all firewall rules for an IP address.'}, u'supportednetworkservices': {u'name': u'listSupportedNetworkServices', u'related': [], u'isasync': False, u'params': [{u'name': u'service', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'network service name to list providers and capabilities of'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'provider', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'network service provider name'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists all network services provided by CloudStack or for the given Provider.'}, u'loadbalancerrules': {u'name': u'listLoadBalancerRules', u'related': [u'createLoadBalancerRule', u'updateLoadBalancerRule'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the availability zone ID'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine of the load balancer rule'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'id', u'required': False, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'publicipid', u'required': False, u'related': [u'restartNetwork', u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'the public IP address id of the load balancer rule '}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the load balancer rule'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}], u'requiredparams': [], u'description': u'Lists load balancer rules.'}, u'autoscalepolicies': {u'name': u'listAutoScalePolicies', u'related': [u'createAutoScalePolicy', u'updateAutoScalePolicy'], u'isasync': False, u'params': [{u'name': u'action', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the action to be executed if all the conditions evaluate to true for the specified duration.'}, {u'name': u'id', u'required': False, u'related': [u'createAutoScalePolicy', u'updateAutoScalePolicy', u'listAutoScalePolicies'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale policy'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'vmgroupid', u'required': False, u'related': [u'createAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale vm group'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'conditionid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the condition of the policy'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists autoscale policies.'}, u'niciranvpdevices': {u'name': u'listNiciraNvpDevices', u'related': [u'addNiciraNvpDevice'], u'isasync': False, u'params': [{u'name': u'nvpdeviceid', u'required': False, u'related': [u'addNiciraNvpDevice', u'listNiciraNvpDevices'], u'length': 255, u'type': u'uuid', u'description': u'nicira nvp device ID'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists Nicira NVP devices'}, u'f5loadbalancernetworks': {u'name': u'listF5LoadBalancerNetworks', u'related': [u'createNetwork', u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'lbdeviceid', u'required': True, u'related': [u'configureF5LoadBalancer', u'addF5LoadBalancer', u'listF5LoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'f5 load balancer device ID'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [u'lbdeviceid'], u'description': u'lists network that are using a F5 load balancer device'}, u'templatepermissions': {u'name': u'listTemplatePermissions', u'related': [u'listIsoPermissions'], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'listIsoPermissions', u'listTemplatePermissions'], u'length': 255, u'type': u'uuid', u'description': u'the template ID'}], u'requiredparams': [u'id'], u'description': u'List template visibility and all accounts that have permissions to view this template.'}, u'projects': {u'name': u'listProjects', u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List projects by tags (key/value pairs)'}, {u'name': u'id', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list projects by project ID'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list projects by name'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list projects by state'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list projects by display text'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}], u'requiredparams': [], u'description': u'Lists projects and provides detailed information for listed projects'}, u'systemvms': {u'name': u'listSystemVms', u'related': [u'rebootSystemVm'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID of the system VM'}, {u'name': u'hostid', u'required': False, u'related': [u'addHost', u'updateHost', u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'the host ID of the system VM'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the state of the system VM'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'storageid', u'required': False, u'related': [u'cancelStorageMaintenance'], u'length': 255, u'type': u'uuid', u'description': u"the storage ID where vm's volumes belong to"}, {u'name': u'systemvmtype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the system VM type. Possible types are "consoleproxy" and "secondarystoragevm".'}, {u'name': u'podid', u'required': False, u'related': [u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID of the system VM'}, {u'name': u'id', u'required': False, u'related': [u'rebootSystemVm', u'listSystemVms'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the system VM'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the system VM'}], u'requiredparams': [], u'description': u'List system virtual machines.'}, u'portforwardingrules': {u'name': u'listPortForwardingRules', u'related': [u'listIpForwardingRules', u'createPortForwardingRule'], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'id', u'required': False, u'related': [u'listIpForwardingRules', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'Lists rule with the specified ID.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'ipaddressid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the id of IP address of the port forwarding services'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}], u'requiredparams': [], u'description': u'Lists all port forwarding rules for an IP address.'}, u'hypervisors': {u'name': u'listHypervisors', u'related': [], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the zone id for listing hypervisors.'}], u'requiredparams': [], u'description': u'List hypervisors'}, u'publicipaddresses': {u'name': u'listPublicIpAddresses', u'related': [u'restartNetwork', u'associateIpAddress'], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'lists all public IP addresses by Zone ID'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'allocatedonly', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'limits search results to allocated public IP addresses'}, {u'name': u'id', u'required': False, u'related': [u'restartNetwork', u'listPublicIpAddresses', u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'lists ip address by id'}, {u'name': u'forloadbalancing', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list only ips used for load balancing'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'isstaticnat', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list only static nat ip addresses'}, {u'name': u'issourcenat', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list only source nat ip addresses'}, {u'name': u'vlanid', u'required': False, u'related': [u'listVlanIpRanges'], u'length': 255, u'type': u'uuid', u'description': u'lists all public IP addresses by VLAN ID'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'ipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists the specified IP address'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'lists all public IP addresses by physical network id'}, {u'name': u'associatednetworkid', u'required': False, u'related': [u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'lists all public IP addresses associated to the network specified'}, {u'name': u'forvirtualnetwork', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'the virtual network for the IP address'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'List ips belonging to the VPC'}], u'requiredparams': [], u'description': u'Lists all public ip addresses'}, u'vpngateways': {u'name': u'listVpnGateways', u'related': [u'createVpnGateway'], u'isasync': False, u'params': [{u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'id', u'required': False, u'related': [u'createVpnGateway', u'listVpnGateways'], u'length': 255, u'type': u'uuid', u'description': u'id of the vpn gateway'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'id of vpc'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}], u'requiredparams': [], u'description': u'Lists site 2 site vpn gateways'}, u'loadbalancerruleinstances': {u'name': u'listLoadBalancerRuleInstances', u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'applied', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if listing all virtual machines currently applied to the load balancer rule; default is true'}, {u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}], u'requiredparams': [u'id'], u'description': u'List all virtual machine instances that are assigned to a load balancer rule.'}, u'hosts': {u'name': u'listHosts', u'related': [], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'podid', u'required': False, u'related': [u'updatePod'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID for the host'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the state of the host'}, {u'name': u'resourcestate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list hosts by resource state. Resource state represents current state determined by admin of host, valule can be one of [Enabled, Disabled, Unmanaged, PrepareForMaintenance, ErrorInMaintenance, Maintenance, Error]'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the host'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the host'}, {u'name': u'virtualmachineid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'lists hosts existing in particular cluster'}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the host type'}, {u'name': u'id', u'required': False, u'related': [u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'the id of the host'}, {u'name': u'details', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'comma separated list of host details requested, value can be a list of [ min, all, capacity, events, stats]'}, {u'name': u'hahost', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, list only hosts dedicated to HA'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists hosts.'}, u'pools': {u'name': u'listPools', u'related': [], u'isasync': False, u'params': [], u'requiredparams': [], u'description': u'List Pool'}, u'counters': {u'name': u'listCounters', u'related': [], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'source', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Source of the counter.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'id', u'required': False, u'related': [u'listCounters'], u'length': 255, u'type': u'uuid', u'description': u'ID of the Counter.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Name of the counter.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'List the counters'}, u'configurations': {u'name': u'listConfigurations', u'related': [], u'isasync': False, u'params': [{u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists configuration by name'}, {u'name': u'category', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists configurations by category'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists all configurations.'}, u'usagerecords': {u'name': u'listUsageRecords', u'related': [], u'isasync': False, u'params': [{u'name': u'enddate', u'required': True, u'related': [], u'length': 255, u'type': u'date', u'description': u'End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.'}, {u'name': u'startdate', u'required': True, u'related': [], u'length': 255, u'type': u'date', u'description': u'Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'List usage records for the specified usage type'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject'], u'length': 255, u'type': u'uuid', u'description': u'List usage records for specified project'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List usage records for the specified user.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'List usage records for the specified domain.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'accountid', u'required': False, u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount'], u'length': 255, u'type': u'uuid', u'description': u'List usage records for the specified account'}], u'requiredparams': [u'enddate', u'startdate'], u'description': u'Lists usage records for accounts'}, u'storagepools': {u'name': u'listStoragePools', u'related': [u'cancelStorageMaintenance'], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID for the storage pool'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'path', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the storage pool path'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list storage pools belongig to the specific cluster'}, {u'name': u'id', u'required': False, u'related': [u'cancelStorageMaintenance', u'listStoragePools'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the storage pool'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'ipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the IP address for the storage pool'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the storage pool'}, {u'name': u'podid', u'required': False, u'related': [u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID for the storage pool'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists storage pools.'}, u'vpncustomergateways': {u'name': u'listVpnCustomerGateways', u'related': [u'updateVpnCustomerGateway', u'createVpnCustomerGateway'], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'updateVpnCustomerGateway', u'createVpnCustomerGateway', u'listVpnCustomerGateways'], u'length': 255, u'type': u'uuid', u'description': u'id of the customer gateway'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}], u'requiredparams': [], u'description': u'Lists site to site vpn customer gateways'}, u'zones': {u'name': u'listZones', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'listZones'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone'}, {u'name': u'available', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the zone'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the domain associated with the zone'}, {u'name': u'showcapacities', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'flag to display the capacity of the zones'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists zones'}, u'serviceofferings': {u'name': u'listServiceOfferings', u'related': [u'updateHypervisorCapabilities'], u'isasync': False, u'params': [{u'name': u'systemvmtype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the system VM type. Possible types are "consoleproxy", "secondarystoragevm" or "domainrouter".'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the domain associated with the service offering'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the service offering'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'issystem', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'is this a system vm offering'}, {u'name': u'id', u'required': False, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings'], u'length': 255, u'type': u'uuid', u'description': u'ID of the service offering'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists all available service offerings.'}, u'externalfirewalls': {u'name': u'listExternalFirewalls', u'related': [u'addExternalFirewall'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'zoneid', u'required': True, u'related': [u'listZones'], u'length': 255, u'type': u'uuid', u'description': u'zone Id'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [u'zoneid'], u'description': u'List external firewall appliances.'}, u'networkserviceproviders': {u'name': u'listNetworkServiceProviders', u'related': [u'addNetworkServiceProvider', u'listTrafficTypes', u'updateNetworkServiceProvider'], u'isasync': False, u'params': [{u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list providers by state'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list providers by name'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'updatePhysicalNetwork', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists network serviceproviders for a given physical network.'}, u'capacity': {u'name': u'listCapacity', u'related': [], u'isasync': False, u'params': [{u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'lists capacity by type* CAPACITY_TYPE_MEMORY = 0* CAPACITY_TYPE_CPU = 1* CAPACITY_TYPE_STORAGE = 2* CAPACITY_TYPE_STORAGE_ALLOCATED = 3* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4* CAPACITY_TYPE_PRIVATE_IP = 5* CAPACITY_TYPE_SECONDARY_STORAGE = 6* CAPACITY_TYPE_VLAN = 7* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8* CAPACITY_TYPE_LOCAL_STORAGE = 9.'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'lists capacity by the Cluster ID'}, {u'name': u'sortby', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Sort the results. Available values: Usage'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'fetchlatest', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'recalculate capacities and fetch the latest'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'lists capacity by the Zone ID'}, {u'name': u'podid', u'required': False, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'lists capacity by the Pod ID'}], u'requiredparams': [], u'description': u'Lists all the system wide capacities.'}, u'diskofferings': {u'name': u'listDiskOfferings', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'listDiskOfferings'], u'length': 255, u'type': u'uuid', u'description': u'ID of the disk offering'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the disk offering'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the domain of the disk offering.'}], u'requiredparams': [], u'description': u'Lists all available disk offerings.'}, u'lbstickinesspolicies': {u'name': u'listLBStickinessPolicies', u'related': [u'createLBStickinessPolicy'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'lbruleid', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [u'lbruleid'], u'description': u'Lists LBStickiness policies.'}, u'srxfirewallnetworks': {u'name': u'listSrxFirewallNetworks', u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'isasync': False, u'params': [{u'name': u'lbdeviceid', u'required': True, u'related': [u'addSrxFirewall'], u'length': 255, u'type': u'uuid', u'description': u'netscaler load balancer device ID'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [u'lbdeviceid'], u'description': u'lists network that are using SRX firewall device'}, u'securitygroups': {u'name': u'listSecurityGroups', u'related': [], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'id', u'required': False, u'related': [u'listSecurityGroups'], u'length': 255, u'type': u'uuid', u'description': u'list the security group by the id provided'}, {u'name': u'securitygroupname', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists security groups by name'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'lists security groups by virtual machine id'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists security groups'}, u'conditions': {u'name': u'listConditions', u'related': [u'listCounters', u'createCounter'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'ID of the Condition.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'counterid', u'required': False, u'related': [u'listConditions', u'listCounters', u'createCounter'], u'length': 255, u'type': u'uuid', u'description': u'Counter-id of the condition.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'policyid', u'required': False, u'related': [u'createAutoScalePolicy', u'updateAutoScalePolicy'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the policy'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}], u'requiredparams': [], u'description': u'List Conditions for the specific user'}, u'swifts': {u'name': u'listSwifts', u'related': [u'addHost', u'updateHost', u'listHosts', u'listExternalLoadBalancers'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'the id of the swift'}], u'requiredparams': [], u'description': u'List Swift.'}, u'hypervisorcapabilities': {u'name': u'listHypervisorCapabilities', u'related': [], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listHypervisorCapabilities'], u'length': 255, u'type': u'uuid', u'description': u'ID of the hypervisor capability'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the hypervisor for which to restrict the search'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists all hypervisor capabilities.'}, u'tags': {u'name': u'listTags', u'related': [], u'isasync': False, u'params': [{u'name': u'resourceid', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by resource id'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'resourcetype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by resource type'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'key', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by key'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'customer', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by customer name'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'value', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by value'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'List resource tag(s)'}, u'routers': {u'name': u'listRouters', u'related': [u'changeServiceForRouter', u'stopRouter', u'destroyRouter', u'rebootRouter', u'startRouter'], u'isasync': False, u'params': [{u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the state of the router'}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'List networks by VPC'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'podid', u'required': False, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID of the router'}, {u'name': u'hostid', u'required': False, u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addSecondaryStorage', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers', u'prepareHostForMaintenance'], u'length': 255, u'type': u'uuid', u'description': u'the host ID of the router'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the router'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID of the router'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'id', u'required': False, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'addNicToVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'listLoadBalancerRuleInstances', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk router'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'suspendProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'networkid', u'required': False, u'related': [u'createNetwork', u'listNiciraNvpDeviceNetworks', u'updateNetwork', u'listF5LoadBalancerNetworks', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'list by network id'}, {u'name': u'forvpc', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true is passed for this parameter, list only VPC routers'}], u'requiredparams': [], u'description': u'List routers.'}, u'traffictypes': {u'name': u'listTrafficTypes', u'related': [u'addNetworkServiceProvider', u'updateNetworkServiceProvider'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'physicalnetworkid', u'required': True, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [u'physicalnetworkid'], u'description': u'Lists traffic types of a given physical network.'}, u'projectinvitations': {u'name': u'listProjectInvitations', u'related': [], u'isasync': False, u'params': [{u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'activeonly', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'if true, list only active invitations - having Pending state and ones that are not timed out yet'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list by project id'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list invitations by state'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'id', u'required': False, u'related': [u'listProjectInvitations'], u'length': 255, u'type': u'uuid', u'description': u'list invitations by id'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}], u'requiredparams': [], u'description': u'Lists projects and provides detailed information for listed projects'}, u'isos': {u'name': u'listIsos', u'related': [], u'isasync': False, u'params': [{u'name': u'bootable', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the ISO is bootable, false otherwise'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list all isos by name'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'id', u'required': False, u'related': [u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'list ISO by id'}, {u'name': u'ispublic', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if the ISO is publicly available to all users, false otherwise.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isofilter', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'possible values are "featured", "self", "selfexecutable","sharedexecutable","executable", and "community". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured. * all : all templates (only usable by admins).'}, {u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the hypervisor for which to restrict the search'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'isready', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if this ISO is ready to be deployed'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists all available ISO files.'}, u'users': {u'name': u'listUsers', u'related': [], u'isasync': False, u'params': [{u'name': u'username', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List user by the username'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'accounttype', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'List users by account type. Valid types include admin, domain-admin, read-only-admin, or user.'}, {u'name': u'id', u'required': False, u'related': [u'listUsers'], u'length': 255, u'type': u'uuid', u'description': u'List user by ID.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List users by state of the user account.'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists user accounts'}, u'sshkeypairs': {u'name': u'listSSHKeyPairs', u'related': [], u'isasync': False, u'params': [{u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'fingerprint', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'A public key fingerprint to look for'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'A key pair name to look for'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}], u'requiredparams': [], u'description': u'List registered keypairs'}, u'privategateways': {u'name': u'listPrivateGateways', u'related': [u'createPrivateGateway'], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'createPrivateGateway', u'listPrivateGateways'], u'length': 255, u'type': u'uuid', u'description': u'list private gateway by id'}, {u'name': u'ipaddress', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list gateways by ip address'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'list gateways by vpc'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list gateways by state'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list gateways by vlan'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}], u'requiredparams': [], u'description': u'List private gateways'}, u'usagetypes': {u'name': u'listUsageTypes', u'related': [], u'isasync': False, u'params': [], u'requiredparams': [], u'description': u'List Usage Types'}, u'domainchildren': {u'name': u'listDomainChildren', u'related': [u'createDomain'], u'isasync': False, u'params': [{u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list children domains by name'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list children domain by parent domain ID.'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'to return the entire tree, use the value "true". To return the first level children, use the value "false".'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists all children domains belonging to a specified domain'}, u'domains': {u'name': u'listDomains', u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'List domain by domain ID.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List domain by domain name.'}, {u'name': u'level', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'List domains by domain level.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}], u'requiredparams': [], u'description': u'Lists domains and provides detailed information for listed domains'}, u'externalloadbalancers': {u'name': u'listExternalLoadBalancers', u'related': [u'addHost', u'updateHost', u'listHosts'], u'isasync': False, u'params': [{u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'zone Id'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists F5 external load balancer appliances added in a zone.'}, u'netscalerloadbalancers': {u'name': u'listNetscalerLoadBalancers', u'related': [], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'lbdeviceid', u'required': False, u'related': [u'listNetscalerLoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'netscaler load balancer device ID'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'lists netscaler load balancer devices'}, u's3s': {u'name': u'listS3s', u'related': [u'addS3'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists S3s'}, u'bigswitchvnsdevices': {u'name': u'listBigSwitchVnsDevices', u'related': [u'addBigSwitchVnsDevice'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'vnsdeviceid', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'bigswitch vns device ID'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}], u'requiredparams': [], u'description': u'Lists BigSwitch Vns devices'}, u'accounts': {u'name': u'listAccounts', u'related': [u'markDefaultZoneForAccount', u'lockAccount'], u'isasync': False, u'params': [{u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list accounts by state. Valid states are enabled, disabled, and locked.'}, {u'name': u'iscleanuprequired', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list accounts by cleanuprequred attribute (values are true or false)'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'accounttype', u'required': False, u'related': [], u'length': 255, u'type': u'long', u'description': u'list accounts by account type. Valid account types are 1 (admin), 2 (domain-admin), and 0 (user).'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'id', u'required': False, u'related': [u'markDefaultZoneForAccount', u'listAccounts', u'lockAccount'], u'length': 255, u'type': u'uuid', u'description': u'list account by account ID'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list account by account name'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}], u'requiredparams': [], u'description': u'Lists accounts and provides detailed account information for listed accounts'}, u'networkdevice': {u'name': u'listNetworkDevice', u'related': [u'addNetworkDevice'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'networkdevicetype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall'}, {u'name': u'networkdeviceparameterlist', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'parameters for network device'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'List network devices'}, u'vlanipranges': {u'name': u'listVlanIpRanges', u'related': [], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'networkid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'network id of the VLAN IP range'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the domain ID with which the VLAN IP range is associated. If used with the account parameter, returns all VLAN IP ranges for that account in the specified domain.'}, {u'name': u'id', u'required': False, u'related': [u'listVlanIpRanges'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the VLAN IP range'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks'], u'length': 255, u'type': u'uuid', u'description': u'physical network id of the VLAN IP range'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'project who will own the VLAN'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account with which the VLAN IP range is associated. Must be used with the domainId parameter.'}, {u'name': u'vlan', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the ID or VID of the VLAN. Default is an "untagged" VLAN.'}, {u'name': u'podid', u'required': False, u'related': [u'updatePod'], u'length': 255, u'type': u'uuid', u'description': u'the Pod ID of the VLAN IP range'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Zone ID of the VLAN IP range'}, {u'name': u'forvirtualnetwork', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if VLAN is of Virtual type, false if Direct'}], u'requiredparams': [], u'description': u'Lists all VLAN IP ranges.'}, u'traffictypeimplementors': {u'name': u'listTrafficTypeImplementors', u'related': [], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'traffictype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'Optional. The network traffic type, if specified, return its implementor. Otherwise, return all traffic types with their implementor'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists implementors of implementor of a network traffic type or implementors of all network traffic types'}, u'storagenetworkiprange': {u'name': u'listStorageNetworkIpRange', u'related': [u'updateStorageNetworkIpRange'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'optional parameter. Zone uuid, if specicied and both pod uuid and range uuid are absent, using it to search the range.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'id', u'required': False, u'related': [u'listStorageNetworkIpRange', u'updateStorageNetworkIpRange'], u'length': 255, u'type': u'uuid', u'description': u'optional parameter. Storaget network IP range uuid, if specicied, using it to search the range.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'podid', u'required': False, u'related': [u'updatePod'], u'length': 255, u'type': u'uuid', u'description': u'optional parameter. Pod uuid, if specicied and range uuid is absent, using it to search the range.'}], u'requiredparams': [], u'description': u'List a storage network IP range.'}, u'isopermissions': {u'name': u'listIsoPermissions', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'listIsoPermissions'], u'length': 255, u'type': u'uuid', u'description': u'the template ID'}], u'requiredparams': [u'id'], u'description': u'List iso visibility and all accounts that have permissions to view this iso.'}, u'snapshotpolicies': {u'name': u'listSnapshotPolicies', u'related': [], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'volumeid', u'required': True, u'related': [u'detachVolume', u'uploadVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [u'volumeid'], u'description': u'Lists snapshot policies.'}, u'autoscalevmgroups': {u'name': u'listAutoScaleVmGroups', u'related': [u'createAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'isasync': False, u'params': [{u'name': u'policyid', u'required': False, u'related': [u'createAutoScalePolicy', u'updateAutoScalePolicy', u'listAutoScalePolicies'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the policy'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'vmprofileid', u'required': False, u'related': [u'updateAutoScaleVmProfile', u'createAutoScaleVmProfile', u'listAutoScaleVmProfiles'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the profile'}, {u'name': u'lbruleid', u'required': False, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the loadbalancer'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the availability zone ID'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'id', u'required': False, u'related': [u'listAutoScaleVmGroups', u'createAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale vm group'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists autoscale vm groups.'}, u'projectaccounts': {u'name': u'listProjectAccounts', u'related': [u'createProject'], u'isasync': False, u'params': [{u'name': u'projectid', u'required': True, u'related': [u'createProject', u'listProjectAccounts'], u'length': 255, u'type': u'uuid', u'description': u'id of the project'}, {u'name': u'role', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list accounts of the project by role'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list accounts of the project by account name'}], u'requiredparams': [u'projectid'], u'description': u"Lists project's accounts"}, u'autoscalevmprofiles': {u'name': u'listAutoScaleVmProfiles', u'related': [], u'isasync': False, u'params': [{u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'domainid', u'required': False, u'related': [u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'id', u'required': False, u'related': [u'listAutoScaleVmProfiles'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale vm profile'}, {u'name': u'templateid', u'required': False, u'related': [u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the templateid of the autoscale vm profile'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'otherdeployparams', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the otherdeployparameters of the autoscale vm profile'}], u'requiredparams': [], u'description': u'Lists autoscale vm profiles.'}, u'apis': {u'name': u'listApis', u'related': [], u'isasync': False, u'params': [{u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'API name'}], u'requiredparams': [], u'description': u'lists all available apis on the server, provided by the Api Discovery plugin'}, u'vpcs': {u'name': u'listVPCs', u'related': [u'restartVPC'], u'isasync': False, u'params': [{u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'domainid', u'required': False, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by name of the VPC'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'cidr', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u"list by cidr of the VPC. All VPC guest networks' cidrs should be within this CIDR"}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'restartrequired', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list VPCs by restartRequired option'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list VPCs by state'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by display text of the VPC'}, {u'name': u'id', u'required': False, u'related': [u'restartVPC', u'listVPCs'], u'length': 255, u'type': u'uuid', u'description': u'list VPC by id'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list by zone'}, {u'name': u'supportedservices', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list VPC supporting certain services'}, {u'name': u'vpcofferingid', u'required': False, u'related': [u'listVPCOfferings', u'createVPCOffering'], u'length': 255, u'type': u'uuid', u'description': u'list by ID of the VPC offering'}], u'requiredparams': [], u'description': u'Lists VPCs'}, u'f5loadbalancers': {u'name': u'listF5LoadBalancers', u'related': [u'configureF5LoadBalancer'], u'isasync': False, u'params': [{u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'updatePhysicalNetwork', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'lbdeviceid', u'required': False, u'related': [u'configureF5LoadBalancer', u'listF5LoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'f5 load balancer device ID'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'lists F5 load balancer devices'}, u'snapshots': {u'name': u'listSnapshots', u'related': [], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'id', u'required': False, u'related': [u'listSnapshots'], u'length': 255, u'type': u'uuid', u'description': u'lists snapshot by snapshot ID'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'intervaltype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'valid values are HOURLY, DAILY, WEEKLY, and MONTHLY.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'volumeid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'lists snapshot by snapshot name'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'snapshottype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'valid values are MANUAL or RECURRING.'}], u'requiredparams': [], u'description': u'Lists all available snapshots for the account.'}, u'networkofferings': {u'name': u'listNetworkOfferings', u'related': [u'createNetworkOffering', u'updateNetworkOffering'], u'isasync': False, u'params': [{u'name': u'isdefault', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if need to list only default network offerings. Default value is false'}, {u'name': u'sourcenatsupported', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if need to list only netwok offerings where source nat is supported, false otherwise'}, {u'name': u'supportedservices', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list network offerings supporting certain services'}, {u'name': u'networkid', u'required': False, u'related': [u'createNetwork', u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.'}, {u'name': u'specifyipranges', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if need to list only network offerings which support specifying ip ranges'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list network offerings by name'}, {u'name': u'id', u'required': False, u'related': [u'listNetworkOfferings', u'createNetworkOffering', u'updateNetworkOffering'], u'length': 255, u'type': u'uuid', u'description': u'list network offerings by id'}, {u'name': u'specifyvlan', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'the tags for the network offering.'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'list netowrk offerings available for network creation in specific zone'}, {u'name': u'forvpc', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'the network offering can be used only for network creation inside the VPC'}, {u'name': u'traffictype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by traffic type'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'guestiptype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list network offerings by guest type: Shared or Isolated'}, {u'name': u'istagged', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if offering has tags specified'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 4096, u'type': u'string', u'description': u'list network offerings by tags'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list network offerings by display text'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list network offerings by state'}, {u'name': u'availability', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the availability of network offering. Default value is Required'}], u'requiredparams': [], u'description': u'Lists all available network offerings.'}, u'virtualmachines': {u'name': u'listVirtualMachines', u'related': [], u'isasync': False, u'params': [{u'name': u'templateid', u'required': False, u'related': [u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'list vms by template'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'networkid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list by network id'}, {u'name': u'storageid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u"the storage ID where vm's volumes belong to"}, {u'name': u'isoid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list vms by iso'}, {u'name': u'vpcid', u'required': False, u'related': [u'restartVPC'], u'length': 255, u'type': u'uuid', u'description': u'list vms by vpc'}, {u'name': u'podid', u'required': False, u'related': [u'updatePod'], u'length': 255, u'type': u'uuid', u'description': u'the pod ID'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the virtual machine'}, {u'name': u'details', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'comma separated list of host details requested, value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]. If no parameter is passed in, the details will be defaulted to all'}, {u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the target hypervisor for the template'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'groupid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the group ID'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the availability zone ID'}, {u'name': u'hostid', u'required': False, u'related': [u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'the host ID'}, {u'name': u'id', u'required': False, u'related': [u'listVirtualMachines'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine'}, {u'name': u'forvirtualnetwork', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list by network type; true if need to list vms using Virtual Network, false otherwise'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'state of the virtual machine'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'List the virtual machines owned by the account.'}, u'netscalerloadbalancernetworks': {u'name': u'listNetscalerLoadBalancerNetworks', u'related': [], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'lbdeviceid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'netscaler load balancer device ID'}], u'requiredparams': [u'lbdeviceid'], u'description': u'lists network that are using a netscaler load balancer device'}, u'oscategories': {u'name': u'listOsCategories', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'listOsCategories'], u'length': 255, u'type': u'uuid', u'description': u'list Os category by id'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list os category by name'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists all supported OS categories for this cloud.'}, u'virtualrouterelements': {u'name': u'listVirtualRouterElements', u'related': [u'createVirtualRouterElement', u'configureVirtualRouterElement'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'nspid', u'required': False, u'related': [u'addNetworkServiceProvider', u'listTrafficTypes', u'updateNetworkServiceProvider'], u'length': 255, u'type': u'uuid', u'description': u'list virtual router elements by network service provider id'}, {u'name': u'id', u'required': False, u'related': [u'createVirtualRouterElement', u'configureVirtualRouterElement', u'listVirtualRouterElements'], u'length': 255, u'type': u'uuid', u'description': u'list virtual router elements by id'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'enabled', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'list network offerings by enabled state'}], u'requiredparams': [], u'description': u'Lists all available virtual router elements.'}, u'lunsonfiler': {u'name': u'listLunsOnFiler', u'related': [], u'isasync': False, u'params': [{u'name': u'poolname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}], u'requiredparams': [u'poolname'], u'description': u'List LUN'}, u'asyncjobs': {u'name': u'listAsyncJobs', u'related': [u'queryAsyncJobResult'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'startdate', u'required': False, u'related': [], u'length': 255, u'type': u'tzdate', u'description': u'the start date of the async job'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}], u'requiredparams': [], u'description': u'Lists all pending asynchronous jobs for the account.'}, u'ostypes': {u'name': u'listOsTypes', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [u'listOsTypes'], u'length': 255, u'type': u'uuid', u'description': u'list by Os type Id'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'oscategoryid', u'required': False, u'related': [u'listOsCategories'], u'length': 255, u'type': u'uuid', u'description': u'list by Os Category id'}, {u'name': u'description', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list os by description'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists all supported OS types for this cloud.'}, u'networkacls': {u'name': u'listNetworkACLs', u'related': [u'createNetworkACL'], u'isasync': False, u'params': [{u'name': u'traffictype', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list network ACLs by traffic type - Ingress or Egress'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'id', u'required': False, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'Lists network ACL with the specified ID.'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'suspendProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'networkid', u'required': False, u'related': [u'createNetwork', u'listNiciraNvpDeviceNetworks', u'updateNetwork', u'listF5LoadBalancerNetworks', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'length': 255, u'type': u'uuid', u'description': u'list network ACLs by network Id'}], u'requiredparams': [], u'description': u'Lists all network ACLs'}, u'volumesonfiler': {u'name': u'listVolumesOnFiler', u'related': [], u'isasync': False, u'params': [{u'name': u'poolname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}], u'requiredparams': [u'poolname'], u'description': u'List Volumes'}, u'eventtypes': {u'name': u'listEventTypes', u'related': [], u'isasync': False, u'params': [], u'requiredparams': [], u'description': u'List Event Types'}, u'remoteaccessvpns': {u'name': u'listRemoteAccessVpns', u'related': [u'createRemoteAccessVpn'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'publicipid', u'required': True, u'related': [u'restartNetwork', u'listPublicIpAddresses', u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'public ip address id of the vpn server'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}], u'requiredparams': [u'publicipid'], u'description': u'Lists remote access vpns'}, u'alerts': {u'name': u'listAlerts', u'related': [], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list by alert type'}, {u'name': u'id', u'required': False, u'related': [u'listAlerts'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the alert'}], u'requiredparams': [], u'description': u'Lists all alerts.'}, u'regions': {u'name': u'listRegions', u'related': [u'addRegion'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'List Region by region ID.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List Region by region name.'}], u'requiredparams': [], u'description': u'Lists Regions'}, u'vpcofferings': {u'name': u'listVPCOfferings', u'related': [], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listVPCOfferings'], u'length': 255, u'type': u'uuid', u'description': u'list VPC offerings by id'}, {u'name': u'state', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list VPC offerings by state'}, {u'name': u'supportedservices', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list VPC offerings supporting certain services'}, {u'name': u'displaytext', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list VPC offerings by display text'}, {u'name': u'isdefault', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if need to list only default VPC offerings. Default value is false'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list VPC offerings by name'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists VPC offerings'}, u'niciranvpdevicenetworks': {u'name': u'listNiciraNvpDeviceNetworks', u'related': [u'createNetwork', u'updateNetwork', u'listF5LoadBalancerNetworks', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks', u'listNetworks'], u'isasync': False, u'params': [{u'name': u'nvpdeviceid', u'required': True, u'related': [u'addNiciraNvpDevice', u'listNiciraNvpDevices'], u'length': 255, u'type': u'uuid', u'description': u'nicira nvp device ID'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [u'nvpdeviceid'], u'description': u'lists network that are using a nicira nvp device'}, u'events': {u'name': u'listEvents', u'related': [], u'isasync': False, u'params': [{u'name': u'startdate', u'required': False, u'related': [], u'length': 255, u'type': u'date', u'description': u'the start date range of the list you want to retrieve (use format "yyyy-MM-dd" or the new format "yyyy-MM-dd HH:mm:ss")'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'enddate', u'required': False, u'related': [], u'length': 255, u'type': u'date', u'description': u'the end date range of the list you want to retrieve (use format "yyyy-MM-dd" or the new format "yyyy-MM-dd HH:mm:ss")'}, {u'name': u'duration', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the duration of the event'}, {u'name': u'id', u'required': False, u'related': [u'listEvents'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the event'}, {u'name': u'level', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the event level (INFO, WARN, ERROR)'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'entrytime', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'the time the event was entered'}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the event type (see event types)'}], u'requiredparams': [], u'description': u'A command to list events.'}, u'templates': {u'name': u'listTemplates', u'related': [u'registerIso', u'updateTemplate', u'prepareTemplate', u'copyIso', u'updateIso', u'listIsos'], u'isasync': False, u'params': [{u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'templatefilter', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'possible values are "featured", "self", "selfexecutable","sharedexecutable","executable", and "community". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured. * all : all templates (only usable by admins).'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listTemplates', u'registerIso', u'updateTemplate', u'prepareTemplate', u'copyIso', u'updateIso', u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the template ID'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the template name'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'hypervisor', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the hypervisor for which to restrict the search'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'list templates by zoneId'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}], u'requiredparams': [u'templatefilter'], u'description': u'List all public, private, and privileged templates.'}, u'cisconexusvsms': {u'name': u'listCiscoNexusVSMs', u'related': [u'disableCiscoNexusVSM', u'enableCiscoNexusVSM'], u'isasync': False, u'params': [{u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'clusterid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.'}], u'requiredparams': [], u'description': u'Retrieves a Cisco Nexus 1000v Virtual Switch Manager device associated with a Cluster'}, u'ipforwardingrules': {u'name': u'listIpForwardingRules', u'related': [], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'id', u'required': False, u'related': [u'listIpForwardingRules'], u'length': 255, u'type': u'uuid', u'description': u'Lists rule with the specified ID.'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'listVirtualMachines', u'destroyVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'Lists all rules applied to the specified Vm.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'ipaddressid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list the rule belonging to this public ip address'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}], u'requiredparams': [], u'description': u'List the ip forwarding rules'}, u'srxfirewalls': {u'name': u'listSrxFirewalls', u'related': [u'addSrxFirewall'], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'physicalnetworkid', u'required': False, u'related': [u'listPhysicalNetworks', u'createPhysicalNetwork'], u'length': 255, u'type': u'uuid', u'description': u'the Physical Network ID'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'fwdeviceid', u'required': False, u'related': [u'listSrxFirewalls', u'addSrxFirewall'], u'length': 255, u'type': u'uuid', u'description': u'SRX firewall device ID'}], u'requiredparams': [], u'description': u'lists SRX firewall devices in a physical network'}, u'vpnconnections': {u'name': u'listVpnConnections', u'related': [], u'isasync': False, u'params': [{u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'vpcid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'id of vpc'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'id', u'required': False, u'related': [u'listVpnConnections'], u'length': 255, u'type': u'uuid', u'description': u'id of the vpn connection'}], u'requiredparams': [], u'description': u'Lists site to site vpn connection gateways'}, u'trafficmonitors': {u'name': u'listTrafficMonitors', u'related': [], u'isasync': False, u'params': [{u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'zoneid', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'zone Id'}], u'requiredparams': [u'zoneid'], u'description': u'List traffic monitor Hosts.'}, u'vpnusers': {u'name': u'listVpnUsers', u'related': [], u'isasync': False, u'params': [{u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'id', u'required': False, u'related': [u'listVpnUsers'], u'length': 255, u'type': u'uuid', u'description': u'The uuid of the Vpn user'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'username', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the username of the vpn user.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}], u'requiredparams': [], u'description': u'Lists vpn users'}, u'egressfirewallrules': {u'name': u'listEgressFirewallRules', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Lists rule with the specified ID.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'networkid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the id network network for the egress firwall services'}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Lists rule with the specified ID.'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'ipaddressid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the id of IP address of the firwall services'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}], u'requiredparams': [], u'description': u'Lists all egress firewall rules for network id.'}, u'staticroutes': {u'name': u'listStaticRoutes', u'related': [u'createStaticRoute'], u'isasync': False, u'params': [{u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'gatewayid', u'required': False, u'related': [u'createPrivateGateway'], u'length': 255, u'type': u'uuid', u'description': u'list static routes by gateway id'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'vpcid', u'required': False, u'related': [u'updateVPC', u'restartVPC', u'listVPCs', u'createVPC'], u'length': 255, u'type': u'uuid', u'description': u'list static routes by vpc id'}, {u'name': u'id', u'required': False, u'related': [u'createStaticRoute', u'listStaticRoutes'], u'length': 255, u'type': u'uuid', u'description': u'list static route by id'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}], u'requiredparams': [], u'description': u'Lists all static routes'}, u'volumes': {u'name': u'listVolumes', u'related': [u'migrateVolume', u'detachVolume', u'resizeVolume', u'attachVolume', u'uploadVolume', u'createVolume'], u'isasync': False, u'params': [{u'name': u'isrecursive', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'defaults to false, but if true, lists all resources from the parent specified by the domainId till leaves.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the disk volume'}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'listProjects', u'suspendProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'list objects by project'}, {u'name': u'hostid', u'required': False, u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addSecondaryStorage', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers', u'prepareHostForMaintenance'], u'length': 255, u'type': u'uuid', u'description': u'list volumes on specified host'}, {u'name': u'id', u'required': False, u'related': [u'migrateVolume', u'detachVolume', u'resizeVolume', u'attachVolume', u'listVolumes', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the disk volume'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'List resources by tags (key/value pairs)'}, {u'name': u'zoneid', u'required': False, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the availability zone'}, {u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'list only resources belonging to the domain specified'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list resources by account. Must be used with the domainId parameter.'}, {u'name': u'virtualmachineid', u'required': False, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'rebootVirtualMachine', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'attachIso', u'listLoadBalancerRuleInstances', u'deployVirtualMachine', u'detachIso', u'resetSSHKeyForVirtualMachine', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the virtual machine'}, {u'name': u'type', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the type of disk volume'}, {u'name': u'listall', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u"If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false"}, {u'name': u'podid', u'required': False, u'related': [u'createPod', u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the pod id the disk volume belongs to'}], u'requiredparams': [], u'description': u'Lists all volumes.'}, u'pods': {u'name': u'listPods', u'related': [u'updatePod'], u'isasync': False, u'params': [{u'name': u'showcapacities', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'flag to display the capacity of the pods'}, {u'name': u'allocationstate', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list pods by allocation state'}, {u'name': u'pagesize', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'list Pods by Zone ID'}, {u'name': u'id', u'required': False, u'related': [u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'list Pods by ID'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'list Pods by name'}, {u'name': u'page', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u''}, {u'name': u'keyword', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'List by keyword'}], u'requiredparams': [], u'description': u'Lists all Pods.'}}, u'upload': {u'volume': {u'name': u'uploadVolume', u'related': [u'detachVolume'], u'isasync': True, u'params': [{u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the name of the volume'}, {u'name': u'format', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the format for the volume. Possible values include QCOW2, OVA, and VHD.'}, {u'name': u'url', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'the URL of where the volume is hosted. Possible URL include http:// and https://'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional accountName. Must be used with domainId.'}, {u'name': u'domainid', u'required': False, u'related': [u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId. If the account parameter is used, domainId must also be used.'}, {u'name': u'checksum', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the MD5 checksum value of this volume'}, {u'name': u'zoneid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone the volume is to be hosted on'}], u'requiredparams': [u'name', u'format', u'url', u'zoneid'], u'description': u'Uploads a data disk.'}, u'customcertificate': {u'name': u'uploadCustomCertificate', u'related': [], u'isasync': True, u'params': [{u'name': u'domainsuffix', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'DNS domain suffix that the certificate is granted for.'}, {u'name': u'certificate', u'required': True, u'related': [], u'length': 65535, u'type': u'string', u'description': u'The certificate to be uploaded.'}, {u'name': u'privatekey', u'required': False, u'related': [], u'length': 65535, u'type': u'string', u'description': u'The private key for the attached certificate.'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'A name / alias for the certificate.'}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'integer', u'description': u'An integer providing the location in a chain that the certificate will hold. Usually, this can be left empty. When creating a chain, the top level certificate should have an ID of 1, with each step in the chain incrementing by one. Example, CA with id = 1, Intermediate CA with id = 2, Site certificate with ID = 3'}], u'requiredparams': [u'domainsuffix', u'certificate'], u'description': u'Uploads a custom certificate for the console proxy VMs to use for SSL. Can be used to upload a single certificate signed by a known CA. Can also be used, through multiple calls, to upload a chain of certificates from CA to the custom certificate itself.'}}, u'remove': {u'region': {u'name': u'removeRegion', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'integer', u'description': u'ID of the region to delete'}], u'requiredparams': [u'id'], u'description': u'Removes specified region'}, u'nicfromvirtualmachine': {u'name': u'removeNicFromVirtualMachine', u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': True, u'params': [{u'name': u'nicid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'NIC ID'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'startVirtualMachine', u'updateDefaultNicForVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'resetPasswordForVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'removeNicFromVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'Virtual Machine ID'}], u'requiredparams': [u'nicid', u'virtualmachineid'], u'description': u'Removes VM from specified network by deleting a NIC'}, u'fromloadbalancerrule': {u'name': u'removeFromLoadBalancerRule', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listIpForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the load balancer rule'}, {u'name': u'virtualmachineids', u'required': True, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'list', u'description': u'the list of IDs of the virtual machines that are being removed from the load balancer rule (i.e. virtualMachineIds=1,2,3)'}], u'requiredparams': [u'id', u'virtualmachineids'], u'description': u'Removes a virtual machine or a list of virtual machines from a load balancer rule.'}, u'vpnuser': {u'name': u'removeVpnUser', u'related': [], u'isasync': True, u'params': [{u'name': u'domainid', u'required': False, u'related': [u'updateDomain', u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.'}, {u'name': u'projectid', u'required': False, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'remove vpn user from the project'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'an optional account for the vpn user. Must be used with domainId.'}, {u'name': u'username', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'username for the vpn user'}], u'requiredparams': [u'username'], u'description': u'Removes vpn user'}}, u'asyncapis': [u'createCondition', u'reconnectHost', u'copyTemplate', u'deleteBigSwitchVnsDevice', u'addNicToVirtualMachine', u'extractVolume', u'addAccountToProject', u'deleteEgressFirewallRule', u'deleteCiscoNexusVSM', u'createVpnConnection', u'suspendProject', u'addF5LoadBalancer', u'deleteAutoScaleVmGroup', u'authorizeSecurityGroupIngress', u'addNetscalerLoadBalancer', u'deleteDomain', u'configureNetscalerLoadBalancer', u'disableAutoScaleVmGroup', u'authorizeSecurityGroupEgress', u'createTemplate', u'migrateVolume', u'updatePhysicalNetwork', u'prepareHostForMaintenance', u'deletePrivateGateway', u'deleteStaticRoute', u'deleteTrafficType', u'deleteLoadBalancerRule', u'attachIso', u'destroySystemVm', u'deletePortForwardingRule', u'enableStorageMaintenance', u'stopRouter', u'configureSrxFirewall', u'attachVolume', u'updateVPCOffering', u'resetSSHKeyForVirtualMachine', u'updateProjectInvitation', u'createTags', u'enableAutoScaleVmGroup', u'deleteTags', u'deleteAccountFromProject', u'removeVpnUser', u'updateVpnCustomerGateway', u'stopSystemVm', u'uploadCustomCertificate', u'restartNetwork', u'createAutoScaleVmProfile', u'rebootVirtualMachine', u'enableCiscoNexusVSM', u'cancelHostMaintenance', u'deleteStorageNetworkIpRange', u'deleteFirewallRule', u'deleteVpnConnection', u'startSystemVm', u'deleteF5LoadBalancer', u'deleteNiciraNvpDevice', u'updateProject', u'deleteNetwork', u'deleteProject', u'deleteNetscalerLoadBalancer', u'deleteIpForwardingRule', u'addTrafficType', u'disableUser', u'resizeVolume', u'configureVirtualRouterElement', u'createStaticRoute', u'deleteProjectInvitation', u'migrateSystemVm', u'activateProject', u'removeNicFromVirtualMachine', u'revokeSecurityGroupIngress', u'updateDefaultNicForVirtualMachine', u'disableStaticNat', u'createNetworkACL', u'createVPC', u'configureF5LoadBalancer', u'disassociateIpAddress', u'createIpForwardingRule', u'createVolume', u'resetPasswordForVirtualMachine', u'assignToLoadBalancerRule', u'startRouter', u'extractIso', u'deleteRemoteAccessVpn', u'resetVpnConnection', u'createRemoteAccessVpn', u'extractTemplate', u'startVirtualMachine', u'detachIso', u'updateVPC', u'deleteAccount', u'associateIpAddress', u'updateAutoScaleVmProfile', u'disableAccount', u'updatePortForwardingRule', u'migrateVirtualMachine', u'createStorageNetworkIpRange', u'cancelStorageMaintenance', u'deployVirtualMachine', u'removeFromLoadBalancerRule', u'revokeSecurityGroupEgress', u'deleteCondition', u'createPortForwardingRule', u'addVpnUser', u'createVPCOffering', u'createEgressFirewallRule', u'deleteLBStickinessPolicy', u'destroyRouter', u'createPrivateGateway', u'disableCiscoNexusVSM', u'deleteAutoScaleVmProfile', u'updateTrafficType', u'deleteSnapshot', u'createProject', u'createLoadBalancerRule', u'addSrxFirewall', u'addNiciraNvpDevice', u'createAutoScalePolicy', u'restoreVirtualMachine', u'copyIso', u'uploadVolume', u'createLBStickinessPolicy', u'stopVirtualMachine', u'createCounter', u'createSnapshot', u'destroyVirtualMachine', u'updateNetwork', u'deleteVpnGateway', u'createAutoScaleVmGroup', u'rebootRouter', u'deleteNetworkServiceProvider', u'deleteIso', u'createVpnCustomerGateway', u'createFirewallRule', u'deleteAutoScalePolicy', u'deleteSrxFirewall', u'addNetworkServiceProvider', u'rebootSystemVm', u'detachVolume', u'deleteNetworkACL', u'markDefaultZoneForAccount', u'deleteVPC', u'restartVPC', u'updateAutoScaleVmGroup', u'updateLoadBalancerRule', u'createPhysicalNetwork', u'deleteTemplate', u'deletePhysicalNetwork', u'deleteVpnCustomerGateway', u'deleteVPCOffering', u'createVirtualRouterElement', u'updateAutoScalePolicy', u'addBigSwitchVnsDevice', u'createVpnGateway', u'updateNetworkServiceProvider', u'deleteCounter', u'updateStorageNetworkIpRange'], u'assign': {u'toloadbalancerrule': {u'name': u'assignToLoadBalancerRule', u'related': [], u'isasync': True, u'params': [{u'name': u'virtualmachineids', u'required': True, u'related': [u'startVirtualMachine', u'updateVirtualMachine', u'stopVirtualMachine', u'recoverVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'migrateVirtualMachine', u'changeServiceForVirtualMachine', u'deployVirtualMachine', u'detachIso', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'list', u'description': u'the list of IDs of the virtual machine that are being assigned to the load balancer rule(i.e. virtualMachineIds=1,2,3)'}, {u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}], u'requiredparams': [u'virtualmachineids', u'id'], u'description': u'Assigns virtual machine or a list of virtual machines to a load balancer rule.'}, u'virtualmachine': {u'name': u'assignVirtualMachine', u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'isasync': False, u'params': [{u'name': u'networkids', u'required': False, u'related': [u'updateNetwork', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'list', u'description': u'list of new network ids in which the moved VM will participate. In case no network ids are provided the VM will be part of the default network for that zone. In case there is no network yet created for the new account the default network will be created.'}, {u'name': u'domainid', u'required': True, u'related': [u'listDomainChildren', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'domain id of the new VM owner.'}, {u'name': u'securitygroupids', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list of security group ids to be applied on the virtual machine. In case no security groups are provided the VM is part of the default security group.'}, {u'name': u'account', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'account name of the new VM owner.'}, {u'name': u'virtualmachineid', u'required': True, u'related': [u'updateVirtualMachine', u'stopVirtualMachine', u'assignVirtualMachine', u'listVirtualMachines', u'destroyVirtualMachine', u'restoreVirtualMachine'], u'length': 255, u'type': u'uuid', u'description': u'id of the VM to be moved'}], u'requiredparams': [u'domainid', u'account', u'virtualmachineid'], u'description': u'Assign a VM from one account to another under the same domain. This API is available for Basic zones with security groups and Advance zones with guest networks. The VM is restricted to move between accounts under same domain.'}}, u'delete': {u'loadbalancerrule': {u'name': u'deleteLoadBalancerRule', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the load balancer rule'}], u'requiredparams': [u'id'], u'description': u'Deletes a load balancer rule.'}, u'domain': {u'name': u'deleteDomain', u'related': [], u'isasync': True, u'params': [{u'name': u'cleanup', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'true if all domain resources (child domains, accounts) have to be cleaned up, false otherwise'}, {u'name': u'id', u'required': True, u'related': [u'updateDomain', u'listDomainChildren', u'listDomains', u'createDomain'], u'length': 255, u'type': u'uuid', u'description': u'ID of domain to delete'}], u'requiredparams': [u'id'], u'description': u'Deletes a specified domain'}, u'instancegroup': {u'name': u'deleteInstanceGroup', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the instance group'}], u'requiredparams': [u'id'], u'description': u'Deletes a vm group'}, u'diskoffering': {u'name': u'deleteDiskOffering', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateDiskOffering', u'createDiskOffering', u'listDiskOfferings'], u'length': 255, u'type': u'uuid', u'description': u'ID of the disk offering'}], u'requiredparams': [u'id'], u'description': u'Updates a disk offering.'}, u'externalloadbalancer': {u'name': u'deleteExternalLoadBalancer', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'listSwifts', u'addHost', u'cancelHostMaintenance', u'addBaremetalHost', u'updateHost', u'addSwift', u'listHosts', u'listExternalLoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'Id of the external loadbalancer appliance.'}], u'requiredparams': [u'id'], u'description': u'Deletes a F5 external load balancer appliance added in a zone.'}, u'securitygroup': {u'name': u'deleteSecurityGroup', u'related': [], u'isasync': False, u'params': [{u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the domain ID of account owning the security group'}, {u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'The ID of the security group. Mutually exclusive with name parameter'}, {u'name': u'name', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'The ID of the security group. Mutually exclusive with id parameter'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account of the security group. Must be specified with domain ID'}, {u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the project of the security group'}], u'requiredparams': [], u'description': u'Deletes security group'}, u'portforwardingrule': {u'name': u'deletePortForwardingRule', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the port forwarding rule'}], u'requiredparams': [u'id'], u'description': u'Deletes a port forwarding rule'}, u'cluster': {u'name': u'deleteCluster', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the cluster ID'}], u'requiredparams': [u'id'], u'description': u'Deletes a cluster.'}, u'accountfromproject': {u'name': u'deleteAccountFromProject', u'related': [], u'isasync': True, u'params': [{u'name': u'projectid', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject', u'updateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to remove the account from'}, {u'name': u'account', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'name of the account to be removed from the project'}], u'requiredparams': [u'projectid', u'account'], u'description': u'Deletes account from the project'}, u'networkdevice': {u'name': u'deleteNetworkDevice', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'addHost', u'updateHost', u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'Id of network device to delete'}], u'requiredparams': [u'id'], u'description': u'Deletes network device.'}, u'firewallrule': {u'name': u'deleteFirewallRule', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the firewall rule'}], u'requiredparams': [u'id'], u'description': u'Deletes a firewall rule'}, u'pod': {u'name': u'deletePod', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'updatePod', u'listPods'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the Pod'}], u'requiredparams': [u'id'], u'description': u'Deletes a Pod.'}, u'ipforwardingrule': {u'name': u'deleteIpForwardingRule', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the id of the forwarding rule'}], u'requiredparams': [u'id'], u'description': u'Deletes an ip forwarding rule'}, u'vpnconnection': {u'name': u'deleteVpnConnection', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listVpnConnections', u'resetVpnConnection'], u'length': 255, u'type': u'uuid', u'description': u'id of vpn connection'}], u'requiredparams': [u'id'], u'description': u'Delete site to site vpn connection'}, u'lbstickinesspolicy': {u'name': u'deleteLBStickinessPolicy', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createLBStickinessPolicy'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the LB stickiness policy'}], u'requiredparams': [u'id'], u'description': u'Deletes a LB stickiness policy.'}, u'vpcoffering': {u'name': u'deleteVPCOffering', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the VPC offering'}], u'requiredparams': [u'id'], u'description': u'Deletes VPC offering'}, u'network': {u'name': u'deleteNetwork', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateNetwork', u'listSrxFirewallNetworks', u'listNetscalerLoadBalancerNetworks'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the network'}], u'requiredparams': [u'id'], u'description': u'Deletes a network'}, u'zone': {u'name': u'deleteZone', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateZone', u'listZones', u'createZone'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the Zone'}], u'requiredparams': [u'id'], u'description': u'Deletes a Zone.'}, u'remoteaccessvpn': {u'name': u'deleteRemoteAccessVpn', u'related': [], u'isasync': True, u'params': [{u'name': u'publicipid', u'required': True, u'related': [u'associateIpAddress'], u'length': 255, u'type': u'uuid', u'description': u'public ip address id of the vpn server'}], u'requiredparams': [u'publicipid'], u'description': u'Destroys a l2tp/ipsec remote access vpn'}, u'storagenetworkiprange': {u'name': u'deleteStorageNetworkIpRange', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listStorageNetworkIpRange', u'createStorageNetworkIpRange', u'updateStorageNetworkIpRange'], u'length': 255, u'type': u'uuid', u'description': u'the uuid of the storage network ip range'}], u'requiredparams': [u'id'], u'description': u'Deletes a storage network IP Range.'}, u'bigswitchvnsdevice': {u'name': u'deleteBigSwitchVnsDevice', u'related': [], u'isasync': True, u'params': [{u'name': u'vnsdeviceid', u'required': True, u'related': [], u'length': 255, u'type': u'long', u'description': u'BigSwitch device ID'}], u'requiredparams': [u'vnsdeviceid'], u'description': u' delete a bigswitch vns device'}, u'projectinvitation': {u'name': u'deleteProjectInvitation', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listProjectInvitations'], u'length': 255, u'type': u'uuid', u'description': u'id of the invitation'}], u'requiredparams': [u'id'], u'description': u'Accepts or declines project invitation'}, u'autoscalepolicy': {u'name': u'deleteAutoScalePolicy', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateAutoScalePolicy'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale policy'}], u'requiredparams': [u'id'], u'description': u'Deletes a autoscale policy.'}, u'niciranvpdevice': {u'name': u'deleteNiciraNvpDevice', u'related': [], u'isasync': True, u'params': [{u'name': u'nvpdeviceid', u'required': True, u'related': [u'addNiciraNvpDevice', u'listNiciraNvpDevices'], u'length': 255, u'type': u'uuid', u'description': u'Nicira device ID'}], u'requiredparams': [u'nvpdeviceid'], u'description': u' delete a nicira nvp device'}, u'serviceoffering': {u'name': u'deleteServiceOffering', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'updateHypervisorCapabilities', u'listServiceOfferings'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the service offering'}], u'requiredparams': [u'id'], u'description': u'Deletes a service offering.'}, u'condition': {u'name': u'deleteCondition', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the condition.'}], u'requiredparams': [u'id'], u'description': u'Removes a condition'}, u'storagepool': {u'name': u'deleteStoragePool', u'related': [], u'isasync': False, u'params': [{u'name': u'forced', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force destroy storage pool (force expunge volumes in Destroyed state as a part of pool removal)'}, {u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'Storage pool id'}], u'requiredparams': [u'id'], u'description': u'Deletes a storage pool.'}, u'vpngateway': {u'name': u'deleteVpnGateway', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createVpnGateway'], u'length': 255, u'type': u'uuid', u'description': u'id of customer gateway'}], u'requiredparams': [u'id'], u'description': u'Delete site to site vpn gateway'}, u'snapshot': {u'name': u'deleteSnapshot', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createSnapshot', u'listSnapshots'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the snapshot'}], u'requiredparams': [u'id'], u'description': u'Deletes a snapshot of a disk volume.'}, u'autoscalevmgroup': {u'name': u'deleteAutoScaleVmGroup', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listAutoScaleVmGroups', u'createAutoScaleVmGroup', u'disableAutoScaleVmGroup', u'enableAutoScaleVmGroup', u'updateAutoScaleVmGroup'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale group'}], u'requiredparams': [u'id'], u'description': u'Deletes a autoscale vm group.'}, u'trafficmonitor': {u'name': u'deleteTrafficMonitor', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'Id of the Traffic Monitor Host.'}], u'requiredparams': [u'id'], u'description': u'Deletes an traffic monitor host.'}, u'networkacl': {u'name': u'deleteNetworkACL', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the network ACL'}], u'requiredparams': [u'id'], u'description': u'Deletes a Network ACL'}, u'template': {u'name': u'deleteTemplate', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the template'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of zone of the template'}], u'requiredparams': [u'id'], u'description': u'Deletes a template from the system. All virtual machines using the deleted template will not be affected.'}, u'tags': {u'name': u'deleteTags', u'related': [], u'isasync': True, u'params': [{u'name': u'resourceids', u'required': True, u'related': [], u'length': 255, u'type': u'list', u'description': u'Delete tags for resource id(s)'}, {u'name': u'tags', u'required': False, u'related': [], u'length': 255, u'type': u'map', u'description': u'Delete tags matching key/value pairs'}, {u'name': u'resourcetype', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Delete tag by resource type'}], u'requiredparams': [u'resourceids', u'resourcetype'], u'description': u'Deleting resource tag(s)'}, u'snapshotpolicies': {u'name': u'deleteSnapshotPolicies', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the Id of the snapshot policy'}, {u'name': u'ids', u'required': False, u'related': [], u'length': 255, u'type': u'list', u'description': u'list of snapshots policy IDs separated by comma'}], u'requiredparams': [], u'description': u'Deletes snapshot policies for the account.'}, u'privategateway': {u'name': u'deletePrivateGateway', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createPrivateGateway', u'listPrivateGateways'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the private gateway'}], u'requiredparams': [u'id'], u'description': u'Deletes a Private gateway'}, u'traffictype': {u'name': u'deleteTrafficType', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'addTrafficType', u'updateTrafficType'], u'length': 255, u'type': u'uuid', u'description': u'traffic type id'}], u'requiredparams': [u'id'], u'description': u'Deletes traffic type of a physical network'}, u'host': {u'name': u'deleteHost', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the host ID'}, {u'name': u'forcedestroylocalstorage', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force destroy local storage on this host. All VMs created on this local storage will be destroyed'}, {u'name': u'forced', u'required': False, u'related': [], u'length': 255, u'type': u'boolean', u'description': u'Force delete the host. All HA enabled vms running on the host will be put to HA; HA disabled ones will be stopped'}], u'requiredparams': [u'id'], u'description': u'Deletes a host.'}, u'staticroute': {u'name': u'deleteStaticRoute', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createStaticRoute', u'listStaticRoutes'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the static route'}], u'requiredparams': [u'id'], u'description': u'Deletes a static route'}, u'vpc': {u'name': u'deleteVPC', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'restartVPC'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the VPC'}], u'requiredparams': [u'id'], u'description': u'Deletes a VPC'}, u'srxfirewall': {u'name': u'deleteSrxFirewall', u'related': [], u'isasync': True, u'params': [{u'name': u'fwdeviceid', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'srx firewall device ID'}], u'requiredparams': [u'fwdeviceid'], u'description': u' delete a SRX firewall device'}, u'externalfirewall': {u'name': u'deleteExternalFirewall', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'listHosts'], u'length': 255, u'type': u'uuid', u'description': u'Id of the external firewall appliance.'}], u'requiredparams': [u'id'], u'description': u'Deletes an external firewall appliance.'}, u'pool': {u'name': u'deletePool', u'related': [], u'isasync': False, u'params': [{u'name': u'poolname', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'pool name.'}], u'requiredparams': [u'poolname'], u'description': u'Delete a pool'}, u'autoscalevmprofile': {u'name': u'deleteAutoScaleVmProfile', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listAutoScaleVmProfiles'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the autoscale profile'}], u'requiredparams': [u'id'], u'description': u'Deletes a autoscale vm profile.'}, u'volume': {u'name': u'deleteVolume', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'detachVolume', u'resizeVolume', u'uploadVolume', u'createVolume'], u'length': 255, u'type': u'uuid', u'description': u'The ID of the disk volume'}], u'requiredparams': [u'id'], u'description': u'Deletes a detached disk volume.'}, u'account': {u'name': u'deleteAccount', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'markDefaultZoneForAccount', u'updateAccount', u'listAccounts', u'lockAccount', u'disableAccount'], u'length': 255, u'type': u'uuid', u'description': u'Account id'}], u'requiredparams': [u'id'], u'description': u'Deletes a account, and all users associated with this account'}, u'cisconexusvsm': {u'name': u'deleteCiscoNexusVSM', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'disableCiscoNexusVSM', u'listCiscoNexusVSMs', u'enableCiscoNexusVSM'], u'length': 255, u'type': u'uuid', u'description': u'Id of the Cisco Nexus 1000v VSM device to be deleted'}], u'requiredparams': [u'id'], u'description': u' delete a Cisco Nexus VSM device'}, u'netscalerloadbalancer': {u'name': u'deleteNetscalerLoadBalancer', u'related': [], u'isasync': True, u'params': [{u'name': u'lbdeviceid', u'required': True, u'related': [u'listNetscalerLoadBalancers'], u'length': 255, u'type': u'uuid', u'description': u'netscaler load balancer device ID'}], u'requiredparams': [u'lbdeviceid'], u'description': u' delete a netscaler load balancer device'}, u'networkoffering': {u'name': u'deleteNetworkOffering', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'createNetworkOffering', u'updateNetworkOffering'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the network offering'}], u'requiredparams': [u'id'], u'description': u'Deletes a network offering.'}, u'vpncustomergateway': {u'name': u'deleteVpnCustomerGateway', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'id of customer gateway'}], u'requiredparams': [u'id'], u'description': u'Delete site to site vpn customer gateway'}, u'counter': {u'name': u'deleteCounter', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the counter'}], u'requiredparams': [u'id'], u'description': u'Deletes a counter'}, u'physicalnetwork': {u'name': u'deletePhysicalNetwork', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the Physical network'}], u'requiredparams': [u'id'], u'description': u'Deletes a Physical Network.'}, u'project': {u'name': u'deleteProject', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'createProject', u'listProjectAccounts', u'activateProject'], u'length': 255, u'type': u'uuid', u'description': u'id of the project to be deleted'}], u'requiredparams': [u'id'], u'description': u'Deletes a project'}, u'vlaniprange': {u'name': u'deleteVlanIpRange', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'listVlanIpRanges'], u'length': 255, u'type': u'uuid', u'description': u'the id of the VLAN IP range'}], u'requiredparams': [u'id'], u'description': u'Creates a VLAN IP range.'}, u'f5loadbalancer': {u'name': u'deleteF5LoadBalancer', u'related': [], u'isasync': True, u'params': [{u'name': u'lbdeviceid', u'required': True, u'related': [u'configureF5LoadBalancer'], u'length': 255, u'type': u'uuid', u'description': u'netscaler load balancer device ID'}], u'requiredparams': [u'lbdeviceid'], u'description': u' delete a F5 load balancer device'}, u'iso': {u'name': u'deleteIso', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'listIsos'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the ISO file'}, {u'name': u'zoneid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones'}], u'requiredparams': [u'id'], u'description': u'Deletes an ISO file.'}, u'egressfirewallrule': {u'name': u'deleteEgressFirewallRule', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'updatePortForwardingRule', u'listIpForwardingRules', u'createIpForwardingRule', u'listPortForwardingRules', u'createPortForwardingRule'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the firewall rule'}], u'requiredparams': [u'id'], u'description': u'Deletes an ggress firewall rule'}, u'networkserviceprovider': {u'name': u'deleteNetworkServiceProvider', u'related': [], u'isasync': True, u'params': [{u'name': u'id', u'required': True, u'related': [u'addNetworkServiceProvider', u'listTrafficTypes', u'updateNetworkServiceProvider'], u'length': 255, u'type': u'uuid', u'description': u'the ID of the network service provider'}], u'requiredparams': [u'id'], u'description': u'Deletes a Network Service Provider.'}, u'sshkeypair': {u'name': u'deleteSSHKeyPair', u'related': [], u'isasync': False, u'params': [{u'name': u'projectid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the project associated with keypair'}, {u'name': u'domainid', u'required': False, u'related': [], u'length': 255, u'type': u'uuid', u'description': u'the domain ID associated with the keypair'}, {u'name': u'name', u'required': True, u'related': [], u'length': 255, u'type': u'string', u'description': u'Name of the keypair'}, {u'name': u'account', u'required': False, u'related': [], u'length': 255, u'type': u'string', u'description': u'the account associated with the keypair. Must be used with the domainId parameter.'}], u'requiredparams': [u'name'], u'description': u'Deletes a keypair by name'}, u'user': {u'name': u'deleteUser', u'related': [], u'isasync': False, u'params': [{u'name': u'id', u'required': True, u'related': [u'lockUser', u'listUsers'], u'length': 255, u'type': u'uuid', u'description': u'id of the user to be deleted'}], u'requiredparams': [u'id'], u'description': u'Deletes a user for an account'}}} diff --git a/tools/ngui/requester.py b/tools/ngui/requester.py deleted file mode 100644 index 03342dfa58d2..000000000000 --- a/tools/ngui/requester.py +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# 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. - -try: - import base64 - import hashlib - import hmac - import httplib - import json - import os - import pdb - import re - import shlex - import sys - import time - import types - import urllib - import urllib2 - -except ImportError, e: - print "Import error in %s : %s" % (__name__, e) - import sys - sys.exit() - - -def logger_debug(logger, message): - if logger is not None: - logger.debug(message) - - -def make_request(command, args, logger, host, port, - apikey, secretkey, protocol, path): - response = None - error = None - - if protocol != 'http' and protocol != 'https': - error = "Protocol must be 'http' or 'https'" - return None, error - - if args is None: - args = {} - - args["command"] = command - args["apiKey"] = apikey - args["response"] = "json" - request = zip(args.keys(), args.values()) - request.sort(key=lambda x: x[0].lower()) - - request_url = "&".join(["=".join([r[0], urllib.quote_plus(str(r[1]))]) - for r in request]) - hashStr = "&".join(["=".join([r[0].lower(), - str.lower(urllib.quote_plus(str(r[1]))).replace("+", - "%20")]) for r in request]) - - sig = urllib.quote_plus(base64.encodebytes(hmac.new(secretkey, hashStr, - hashlib.sha1).digest()).strip()) - request_url += "&signature=%s" % sig - request_url = "%s://%s:%s%s?%s" % (protocol, host, port, path, request_url) - - try: - logger_debug(logger, "Request sent: %s" % request_url) - connection = urllib2.urlopen(request_url) - response = connection.read() - except Exception, e: - error = str(e) - - logger_debug(logger, "Response received: %s" % response) - if error is not None: - logger_debug(logger, error) - - return response, error - - -def monkeyrequest(command, args, isasync, asyncblock, logger, host, port, - apikey, secretkey, timeout, protocol, path): - - response = None - error = None - logger_debug(logger, "======== START Request ========") - logger_debug(logger, "Requesting command=%s, args=%s" % (command, args)) - response, error = make_request(command, args, logger, host, port, - apikey, secretkey, protocol, path) - logger_debug(logger, "======== END Request ========\n") - - if error is not None: - return response, error - - def process_json(response): - try: - response = json.loads(str(response)) - except ValueError, e: - error = "Error processing json response, %s" % e - logger_debug(logger, "Error processing json", e) - return response - - response = process_json(response) - if response is None: - return response, error - - isasync = isasync and (asyncblock == "true") - responsekey = filter(lambda x: 'response' in x, response.keys())[0] - - if isasync and 'jobid' in response[responsekey]: - jobid = response[responsekey]['jobid'] - command = "queryAsyncJobResult" - request = {'jobid': jobid} - timeout = int(timeout) - pollperiod = 3 - progress = 1 - while timeout > 0: - print '\r' + '.' * progress, - time.sleep(pollperiod) - timeout = timeout - pollperiod - progress += 1 - logger_debug(logger, "Job %s to timeout in %ds" % (jobid, timeout)) - sys.stdout.flush() - response, error = monkeyrequest(command, request, isasync, - asyncblock, logger, - host, port, apikey, secretkey, - timeout, protocol, path) - response = process_json(response) - responsekeys = filter(lambda x: 'response' in x, response.keys()) - if len(responsekeys) < 1: - continue - result = response[responsekeys[0]] - jobstatus = result['jobstatus'] - if jobstatus == 2: - jobresult = result["jobresult"] - error = "\rAsync job %s failed\nError %s, %s" % (jobid, - jobresult["errorcode"], jobresult["errortext"]) - return response, error - elif jobstatus == 1: - print '\r', - return response, error - error = "Error: Async query timeout occurred for jobid %s" % jobid - - return response, error diff --git a/tools/ngui/static/bootstrap/css/bootstrap-responsive.css b/tools/ngui/static/bootstrap/css/bootstrap-responsive.css deleted file mode 100644 index 09e88ce3fecc..000000000000 --- a/tools/ngui/static/bootstrap/css/bootstrap-responsive.css +++ /dev/null @@ -1,1109 +0,0 @@ -/*! - * Bootstrap Responsive v2.3.2 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */ - -.clearfix { - *zoom: 1; -} - -.clearfix:before, -.clearfix:after { - display: table; - line-height: 0; - content: ""; -} - -.clearfix:after { - clear: both; -} - -.hide-text { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; -} - -.input-block-level { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; -} - -@-ms-viewport { - width: device-width; -} - -.hidden { - display: none; - visibility: hidden; -} - -.visible-phone { - display: none !important; -} - -.visible-tablet { - display: none !important; -} - -.hidden-desktop { - display: none !important; -} - -.visible-desktop { - display: inherit !important; -} - -@media (min-width: 768px) and (max-width: 979px) { - .hidden-desktop { - display: inherit !important; - } - .visible-desktop { - display: none !important ; - } - .visible-tablet { - display: inherit !important; - } - .hidden-tablet { - display: none !important; - } -} - -@media (max-width: 767px) { - .hidden-desktop { - display: inherit !important; - } - .visible-desktop { - display: none !important; - } - .visible-phone { - display: inherit !important; - } - .hidden-phone { - display: none !important; - } -} - -.visible-print { - display: none !important; -} - -@media print { - .visible-print { - display: inherit !important; - } - .hidden-print { - display: none !important; - } -} - -@media (min-width: 1200px) { - .row { - margin-left: -30px; - *zoom: 1; - } - .row:before, - .row:after { - display: table; - line-height: 0; - content: ""; - } - .row:after { - clear: both; - } - [class*="span"] { - float: left; - min-height: 1px; - margin-left: 30px; - } - .container, - .navbar-static-top .container, - .navbar-fixed-top .container, - .navbar-fixed-bottom .container { - width: 1170px; - } - .span12 { - width: 1170px; - } - .span11 { - width: 1070px; - } - .span10 { - width: 970px; - } - .span9 { - width: 870px; - } - .span8 { - width: 770px; - } - .span7 { - width: 670px; - } - .span6 { - width: 570px; - } - .span5 { - width: 470px; - } - .span4 { - width: 370px; - } - .span3 { - width: 270px; - } - .span2 { - width: 170px; - } - .span1 { - width: 70px; - } - .offset12 { - margin-left: 1230px; - } - .offset11 { - margin-left: 1130px; - } - .offset10 { - margin-left: 1030px; - } - .offset9 { - margin-left: 930px; - } - .offset8 { - margin-left: 830px; - } - .offset7 { - margin-left: 730px; - } - .offset6 { - margin-left: 630px; - } - .offset5 { - margin-left: 530px; - } - .offset4 { - margin-left: 430px; - } - .offset3 { - margin-left: 330px; - } - .offset2 { - margin-left: 230px; - } - .offset1 { - margin-left: 130px; - } - .row-fluid { - width: 100%; - *zoom: 1; - } - .row-fluid:before, - .row-fluid:after { - display: table; - line-height: 0; - content: ""; - } - .row-fluid:after { - clear: both; - } - .row-fluid [class*="span"] { - display: block; - float: left; - width: 100%; - min-height: 30px; - margin-left: 2.564102564102564%; - *margin-left: 2.5109110747408616%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="span"]:first-child { - margin-left: 0; - } - .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.564102564102564%; - } - .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; - } - .row-fluid .span11 { - width: 91.45299145299145%; - *width: 91.39979996362975%; - } - .row-fluid .span10 { - width: 82.90598290598291%; - *width: 82.8527914166212%; - } - .row-fluid .span9 { - width: 74.35897435897436%; - *width: 74.30578286961266%; - } - .row-fluid .span8 { - width: 65.81196581196582%; - *width: 65.75877432260411%; - } - .row-fluid .span7 { - width: 57.26495726495726%; - *width: 57.21176577559556%; - } - .row-fluid .span6 { - width: 48.717948717948715%; - *width: 48.664757228587014%; - } - .row-fluid .span5 { - width: 40.17094017094017%; - *width: 40.11774868157847%; - } - .row-fluid .span4 { - width: 31.623931623931625%; - *width: 31.570740134569924%; - } - .row-fluid .span3 { - width: 23.076923076923077%; - *width: 23.023731587561375%; - } - .row-fluid .span2 { - width: 14.52991452991453%; - *width: 14.476723040552828%; - } - .row-fluid .span1 { - width: 5.982905982905983%; - *width: 5.929714493544281%; - } - .row-fluid .offset12 { - margin-left: 105.12820512820512%; - *margin-left: 105.02182214948171%; - } - .row-fluid .offset12:first-child { - margin-left: 102.56410256410257%; - *margin-left: 102.45771958537915%; - } - .row-fluid .offset11 { - margin-left: 96.58119658119658%; - *margin-left: 96.47481360247316%; - } - .row-fluid .offset11:first-child { - margin-left: 94.01709401709402%; - *margin-left: 93.91071103837061%; - } - .row-fluid .offset10 { - margin-left: 88.03418803418803%; - *margin-left: 87.92780505546462%; - } - .row-fluid .offset10:first-child { - margin-left: 85.47008547008548%; - *margin-left: 85.36370249136206%; - } - .row-fluid .offset9 { - margin-left: 79.48717948717949%; - *margin-left: 79.38079650845607%; - } - .row-fluid .offset9:first-child { - margin-left: 76.92307692307693%; - *margin-left: 76.81669394435352%; - } - .row-fluid .offset8 { - margin-left: 70.94017094017094%; - *margin-left: 70.83378796144753%; - } - .row-fluid .offset8:first-child { - margin-left: 68.37606837606839%; - *margin-left: 68.26968539734497%; - } - .row-fluid .offset7 { - margin-left: 62.393162393162385%; - *margin-left: 62.28677941443899%; - } - .row-fluid .offset7:first-child { - margin-left: 59.82905982905982%; - *margin-left: 59.72267685033642%; - } - .row-fluid .offset6 { - margin-left: 53.84615384615384%; - *margin-left: 53.739770867430444%; - } - .row-fluid .offset6:first-child { - margin-left: 51.28205128205128%; - *margin-left: 51.175668303327875%; - } - .row-fluid .offset5 { - margin-left: 45.299145299145295%; - *margin-left: 45.1927623204219%; - } - .row-fluid .offset5:first-child { - margin-left: 42.73504273504273%; - *margin-left: 42.62865975631933%; - } - .row-fluid .offset4 { - margin-left: 36.75213675213675%; - *margin-left: 36.645753773413354%; - } - .row-fluid .offset4:first-child { - margin-left: 34.18803418803419%; - *margin-left: 34.081651209310785%; - } - .row-fluid .offset3 { - margin-left: 28.205128205128204%; - *margin-left: 28.0987452264048%; - } - .row-fluid .offset3:first-child { - margin-left: 25.641025641025642%; - *margin-left: 25.53464266230224%; - } - .row-fluid .offset2 { - margin-left: 19.65811965811966%; - *margin-left: 19.551736679396257%; - } - .row-fluid .offset2:first-child { - margin-left: 17.094017094017094%; - *margin-left: 16.98763411529369%; - } - .row-fluid .offset1 { - margin-left: 11.11111111111111%; - *margin-left: 11.004728132387708%; - } - .row-fluid .offset1:first-child { - margin-left: 8.547008547008547%; - *margin-left: 8.440625568285142%; - } - input, - textarea, - .uneditable-input { - margin-left: 0; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 30px; - } - input.span12, - textarea.span12, - .uneditable-input.span12 { - width: 1156px; - } - input.span11, - textarea.span11, - .uneditable-input.span11 { - width: 1056px; - } - input.span10, - textarea.span10, - .uneditable-input.span10 { - width: 956px; - } - input.span9, - textarea.span9, - .uneditable-input.span9 { - width: 856px; - } - input.span8, - textarea.span8, - .uneditable-input.span8 { - width: 756px; - } - input.span7, - textarea.span7, - .uneditable-input.span7 { - width: 656px; - } - input.span6, - textarea.span6, - .uneditable-input.span6 { - width: 556px; - } - input.span5, - textarea.span5, - .uneditable-input.span5 { - width: 456px; - } - input.span4, - textarea.span4, - .uneditable-input.span4 { - width: 356px; - } - input.span3, - textarea.span3, - .uneditable-input.span3 { - width: 256px; - } - input.span2, - textarea.span2, - .uneditable-input.span2 { - width: 156px; - } - input.span1, - textarea.span1, - .uneditable-input.span1 { - width: 56px; - } - .thumbnails { - margin-left: -30px; - } - .thumbnails > li { - margin-left: 30px; - } - .row-fluid .thumbnails { - margin-left: 0; - } -} - -@media (min-width: 768px) and (max-width: 979px) { - .row { - margin-left: -20px; - *zoom: 1; - } - .row:before, - .row:after { - display: table; - line-height: 0; - content: ""; - } - .row:after { - clear: both; - } - [class*="span"] { - float: left; - min-height: 1px; - margin-left: 20px; - } - .container, - .navbar-static-top .container, - .navbar-fixed-top .container, - .navbar-fixed-bottom .container { - width: 724px; - } - .span12 { - width: 724px; - } - .span11 { - width: 662px; - } - .span10 { - width: 600px; - } - .span9 { - width: 538px; - } - .span8 { - width: 476px; - } - .span7 { - width: 414px; - } - .span6 { - width: 352px; - } - .span5 { - width: 290px; - } - .span4 { - width: 228px; - } - .span3 { - width: 166px; - } - .span2 { - width: 104px; - } - .span1 { - width: 42px; - } - .offset12 { - margin-left: 764px; - } - .offset11 { - margin-left: 702px; - } - .offset10 { - margin-left: 640px; - } - .offset9 { - margin-left: 578px; - } - .offset8 { - margin-left: 516px; - } - .offset7 { - margin-left: 454px; - } - .offset6 { - margin-left: 392px; - } - .offset5 { - margin-left: 330px; - } - .offset4 { - margin-left: 268px; - } - .offset3 { - margin-left: 206px; - } - .offset2 { - margin-left: 144px; - } - .offset1 { - margin-left: 82px; - } - .row-fluid { - width: 100%; - *zoom: 1; - } - .row-fluid:before, - .row-fluid:after { - display: table; - line-height: 0; - content: ""; - } - .row-fluid:after { - clear: both; - } - .row-fluid [class*="span"] { - display: block; - float: left; - width: 100%; - min-height: 30px; - margin-left: 2.7624309392265194%; - *margin-left: 2.709239449864817%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="span"]:first-child { - margin-left: 0; - } - .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.7624309392265194%; - } - .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; - } - .row-fluid .span11 { - width: 91.43646408839778%; - *width: 91.38327259903608%; - } - .row-fluid .span10 { - width: 82.87292817679558%; - *width: 82.81973668743387%; - } - .row-fluid .span9 { - width: 74.30939226519337%; - *width: 74.25620077583166%; - } - .row-fluid .span8 { - width: 65.74585635359117%; - *width: 65.69266486422946%; - } - .row-fluid .span7 { - width: 57.18232044198895%; - *width: 57.12912895262725%; - } - .row-fluid .span6 { - width: 48.61878453038674%; - *width: 48.56559304102504%; - } - .row-fluid .span5 { - width: 40.05524861878453%; - *width: 40.00205712942283%; - } - .row-fluid .span4 { - width: 31.491712707182323%; - *width: 31.43852121782062%; - } - .row-fluid .span3 { - width: 22.92817679558011%; - *width: 22.87498530621841%; - } - .row-fluid .span2 { - width: 14.3646408839779%; - *width: 14.311449394616199%; - } - .row-fluid .span1 { - width: 5.801104972375691%; - *width: 5.747913483013988%; - } - .row-fluid .offset12 { - margin-left: 105.52486187845304%; - *margin-left: 105.41847889972962%; - } - .row-fluid .offset12:first-child { - margin-left: 102.76243093922652%; - *margin-left: 102.6560479605031%; - } - .row-fluid .offset11 { - margin-left: 96.96132596685082%; - *margin-left: 96.8549429881274%; - } - .row-fluid .offset11:first-child { - margin-left: 94.1988950276243%; - *margin-left: 94.09251204890089%; - } - .row-fluid .offset10 { - margin-left: 88.39779005524862%; - *margin-left: 88.2914070765252%; - } - .row-fluid .offset10:first-child { - margin-left: 85.6353591160221%; - *margin-left: 85.52897613729868%; - } - .row-fluid .offset9 { - margin-left: 79.8342541436464%; - *margin-left: 79.72787116492299%; - } - .row-fluid .offset9:first-child { - margin-left: 77.07182320441989%; - *margin-left: 76.96544022569647%; - } - .row-fluid .offset8 { - margin-left: 71.2707182320442%; - *margin-left: 71.16433525332079%; - } - .row-fluid .offset8:first-child { - margin-left: 68.50828729281768%; - *margin-left: 68.40190431409427%; - } - .row-fluid .offset7 { - margin-left: 62.70718232044199%; - *margin-left: 62.600799341718584%; - } - .row-fluid .offset7:first-child { - margin-left: 59.94475138121547%; - *margin-left: 59.838368402492065%; - } - .row-fluid .offset6 { - margin-left: 54.14364640883978%; - *margin-left: 54.037263430116376%; - } - .row-fluid .offset6:first-child { - margin-left: 51.38121546961326%; - *margin-left: 51.27483249088986%; - } - .row-fluid .offset5 { - margin-left: 45.58011049723757%; - *margin-left: 45.47372751851417%; - } - .row-fluid .offset5:first-child { - margin-left: 42.81767955801105%; - *margin-left: 42.71129657928765%; - } - .row-fluid .offset4 { - margin-left: 37.01657458563536%; - *margin-left: 36.91019160691196%; - } - .row-fluid .offset4:first-child { - margin-left: 34.25414364640884%; - *margin-left: 34.14776066768544%; - } - .row-fluid .offset3 { - margin-left: 28.45303867403315%; - *margin-left: 28.346655695309746%; - } - .row-fluid .offset3:first-child { - margin-left: 25.69060773480663%; - *margin-left: 25.584224756083227%; - } - .row-fluid .offset2 { - margin-left: 19.88950276243094%; - *margin-left: 19.783119783707537%; - } - .row-fluid .offset2:first-child { - margin-left: 17.12707182320442%; - *margin-left: 17.02068884448102%; - } - .row-fluid .offset1 { - margin-left: 11.32596685082873%; - *margin-left: 11.219583872105325%; - } - .row-fluid .offset1:first-child { - margin-left: 8.56353591160221%; - *margin-left: 8.457152932878806%; - } - input, - textarea, - .uneditable-input { - margin-left: 0; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 20px; - } - input.span12, - textarea.span12, - .uneditable-input.span12 { - width: 710px; - } - input.span11, - textarea.span11, - .uneditable-input.span11 { - width: 648px; - } - input.span10, - textarea.span10, - .uneditable-input.span10 { - width: 586px; - } - input.span9, - textarea.span9, - .uneditable-input.span9 { - width: 524px; - } - input.span8, - textarea.span8, - .uneditable-input.span8 { - width: 462px; - } - input.span7, - textarea.span7, - .uneditable-input.span7 { - width: 400px; - } - input.span6, - textarea.span6, - .uneditable-input.span6 { - width: 338px; - } - input.span5, - textarea.span5, - .uneditable-input.span5 { - width: 276px; - } - input.span4, - textarea.span4, - .uneditable-input.span4 { - width: 214px; - } - input.span3, - textarea.span3, - .uneditable-input.span3 { - width: 152px; - } - input.span2, - textarea.span2, - .uneditable-input.span2 { - width: 90px; - } - input.span1, - textarea.span1, - .uneditable-input.span1 { - width: 28px; - } -} - -@media (max-width: 767px) { - body { - padding-right: 20px; - padding-left: 20px; - } - .navbar-fixed-top, - .navbar-fixed-bottom, - .navbar-static-top { - margin-right: -20px; - margin-left: -20px; - } - .container-fluid { - padding: 0; - } - .dl-horizontal dt { - float: none; - width: auto; - clear: none; - text-align: left; - } - .dl-horizontal dd { - margin-left: 0; - } - .container { - width: auto; - } - .row-fluid { - width: 100%; - } - .row, - .thumbnails { - margin-left: 0; - } - .thumbnails > li { - float: none; - margin-left: 0; - } - [class*="span"], - .uneditable-input[class*="span"], - .row-fluid [class*="span"] { - display: block; - float: none; - width: 100%; - margin-left: 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .span12, - .row-fluid .span12 { - width: 100%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="offset"]:first-child { - margin-left: 0; - } - .input-large, - .input-xlarge, - .input-xxlarge, - input[class*="span"], - select[class*="span"], - textarea[class*="span"], - .uneditable-input { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .input-prepend input, - .input-append input, - .input-prepend input[class*="span"], - .input-append input[class*="span"] { - display: inline-block; - width: auto; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 0; - } - .modal { - position: fixed; - top: 20px; - right: 20px; - left: 20px; - width: auto; - margin: 0; - } - .modal.fade { - top: -100px; - } - .modal.fade.in { - top: 20px; - } -} - -@media (max-width: 480px) { - .nav-collapse { - -webkit-transform: translate3d(0, 0, 0); - } - .page-header h1 small { - display: block; - line-height: 20px; - } - input[type="checkbox"], - input[type="radio"] { - border: 1px solid #ccc; - } - .form-horizontal .control-label { - float: none; - width: auto; - padding-top: 0; - text-align: left; - } - .form-horizontal .controls { - margin-left: 0; - } - .form-horizontal .control-list { - padding-top: 0; - } - .form-horizontal .form-actions { - padding-right: 10px; - padding-left: 10px; - } - .media .pull-left, - .media .pull-right { - display: block; - float: none; - margin-bottom: 10px; - } - .media-object { - margin-right: 0; - margin-left: 0; - } - .modal { - top: 10px; - right: 10px; - left: 10px; - } - .modal-header .close { - padding: 10px; - margin: -10px; - } - .carousel-caption { - position: static; - } -} - -@media (max-width: 979px) { - body { - padding-top: 0; - } - .navbar-fixed-top, - .navbar-fixed-bottom { - position: static; - } - .navbar-fixed-top { - margin-bottom: 20px; - } - .navbar-fixed-bottom { - margin-top: 20px; - } - .navbar-fixed-top .navbar-inner, - .navbar-fixed-bottom .navbar-inner { - padding: 5px; - } - .navbar .container { - width: auto; - padding: 0; - } - .navbar .brand { - padding-right: 10px; - padding-left: 10px; - margin: 0 0 0 -5px; - } - .nav-collapse { - clear: both; - } - .nav-collapse .nav { - float: none; - margin: 0 0 10px; - } - .nav-collapse .nav > li { - float: none; - } - .nav-collapse .nav > li > a { - margin-bottom: 2px; - } - .nav-collapse .nav > .divider-vertical { - display: none; - } - .nav-collapse .nav .nav-header { - color: #777777; - text-shadow: none; - } - .nav-collapse .nav > li > a, - .nav-collapse .dropdown-menu a { - padding: 9px 15px; - font-weight: bold; - color: #777777; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - } - .nav-collapse .btn { - padding: 4px 10px 4px; - font-weight: normal; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - } - .nav-collapse .dropdown-menu li + li a { - margin-bottom: 2px; - } - .nav-collapse .nav > li > a:hover, - .nav-collapse .nav > li > a:focus, - .nav-collapse .dropdown-menu a:hover, - .nav-collapse .dropdown-menu a:focus { - background-color: #f2f2f2; - } - .navbar-inverse .nav-collapse .nav > li > a, - .navbar-inverse .nav-collapse .dropdown-menu a { - color: #999999; - } - .navbar-inverse .nav-collapse .nav > li > a:hover, - .navbar-inverse .nav-collapse .nav > li > a:focus, - .navbar-inverse .nav-collapse .dropdown-menu a:hover, - .navbar-inverse .nav-collapse .dropdown-menu a:focus { - background-color: #111111; - } - .nav-collapse.in .btn-group { - padding: 0; - margin-top: 5px; - } - .nav-collapse .dropdown-menu { - position: static; - top: auto; - left: auto; - display: none; - float: none; - max-width: none; - padding: 0; - margin: 0 15px; - background-color: transparent; - border: none; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - } - .nav-collapse .open > .dropdown-menu { - display: block; - } - .nav-collapse .dropdown-menu:before, - .nav-collapse .dropdown-menu:after { - display: none; - } - .nav-collapse .dropdown-menu .divider { - display: none; - } - .nav-collapse .nav > li > .dropdown-menu:before, - .nav-collapse .nav > li > .dropdown-menu:after { - display: none; - } - .nav-collapse .navbar-form, - .nav-collapse .navbar-search { - float: none; - padding: 10px 15px; - margin: 10px 0; - border-top: 1px solid #f2f2f2; - border-bottom: 1px solid #f2f2f2; - -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); - -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); - } - .navbar-inverse .nav-collapse .navbar-form, - .navbar-inverse .nav-collapse .navbar-search { - border-top-color: #111111; - border-bottom-color: #111111; - } - .navbar .nav-collapse .nav.pull-right { - float: none; - margin-left: 0; - } - .nav-collapse, - .nav-collapse.collapse { - height: 0; - overflow: hidden; - } - .navbar .btn-navbar { - display: block; - } - .navbar-static .navbar-inner { - padding-right: 10px; - padding-left: 10px; - } -} - -@media (min-width: 980px) { - .nav-collapse.collapse { - height: auto !important; - overflow: visible !important; - } -} diff --git a/tools/ngui/static/bootstrap/css/bootstrap-responsive.min.css b/tools/ngui/static/bootstrap/css/bootstrap-responsive.min.css deleted file mode 100644 index d1b7f4b0b821..000000000000 --- a/tools/ngui/static/bootstrap/css/bootstrap-responsive.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * Bootstrap Responsive v2.3.1 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}@-ms-viewport{width:device-width}.hidden{display:none;visibility:hidden}.visible-phone{display:none!important}.visible-tablet{display:none!important}.hidden-desktop{display:none!important}.visible-desktop{display:inherit!important}@media(min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-tablet{display:inherit!important}.hidden-tablet{display:none!important}}@media(max-width:767px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-phone{display:inherit!important}.hidden-phone{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:inherit!important}.hidden-print{display:none!important}}@media(min-width:1200px){.row{margin-left:-30px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:30px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px}.span12{width:1170px}.span11{width:1070px}.span10{width:970px}.span9{width:870px}.span8{width:770px}.span7{width:670px}.span6{width:570px}.span5{width:470px}.span4{width:370px}.span3{width:270px}.span2{width:170px}.span1{width:70px}.offset12{margin-left:1230px}.offset11{margin-left:1130px}.offset10{margin-left:1030px}.offset9{margin-left:930px}.offset8{margin-left:830px}.offset7{margin-left:730px}.offset6{margin-left:630px}.offset5{margin-left:530px}.offset4{margin-left:430px}.offset3{margin-left:330px}.offset2{margin-left:230px}.offset1{margin-left:130px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%}.row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%}.row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%}.row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%}.row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%}.row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%}.row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%}.row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%}.row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%}.row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%}.row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%}.row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%}.row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%}.row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%}.row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%}.row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%}.row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%}.row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%}.row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%}.row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%}.row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%}.row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%}.row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%}.row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%}.row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%}.row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%}.row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%}.row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%}.row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%}.row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%}.row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%}.row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%}.row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%}.row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%}.row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:30px}input.span12,textarea.span12,.uneditable-input.span12{width:1156px}input.span11,textarea.span11,.uneditable-input.span11{width:1056px}input.span10,textarea.span10,.uneditable-input.span10{width:956px}input.span9,textarea.span9,.uneditable-input.span9{width:856px}input.span8,textarea.span8,.uneditable-input.span8{width:756px}input.span7,textarea.span7,.uneditable-input.span7{width:656px}input.span6,textarea.span6,.uneditable-input.span6{width:556px}input.span5,textarea.span5,.uneditable-input.span5{width:456px}input.span4,textarea.span4,.uneditable-input.span4{width:356px}input.span3,textarea.span3,.uneditable-input.span3{width:256px}input.span2,textarea.span2,.uneditable-input.span2{width:156px}input.span1,textarea.span1,.uneditable-input.span1{width:56px}.thumbnails{margin-left:-30px}.thumbnails>li{margin-left:30px}.row-fluid .thumbnails{margin-left:0}}@media(min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px}.span12{width:724px}.span11{width:662px}.span10{width:600px}.span9{width:538px}.span8{width:476px}.span7{width:414px}.span6{width:352px}.span5{width:290px}.span4{width:228px}.span3{width:166px}.span2{width:104px}.span1{width:42px}.offset12{margin-left:764px}.offset11{margin-left:702px}.offset10{margin-left:640px}.offset9{margin-left:578px}.offset8{margin-left:516px}.offset7{margin-left:454px}.offset6{margin-left:392px}.offset5{margin-left:330px}.offset4{margin-left:268px}.offset3{margin-left:206px}.offset2{margin-left:144px}.offset1{margin-left:82px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%}.row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%}.row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%}.row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%}.row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%}.row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%}.row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%}.row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%}.row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%}.row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%}.row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%}.row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%}.row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%}.row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%}.row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%}.row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%}.row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%}.row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%}.row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%}.row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%}.row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%}.row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%}.row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%}.row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%}.row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%}.row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%}.row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%}.row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%}.row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%}.row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%}.row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%}.row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%}.row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%}.row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%}.row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:710px}input.span11,textarea.span11,.uneditable-input.span11{width:648px}input.span10,textarea.span10,.uneditable-input.span10{width:586px}input.span9,textarea.span9,.uneditable-input.span9{width:524px}input.span8,textarea.span8,.uneditable-input.span8{width:462px}input.span7,textarea.span7,.uneditable-input.span7{width:400px}input.span6,textarea.span6,.uneditable-input.span6{width:338px}input.span5,textarea.span5,.uneditable-input.span5{width:276px}input.span4,textarea.span4,.uneditable-input.span4{width:214px}input.span3,textarea.span3,.uneditable-input.span3{width:152px}input.span2,textarea.span2,.uneditable-input.span2{width:90px}input.span1,textarea.span1,.uneditable-input.span1{width:28px}}@media(max-width:767px){body{padding-right:20px;padding-left:20px}.navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-right:-20px;margin-left:-20px}.container-fluid{padding:0}.dl-horizontal dt{float:none;width:auto;clear:none;text-align:left}.dl-horizontal dd{margin-left:0}.container{width:auto}.row-fluid{width:100%}.row,.thumbnails{margin-left:0}.thumbnails>li{float:none;margin-left:0}[class*="span"],.uneditable-input[class*="span"],.row-fluid [class*="span"]{display:block;float:none;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="offset"]:first-child{margin-left:0}.input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto}.controls-row [class*="span"]+[class*="span"]{margin-left:0}.modal{position:fixed;top:20px;right:20px;left:20px;width:auto;margin:0}.modal.fade{top:-100px}.modal.fade.in{top:20px}}@media(max-width:480px){.nav-collapse{-webkit-transform:translate3d(0,0,0)}.page-header h1 small{display:block;line-height:20px}input[type="checkbox"],input[type="radio"]{border:1px solid #ccc}.form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left}.form-horizontal .controls{margin-left:0}.form-horizontal .control-list{padding-top:0}.form-horizontal .form-actions{padding-right:10px;padding-left:10px}.media .pull-left,.media .pull-right{display:block;float:none;margin-bottom:10px}.media-object{margin-right:0;margin-left:0}.modal{top:10px;right:10px;left:10px}.modal-header .close{padding:10px;margin:-10px}.carousel-caption{position:static}}@media(max-width:979px){body{padding-top:0}.navbar-fixed-top,.navbar-fixed-bottom{position:static}.navbar-fixed-top{margin-bottom:20px}.navbar-fixed-bottom{margin-top:20px}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px}.navbar .container{width:auto;padding:0}.navbar .brand{padding-right:10px;padding-left:10px;margin:0 0 0 -5px}.nav-collapse{clear:both}.nav-collapse .nav{float:none;margin:0 0 10px}.nav-collapse .nav>li{float:none}.nav-collapse .nav>li>a{margin-bottom:2px}.nav-collapse .nav>.divider-vertical{display:none}.nav-collapse .nav .nav-header{color:#777;text-shadow:none}.nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.nav-collapse .dropdown-menu li+li a{margin-bottom:2px}.nav-collapse .nav>li>a:hover,.nav-collapse .nav>li>a:focus,.nav-collapse .dropdown-menu a:hover,.nav-collapse .dropdown-menu a:focus{background-color:#f2f2f2}.navbar-inverse .nav-collapse .nav>li>a,.navbar-inverse .nav-collapse .dropdown-menu a{color:#999}.navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .nav>li>a:focus,.navbar-inverse .nav-collapse .dropdown-menu a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:focus{background-color:#111}.nav-collapse.in .btn-group{padding:0;margin-top:5px}.nav-collapse .dropdown-menu{position:static;top:auto;left:auto;display:none;float:none;max-width:none;padding:0;margin:0 15px;background-color:transparent;border:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.nav-collapse .open>.dropdown-menu{display:block}.nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none}.nav-collapse .dropdown-menu .divider{display:none}.nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none}.nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}.navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111;border-bottom-color:#111}.navbar .nav-collapse .nav.pull-right{float:none;margin-left:0}.nav-collapse,.nav-collapse.collapse{height:0;overflow:hidden}.navbar .btn-navbar{display:block}.navbar-static .navbar-inner{padding-right:10px;padding-left:10px}}@media(min-width:980px){.nav-collapse.collapse{height:auto!important;overflow:visible!important}} diff --git a/tools/ngui/static/bootstrap/css/bootstrap.css b/tools/ngui/static/bootstrap/css/bootstrap.css deleted file mode 100644 index f857ba213f61..000000000000 --- a/tools/ngui/static/bootstrap/css/bootstrap.css +++ /dev/null @@ -1,6315 +0,0 @@ -/*! - * Bootstrap v2.3.2 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */ -.clearfix { - *zoom: 1; -} -.clearfix:before, -.clearfix:after { - display: table; - content: ""; - line-height: 0; -} -.clearfix:after { - clear: both; -} -.hide-text { - font: 0/0 a; - color: transparent; - text-shadow: none; - background-color: transparent; - border: 0; -} -.input-block-level { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; -} -article, -aside, -details, -figcaption, -figure, -footer, -header, -hgroup, -nav, -section { - display: block; -} -audio, -canvas, -video { - display: inline-block; - *display: inline; - *zoom: 1; -} -audio:not([controls]) { - display: none; -} -html { - font-size: 100%; - -webkit-text-size-adjust: 100%; - -ms-text-size-adjust: 100%; -} -a:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} -a:hover, -a:active { - outline: 0; -} -sub, -sup { - position: relative; - font-size: 75%; - line-height: 0; - vertical-align: baseline; -} -sup { - top: -0.5em; -} -sub { - bottom: -0.25em; -} -img { - /* Responsive images (ensure images don't scale beyond their parents) */ - - max-width: 100%; - /* Part 1: Set a maxium relative to the parent */ - - width: auto\9; - /* IE7-8 need help adjusting responsive images */ - - height: auto; - /* Part 2: Scale the height according to the width, otherwise you get stretching */ - - vertical-align: middle; - border: 0; - -ms-interpolation-mode: bicubic; -} -#map_canvas img, -.google-maps img { - max-width: none; -} -button, -input, -select, -textarea { - margin: 0; - font-size: 100%; - vertical-align: middle; -} -button, -input { - *overflow: visible; - line-height: normal; -} -button::-moz-focus-inner, -input::-moz-focus-inner { - padding: 0; - border: 0; -} -button, -html input[type="button"], -input[type="reset"], -input[type="submit"] { - -webkit-appearance: button; - cursor: pointer; -} -label, -select, -button, -input[type="button"], -input[type="reset"], -input[type="submit"], -input[type="radio"], -input[type="checkbox"] { - cursor: pointer; -} -input[type="search"] { - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; - -webkit-appearance: textfield; -} -input[type="search"]::-webkit-search-decoration, -input[type="search"]::-webkit-search-cancel-button { - -webkit-appearance: none; -} -textarea { - overflow: auto; - vertical-align: top; -} -@media print { - * { - text-shadow: none !important; - color: #000 !important; - background: transparent !important; - box-shadow: none !important; - } - a, - a:visited { - text-decoration: underline; - } - a[href]:after { - content: " (" attr(href) ")"; - } - abbr[title]:after { - content: " (" attr(title) ")"; - } - .ir a:after, - a[href^="javascript:"]:after, - a[href^="#"]:after { - content: ""; - } - pre, - blockquote { - border: 1px solid #999; - page-break-inside: avoid; - } - thead { - display: table-header-group; - } - tr, - img { - page-break-inside: avoid; - } - img { - max-width: 100% !important; - } - @page { - margin: 0.5cm; - } - p, - h2, - h3 { - orphans: 3; - widows: 3; - } - h2, - h3 { - page-break-after: avoid; - } -} -body { - margin: 0; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - line-height: 20px; - color: #333333; - background-color: #ffffff; -} -a { - color: #0088cc; - text-decoration: none; -} -a:hover, -a:focus { - color: #005580; - text-decoration: underline; -} -.img-rounded { - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} -.img-polaroid { - padding: 4px; - background-color: #fff; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -} -.img-circle { - -webkit-border-radius: 500px; - -moz-border-radius: 500px; - border-radius: 500px; -} -.row { - margin-left: -20px; - *zoom: 1; -} -.row:before, -.row:after { - display: table; - content: ""; - line-height: 0; -} -.row:after { - clear: both; -} -[class*="span"] { - float: left; - min-height: 1px; - margin-left: 20px; -} -.container, -.navbar-static-top .container, -.navbar-fixed-top .container, -.navbar-fixed-bottom .container { - width: 940px; -} -.span12 { - width: 940px; -} -.span11 { - width: 860px; -} -.span10 { - width: 780px; -} -.span9 { - width: 700px; -} -.span8 { - width: 620px; -} -.span7 { - width: 540px; -} -.span6 { - width: 460px; -} -.span5 { - width: 380px; -} -.span4 { - width: 300px; -} -.span3 { - width: 220px; -} -.span2 { - width: 140px; -} -.span1 { - width: 60px; -} -.offset12 { - margin-left: 980px; -} -.offset11 { - margin-left: 900px; -} -.offset10 { - margin-left: 820px; -} -.offset9 { - margin-left: 740px; -} -.offset8 { - margin-left: 660px; -} -.offset7 { - margin-left: 580px; -} -.offset6 { - margin-left: 500px; -} -.offset5 { - margin-left: 420px; -} -.offset4 { - margin-left: 340px; -} -.offset3 { - margin-left: 260px; -} -.offset2 { - margin-left: 180px; -} -.offset1 { - margin-left: 100px; -} -.row-fluid { - width: 100%; - *zoom: 1; -} -.row-fluid:before, -.row-fluid:after { - display: table; - content: ""; - line-height: 0; -} -.row-fluid:after { - clear: both; -} -.row-fluid [class*="span"] { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - float: left; - margin-left: 2.127659574468085%; - *margin-left: 2.074468085106383%; -} -.row-fluid [class*="span"]:first-child { - margin-left: 0; -} -.row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.127659574468085%; -} -.row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; -} -.row-fluid .span11 { - width: 91.48936170212765%; - *width: 91.43617021276594%; -} -.row-fluid .span10 { - width: 82.97872340425532%; - *width: 82.92553191489361%; -} -.row-fluid .span9 { - width: 74.46808510638297%; - *width: 74.41489361702126%; -} -.row-fluid .span8 { - width: 65.95744680851064%; - *width: 65.90425531914893%; -} -.row-fluid .span7 { - width: 57.44680851063829%; - *width: 57.39361702127659%; -} -.row-fluid .span6 { - width: 48.93617021276595%; - *width: 48.88297872340425%; -} -.row-fluid .span5 { - width: 40.42553191489362%; - *width: 40.37234042553192%; -} -.row-fluid .span4 { - width: 31.914893617021278%; - *width: 31.861702127659576%; -} -.row-fluid .span3 { - width: 23.404255319148934%; - *width: 23.351063829787233%; -} -.row-fluid .span2 { - width: 14.893617021276595%; - *width: 14.840425531914894%; -} -.row-fluid .span1 { - width: 6.382978723404255%; - *width: 6.329787234042553%; -} -.row-fluid .offset12 { - margin-left: 104.25531914893617%; - *margin-left: 104.14893617021275%; -} -.row-fluid .offset12:first-child { - margin-left: 102.12765957446808%; - *margin-left: 102.02127659574467%; -} -.row-fluid .offset11 { - margin-left: 95.74468085106382%; - *margin-left: 95.6382978723404%; -} -.row-fluid .offset11:first-child { - margin-left: 93.61702127659574%; - *margin-left: 93.51063829787232%; -} -.row-fluid .offset10 { - margin-left: 87.23404255319149%; - *margin-left: 87.12765957446807%; -} -.row-fluid .offset10:first-child { - margin-left: 85.1063829787234%; - *margin-left: 84.99999999999999%; -} -.row-fluid .offset9 { - margin-left: 78.72340425531914%; - *margin-left: 78.61702127659572%; -} -.row-fluid .offset9:first-child { - margin-left: 76.59574468085106%; - *margin-left: 76.48936170212764%; -} -.row-fluid .offset8 { - margin-left: 70.2127659574468%; - *margin-left: 70.10638297872339%; -} -.row-fluid .offset8:first-child { - margin-left: 68.08510638297872%; - *margin-left: 67.9787234042553%; -} -.row-fluid .offset7 { - margin-left: 61.70212765957446%; - *margin-left: 61.59574468085106%; -} -.row-fluid .offset7:first-child { - margin-left: 59.574468085106375%; - *margin-left: 59.46808510638297%; -} -.row-fluid .offset6 { - margin-left: 53.191489361702125%; - *margin-left: 53.085106382978715%; -} -.row-fluid .offset6:first-child { - margin-left: 51.063829787234035%; - *margin-left: 50.95744680851063%; -} -.row-fluid .offset5 { - margin-left: 44.68085106382979%; - *margin-left: 44.57446808510638%; -} -.row-fluid .offset5:first-child { - margin-left: 42.5531914893617%; - *margin-left: 42.4468085106383%; -} -.row-fluid .offset4 { - margin-left: 36.170212765957444%; - *margin-left: 36.06382978723405%; -} -.row-fluid .offset4:first-child { - margin-left: 34.04255319148936%; - *margin-left: 33.93617021276596%; -} -.row-fluid .offset3 { - margin-left: 27.659574468085104%; - *margin-left: 27.5531914893617%; -} -.row-fluid .offset3:first-child { - margin-left: 25.53191489361702%; - *margin-left: 25.425531914893618%; -} -.row-fluid .offset2 { - margin-left: 19.148936170212764%; - *margin-left: 19.04255319148936%; -} -.row-fluid .offset2:first-child { - margin-left: 17.02127659574468%; - *margin-left: 16.914893617021278%; -} -.row-fluid .offset1 { - margin-left: 10.638297872340425%; - *margin-left: 10.53191489361702%; -} -.row-fluid .offset1:first-child { - margin-left: 8.51063829787234%; - *margin-left: 8.404255319148938%; -} -[class*="span"].hide, -.row-fluid [class*="span"].hide { - display: none; -} -[class*="span"].pull-right, -.row-fluid [class*="span"].pull-right { - float: right; -} -.container { - margin-right: auto; - margin-left: auto; - *zoom: 1; -} -.container:before, -.container:after { - display: table; - content: ""; - line-height: 0; -} -.container:after { - clear: both; -} -.container-fluid { - padding-right: 20px; - padding-left: 20px; - *zoom: 1; -} -.container-fluid:before, -.container-fluid:after { - display: table; - content: ""; - line-height: 0; -} -.container-fluid:after { - clear: both; -} -p { - margin: 0 0 10px; -} -.lead { - margin-bottom: 20px; - font-size: 19.5px; - font-weight: 200; - line-height: 30px; -} -small { - font-size: 85%; -} -strong { - font-weight: bold; -} -em { - font-style: italic; -} -cite { - font-style: normal; -} -.muted { - color: #999999; -} -a.muted:hover, -a.muted:focus { - color: #808080; -} -.text-warning { - color: #c09853; -} -a.text-warning:hover, -a.text-warning:focus { - color: #a47e3c; -} -.text-error { - color: #b94a48; -} -a.text-error:hover, -a.text-error:focus { - color: #953b39; -} -.text-info { - color: #3a87ad; -} -a.text-info:hover, -a.text-info:focus { - color: #2d6987; -} -.text-success { - color: #468847; -} -a.text-success:hover, -a.text-success:focus { - color: #356635; -} -.text-left { - text-align: left; -} -.text-right { - text-align: right; -} -.text-center { - text-align: center; -} -h1, -h2, -h3, -h4, -h5, -h6 { - margin: 10px 0; - font-family: inherit; - font-weight: bold; - line-height: 20px; - color: inherit; - text-rendering: optimizelegibility; -} -h1 small, -h2 small, -h3 small, -h4 small, -h5 small, -h6 small { - font-weight: normal; - line-height: 1; - color: #999999; -} -h1, -h2, -h3 { - line-height: 40px; -} -h1 { - font-size: 35.75px; -} -h2 { - font-size: 29.25px; -} -h3 { - font-size: 22.75px; -} -h4 { - font-size: 16.25px; -} -h5 { - font-size: 13px; -} -h6 { - font-size: 11.049999999999999px; -} -h1 small { - font-size: 22.75px; -} -h2 small { - font-size: 16.25px; -} -h3 small { - font-size: 13px; -} -h4 small { - font-size: 13px; -} -.page-header { - padding-bottom: 9px; - margin: 20px 0 30px; - border-bottom: 1px solid #eeeeee; -} -ul, -ol { - padding: 0; - margin: 0 0 10px 25px; -} -ul ul, -ul ol, -ol ol, -ol ul { - margin-bottom: 0; -} -li { - line-height: 20px; -} -ul.unstyled, -ol.unstyled { - margin-left: 0; - list-style: none; -} -ul.inline, -ol.inline { - margin-left: 0; - list-style: none; -} -ul.inline > li, -ol.inline > li { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - padding-left: 5px; - padding-right: 5px; -} -dl { - margin-bottom: 20px; -} -dt, -dd { - line-height: 20px; -} -dt { - font-weight: bold; -} -dd { - margin-left: 10px; -} -.dl-horizontal { - *zoom: 1; -} -.dl-horizontal:before, -.dl-horizontal:after { - display: table; - content: ""; - line-height: 0; -} -.dl-horizontal:after { - clear: both; -} -.dl-horizontal dt { - float: left; - width: 160px; - clear: left; - text-align: right; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} -.dl-horizontal dd { - margin-left: 180px; -} -hr { - margin: 20px 0; - border: 0; - border-top: 1px solid #eeeeee; - border-bottom: 1px solid #ffffff; -} -abbr[title], -abbr[data-original-title] { - cursor: help; - border-bottom: 1px dotted #999999; -} -abbr.initialism { - font-size: 90%; - text-transform: uppercase; -} -blockquote { - padding: 0 0 0 15px; - margin: 0 0 20px; - border-left: 5px solid #eeeeee; -} -blockquote p { - margin-bottom: 0; - font-size: 16.25px; - font-weight: 300; - line-height: 1.25; -} -blockquote small { - display: block; - line-height: 20px; - color: #999999; -} -blockquote small:before { - content: '\2014 \00A0'; -} -blockquote.pull-right { - float: right; - padding-right: 15px; - padding-left: 0; - border-right: 5px solid #eeeeee; - border-left: 0; -} -blockquote.pull-right p, -blockquote.pull-right small { - text-align: right; -} -blockquote.pull-right small:before { - content: ''; -} -blockquote.pull-right small:after { - content: '\00A0 \2014'; -} -q:before, -q:after, -blockquote:before, -blockquote:after { - content: ""; -} -address { - display: block; - margin-bottom: 20px; - font-style: normal; - line-height: 20px; -} -code, -pre { - padding: 0 3px 2px; - font-family: Monaco, Menlo, Consolas, "Courier New", monospace; - font-size: 11px; - color: #333333; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} -code { - padding: 2px 4px; - color: #d14; - background-color: #f7f7f9; - border: 1px solid #e1e1e8; - white-space: nowrap; -} -pre { - display: block; - padding: 9.5px; - margin: 0 0 10px; - font-size: 12px; - line-height: 20px; - word-break: break-all; - word-wrap: break-word; - white-space: pre; - white-space: pre-wrap; - background-color: #f5f5f5; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.15); - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -pre.prettyprint { - margin-bottom: 20px; -} -pre code { - padding: 0; - color: inherit; - white-space: pre; - white-space: pre-wrap; - background-color: transparent; - border: 0; -} -.pre-scrollable { - max-height: 340px; - overflow-y: scroll; -} -.label, -.badge { - display: inline-block; - padding: 2px 4px; - font-size: 10.998px; - font-weight: bold; - line-height: 14px; - color: #ffffff; - vertical-align: baseline; - white-space: nowrap; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #999999; -} -.label { - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} -.badge { - padding-left: 9px; - padding-right: 9px; - -webkit-border-radius: 9px; - -moz-border-radius: 9px; - border-radius: 9px; -} -.label:empty, -.badge:empty { - display: none; -} -a.label:hover, -a.label:focus, -a.badge:hover, -a.badge:focus { - color: #ffffff; - text-decoration: none; - cursor: pointer; -} -.label-important, -.badge-important { - background-color: #b94a48; -} -.label-important[href], -.badge-important[href] { - background-color: #953b39; -} -.label-warning, -.badge-warning { - background-color: #f89406; -} -.label-warning[href], -.badge-warning[href] { - background-color: #c67605; -} -.label-success, -.badge-success { - background-color: #468847; -} -.label-success[href], -.badge-success[href] { - background-color: #356635; -} -.label-info, -.badge-info { - background-color: #3a87ad; -} -.label-info[href], -.badge-info[href] { - background-color: #2d6987; -} -.label-inverse, -.badge-inverse { - background-color: #333333; -} -.label-inverse[href], -.badge-inverse[href] { - background-color: #1a1a1a; -} -.btn .label, -.btn .badge { - position: relative; - top: -1px; -} -.btn-mini .label, -.btn-mini .badge { - top: 0; -} -table { - max-width: 100%; - background-color: transparent; - border-collapse: collapse; - border-spacing: 0; -} -.table { - width: 100%; - margin-bottom: 20px; -} -.table th, -.table td { - padding: 8px; - line-height: 20px; - text-align: left; - vertical-align: top; - border-top: 1px solid #dddddd; -} -.table th { - font-weight: bold; -} -.table thead th { - vertical-align: bottom; -} -.table caption + thead tr:first-child th, -.table caption + thead tr:first-child td, -.table colgroup + thead tr:first-child th, -.table colgroup + thead tr:first-child td, -.table thead:first-child tr:first-child th, -.table thead:first-child tr:first-child td { - border-top: 0; -} -.table tbody + tbody { - border-top: 2px solid #dddddd; -} -.table .table { - background-color: #ffffff; -} -.table-condensed th, -.table-condensed td { - padding: 4px 5px; -} -.table-bordered { - border: 1px solid #dddddd; - border-collapse: separate; - *border-collapse: collapse; - border-left: 0; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.table-bordered th, -.table-bordered td { - border-left: 1px solid #dddddd; -} -.table-bordered caption + thead tr:first-child th, -.table-bordered caption + tbody tr:first-child th, -.table-bordered caption + tbody tr:first-child td, -.table-bordered colgroup + thead tr:first-child th, -.table-bordered colgroup + tbody tr:first-child th, -.table-bordered colgroup + tbody tr:first-child td, -.table-bordered thead:first-child tr:first-child th, -.table-bordered tbody:first-child tr:first-child th, -.table-bordered tbody:first-child tr:first-child td { - border-top: 0; -} -.table-bordered thead:first-child tr:first-child > th:first-child, -.table-bordered tbody:first-child tr:first-child > td:first-child, -.table-bordered tbody:first-child tr:first-child > th:first-child { - -webkit-border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; - border-top-left-radius: 4px; -} -.table-bordered thead:first-child tr:first-child > th:last-child, -.table-bordered tbody:first-child tr:first-child > td:last-child, -.table-bordered tbody:first-child tr:first-child > th:last-child { - -webkit-border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; - border-top-right-radius: 4px; -} -.table-bordered thead:last-child tr:last-child > th:first-child, -.table-bordered tbody:last-child tr:last-child > td:first-child, -.table-bordered tbody:last-child tr:last-child > th:first-child, -.table-bordered tfoot:last-child tr:last-child > td:first-child, -.table-bordered tfoot:last-child tr:last-child > th:first-child { - -webkit-border-bottom-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - border-bottom-left-radius: 4px; -} -.table-bordered thead:last-child tr:last-child > th:last-child, -.table-bordered tbody:last-child tr:last-child > td:last-child, -.table-bordered tbody:last-child tr:last-child > th:last-child, -.table-bordered tfoot:last-child tr:last-child > td:last-child, -.table-bordered tfoot:last-child tr:last-child > th:last-child { - -webkit-border-bottom-right-radius: 4px; - -moz-border-radius-bottomright: 4px; - border-bottom-right-radius: 4px; -} -.table-bordered tfoot + tbody:last-child tr:last-child td:first-child { - -webkit-border-bottom-left-radius: 0; - -moz-border-radius-bottomleft: 0; - border-bottom-left-radius: 0; -} -.table-bordered tfoot + tbody:last-child tr:last-child td:last-child { - -webkit-border-bottom-right-radius: 0; - -moz-border-radius-bottomright: 0; - border-bottom-right-radius: 0; -} -.table-bordered caption + thead tr:first-child th:first-child, -.table-bordered caption + tbody tr:first-child td:first-child, -.table-bordered colgroup + thead tr:first-child th:first-child, -.table-bordered colgroup + tbody tr:first-child td:first-child { - -webkit-border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; - border-top-left-radius: 4px; -} -.table-bordered caption + thead tr:first-child th:last-child, -.table-bordered caption + tbody tr:first-child td:last-child, -.table-bordered colgroup + thead tr:first-child th:last-child, -.table-bordered colgroup + tbody tr:first-child td:last-child { - -webkit-border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; - border-top-right-radius: 4px; -} -.table-striped tbody > tr:nth-child(odd) > td, -.table-striped tbody > tr:nth-child(odd) > th { - background-color: #f9f9f9; -} -.table-hover tbody tr:hover > td, -.table-hover tbody tr:hover > th { - background-color: #f5f5f5; -} -table td[class*="span"], -table th[class*="span"], -.row-fluid table td[class*="span"], -.row-fluid table th[class*="span"] { - display: table-cell; - float: none; - margin-left: 0; -} -.table td.span1, -.table th.span1 { - float: none; - width: 44px; - margin-left: 0; -} -.table td.span2, -.table th.span2 { - float: none; - width: 124px; - margin-left: 0; -} -.table td.span3, -.table th.span3 { - float: none; - width: 204px; - margin-left: 0; -} -.table td.span4, -.table th.span4 { - float: none; - width: 284px; - margin-left: 0; -} -.table td.span5, -.table th.span5 { - float: none; - width: 364px; - margin-left: 0; -} -.table td.span6, -.table th.span6 { - float: none; - width: 444px; - margin-left: 0; -} -.table td.span7, -.table th.span7 { - float: none; - width: 524px; - margin-left: 0; -} -.table td.span8, -.table th.span8 { - float: none; - width: 604px; - margin-left: 0; -} -.table td.span9, -.table th.span9 { - float: none; - width: 684px; - margin-left: 0; -} -.table td.span10, -.table th.span10 { - float: none; - width: 764px; - margin-left: 0; -} -.table td.span11, -.table th.span11 { - float: none; - width: 844px; - margin-left: 0; -} -.table td.span12, -.table th.span12 { - float: none; - width: 924px; - margin-left: 0; -} -.table tbody tr.success > td { - background-color: #dff0d8; -} -.table tbody tr.error > td { - background-color: #f2dede; -} -.table tbody tr.warning > td { - background-color: #fcf8e3; -} -.table tbody tr.info > td { - background-color: #d9edf7; -} -.table-hover tbody tr.success:hover > td { - background-color: #d0e9c6; -} -.table-hover tbody tr.error:hover > td { - background-color: #ebcccc; -} -.table-hover tbody tr.warning:hover > td { - background-color: #faf2cc; -} -.table-hover tbody tr.info:hover > td { - background-color: #c4e3f3; -} -form { - margin: 0 0 20px; -} -fieldset { - padding: 0; - margin: 0; - border: 0; -} -legend { - display: block; - width: 100%; - padding: 0; - margin-bottom: 20px; - font-size: 19.5px; - line-height: 40px; - color: #333333; - border: 0; - border-bottom: 1px solid #e5e5e5; -} -legend small { - font-size: 15px; - color: #999999; -} -label, -input, -button, -select, -textarea { - font-size: 13px; - font-weight: normal; - line-height: 20px; -} -input, -button, -select, -textarea { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; -} -label { - display: block; - margin-bottom: 5px; -} -select, -textarea, -input[type="text"], -input[type="password"], -input[type="datetime"], -input[type="datetime-local"], -input[type="date"], -input[type="month"], -input[type="time"], -input[type="week"], -input[type="number"], -input[type="email"], -input[type="url"], -input[type="search"], -input[type="tel"], -input[type="color"], -.uneditable-input { - display: inline-block; - height: 20px; - padding: 4px 6px; - margin-bottom: 10px; - font-size: 13px; - line-height: 20px; - color: #555555; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - vertical-align: middle; -} -input, -textarea, -.uneditable-input { - width: 206px; -} -textarea { - height: auto; -} -textarea, -input[type="text"], -input[type="password"], -input[type="datetime"], -input[type="datetime-local"], -input[type="date"], -input[type="month"], -input[type="time"], -input[type="week"], -input[type="number"], -input[type="email"], -input[type="url"], -input[type="search"], -input[type="tel"], -input[type="color"], -.uneditable-input { - background-color: #ffffff; - border: 1px solid #cccccc; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -webkit-transition: border linear .2s, box-shadow linear .2s; - -moz-transition: border linear .2s, box-shadow linear .2s; - -o-transition: border linear .2s, box-shadow linear .2s; - transition: border linear .2s, box-shadow linear .2s; -} -textarea:focus, -input[type="text"]:focus, -input[type="password"]:focus, -input[type="datetime"]:focus, -input[type="datetime-local"]:focus, -input[type="date"]:focus, -input[type="month"]:focus, -input[type="time"]:focus, -input[type="week"]:focus, -input[type="number"]:focus, -input[type="email"]:focus, -input[type="url"]:focus, -input[type="search"]:focus, -input[type="tel"]:focus, -input[type="color"]:focus, -.uneditable-input:focus { - border-color: rgba(82, 168, 236, 0.8); - outline: 0; - outline: thin dotted \9; - /* IE6-9 */ - - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); - -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); - box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); -} -input[type="radio"], -input[type="checkbox"] { - margin: 4px 0 0; - *margin-top: 0; - /* IE7 */ - - margin-top: 1px \9; - /* IE8-9 */ - - line-height: normal; -} -input[type="file"], -input[type="image"], -input[type="submit"], -input[type="reset"], -input[type="button"], -input[type="radio"], -input[type="checkbox"] { - width: auto; -} -select, -input[type="file"] { - height: 30px; - /* In IE7, the height of the select element cannot be changed by height, only font-size */ - - *margin-top: 4px; - /* For IE7, add top margin to align select with labels */ - - line-height: 30px; -} -select { - width: 220px; - border: 1px solid #cccccc; - background-color: #ffffff; -} -select[multiple], -select[size] { - height: auto; -} -select:focus, -input[type="file"]:focus, -input[type="radio"]:focus, -input[type="checkbox"]:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} -.uneditable-input, -.uneditable-textarea { - color: #999999; - background-color: #fcfcfc; - border-color: #cccccc; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.025); - cursor: not-allowed; -} -.uneditable-input { - overflow: hidden; - white-space: nowrap; -} -.uneditable-textarea { - width: auto; - height: auto; -} -input:-moz-placeholder, -textarea:-moz-placeholder { - color: #999999; -} -input:-ms-input-placeholder, -textarea:-ms-input-placeholder { - color: #999999; -} -input::-webkit-input-placeholder, -textarea::-webkit-input-placeholder { - color: #999999; -} -.radio, -.checkbox { - min-height: 20px; - padding-left: 20px; -} -.radio input[type="radio"], -.checkbox input[type="checkbox"] { - float: left; - margin-left: -20px; -} -.controls > .radio:first-child, -.controls > .checkbox:first-child { - padding-top: 5px; -} -.radio.inline, -.checkbox.inline { - display: inline-block; - padding-top: 5px; - margin-bottom: 0; - vertical-align: middle; -} -.radio.inline + .radio.inline, -.checkbox.inline + .checkbox.inline { - margin-left: 10px; -} -.input-mini { - width: 60px; -} -.input-small { - width: 90px; -} -.input-medium { - width: 150px; -} -.input-large { - width: 210px; -} -.input-xlarge { - width: 270px; -} -.input-xxlarge { - width: 530px; -} -input[class*="span"], -select[class*="span"], -textarea[class*="span"], -.uneditable-input[class*="span"], -.row-fluid input[class*="span"], -.row-fluid select[class*="span"], -.row-fluid textarea[class*="span"], -.row-fluid .uneditable-input[class*="span"] { - float: none; - margin-left: 0; -} -.input-append input[class*="span"], -.input-append .uneditable-input[class*="span"], -.input-prepend input[class*="span"], -.input-prepend .uneditable-input[class*="span"], -.row-fluid input[class*="span"], -.row-fluid select[class*="span"], -.row-fluid textarea[class*="span"], -.row-fluid .uneditable-input[class*="span"], -.row-fluid .input-prepend [class*="span"], -.row-fluid .input-append [class*="span"] { - display: inline-block; -} -input, -textarea, -.uneditable-input { - margin-left: 0; -} -.controls-row [class*="span"] + [class*="span"] { - margin-left: 20px; -} -input.span12, -textarea.span12, -.uneditable-input.span12 { - width: 926px; -} -input.span11, -textarea.span11, -.uneditable-input.span11 { - width: 846px; -} -input.span10, -textarea.span10, -.uneditable-input.span10 { - width: 766px; -} -input.span9, -textarea.span9, -.uneditable-input.span9 { - width: 686px; -} -input.span8, -textarea.span8, -.uneditable-input.span8 { - width: 606px; -} -input.span7, -textarea.span7, -.uneditable-input.span7 { - width: 526px; -} -input.span6, -textarea.span6, -.uneditable-input.span6 { - width: 446px; -} -input.span5, -textarea.span5, -.uneditable-input.span5 { - width: 366px; -} -input.span4, -textarea.span4, -.uneditable-input.span4 { - width: 286px; -} -input.span3, -textarea.span3, -.uneditable-input.span3 { - width: 206px; -} -input.span2, -textarea.span2, -.uneditable-input.span2 { - width: 126px; -} -input.span1, -textarea.span1, -.uneditable-input.span1 { - width: 46px; -} -.controls-row { - *zoom: 1; -} -.controls-row:before, -.controls-row:after { - display: table; - content: ""; - line-height: 0; -} -.controls-row:after { - clear: both; -} -.controls-row [class*="span"], -.row-fluid .controls-row [class*="span"] { - float: left; -} -.controls-row .checkbox[class*="span"], -.controls-row .radio[class*="span"] { - padding-top: 5px; -} -input[disabled], -select[disabled], -textarea[disabled], -input[readonly], -select[readonly], -textarea[readonly] { - cursor: not-allowed; - background-color: #eeeeee; -} -input[type="radio"][disabled], -input[type="checkbox"][disabled], -input[type="radio"][readonly], -input[type="checkbox"][readonly] { - background-color: transparent; -} -.control-group.warning .control-label, -.control-group.warning .help-block, -.control-group.warning .help-inline { - color: #c09853; -} -.control-group.warning .checkbox, -.control-group.warning .radio, -.control-group.warning input, -.control-group.warning select, -.control-group.warning textarea { - color: #c09853; -} -.control-group.warning input, -.control-group.warning select, -.control-group.warning textarea { - border-color: #c09853; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -} -.control-group.warning input:focus, -.control-group.warning select:focus, -.control-group.warning textarea:focus { - border-color: #a47e3c; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; -} -.control-group.warning .input-prepend .add-on, -.control-group.warning .input-append .add-on { - color: #c09853; - background-color: #fcf8e3; - border-color: #c09853; -} -.control-group.error .control-label, -.control-group.error .help-block, -.control-group.error .help-inline { - color: #b94a48; -} -.control-group.error .checkbox, -.control-group.error .radio, -.control-group.error input, -.control-group.error select, -.control-group.error textarea { - color: #b94a48; -} -.control-group.error input, -.control-group.error select, -.control-group.error textarea { - border-color: #b94a48; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -} -.control-group.error input:focus, -.control-group.error select:focus, -.control-group.error textarea:focus { - border-color: #953b39; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; -} -.control-group.error .input-prepend .add-on, -.control-group.error .input-append .add-on { - color: #b94a48; - background-color: #f2dede; - border-color: #b94a48; -} -.control-group.success .control-label, -.control-group.success .help-block, -.control-group.success .help-inline { - color: #468847; -} -.control-group.success .checkbox, -.control-group.success .radio, -.control-group.success input, -.control-group.success select, -.control-group.success textarea { - color: #468847; -} -.control-group.success input, -.control-group.success select, -.control-group.success textarea { - border-color: #468847; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -} -.control-group.success input:focus, -.control-group.success select:focus, -.control-group.success textarea:focus { - border-color: #356635; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; -} -.control-group.success .input-prepend .add-on, -.control-group.success .input-append .add-on { - color: #468847; - background-color: #dff0d8; - border-color: #468847; -} -.control-group.info .control-label, -.control-group.info .help-block, -.control-group.info .help-inline { - color: #3a87ad; -} -.control-group.info .checkbox, -.control-group.info .radio, -.control-group.info input, -.control-group.info select, -.control-group.info textarea { - color: #3a87ad; -} -.control-group.info input, -.control-group.info select, -.control-group.info textarea { - border-color: #3a87ad; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -} -.control-group.info input:focus, -.control-group.info select:focus, -.control-group.info textarea:focus { - border-color: #2d6987; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3; -} -.control-group.info .input-prepend .add-on, -.control-group.info .input-append .add-on { - color: #3a87ad; - background-color: #d9edf7; - border-color: #3a87ad; -} -input:focus:invalid, -textarea:focus:invalid, -select:focus:invalid { - color: #b94a48; - border-color: #ee5f5b; -} -input:focus:invalid:focus, -textarea:focus:invalid:focus, -select:focus:invalid:focus { - border-color: #e9322d; - -webkit-box-shadow: 0 0 6px #f8b9b7; - -moz-box-shadow: 0 0 6px #f8b9b7; - box-shadow: 0 0 6px #f8b9b7; -} -.form-actions { - padding: 19px 20px 20px; - margin-top: 20px; - margin-bottom: 20px; - background-color: #f5f5f5; - border-top: 1px solid #e5e5e5; - *zoom: 1; -} -.form-actions:before, -.form-actions:after { - display: table; - content: ""; - line-height: 0; -} -.form-actions:after { - clear: both; -} -.help-block, -.help-inline { - color: #595959; -} -.help-block { - display: block; - margin-bottom: 10px; -} -.help-inline { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - vertical-align: middle; - padding-left: 5px; -} -.input-append, -.input-prepend { - display: inline-block; - margin-bottom: 10px; - vertical-align: middle; - font-size: 0; - white-space: nowrap; -} -.input-append input, -.input-prepend input, -.input-append select, -.input-prepend select, -.input-append .uneditable-input, -.input-prepend .uneditable-input, -.input-append .dropdown-menu, -.input-prepend .dropdown-menu, -.input-append .popover, -.input-prepend .popover { - font-size: 13px; -} -.input-append input, -.input-prepend input, -.input-append select, -.input-prepend select, -.input-append .uneditable-input, -.input-prepend .uneditable-input { - position: relative; - margin-bottom: 0; - *margin-left: 0; - vertical-align: top; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} -.input-append input:focus, -.input-prepend input:focus, -.input-append select:focus, -.input-prepend select:focus, -.input-append .uneditable-input:focus, -.input-prepend .uneditable-input:focus { - z-index: 2; -} -.input-append .add-on, -.input-prepend .add-on { - display: inline-block; - width: auto; - height: 20px; - min-width: 16px; - padding: 4px 5px; - font-size: 13px; - font-weight: normal; - line-height: 20px; - text-align: center; - text-shadow: 0 1px 0 #ffffff; - background-color: #eeeeee; - border: 1px solid #ccc; -} -.input-append .add-on, -.input-prepend .add-on, -.input-append .btn, -.input-prepend .btn, -.input-append .btn-group > .dropdown-toggle, -.input-prepend .btn-group > .dropdown-toggle { - vertical-align: top; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.input-append .active, -.input-prepend .active { - background-color: #a9dba9; - border-color: #46a546; -} -.input-prepend .add-on, -.input-prepend .btn { - margin-right: -1px; -} -.input-prepend .add-on:first-child, -.input-prepend .btn:first-child { - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; -} -.input-append input, -.input-append select, -.input-append .uneditable-input { - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; -} -.input-append input + .btn-group .btn:last-child, -.input-append select + .btn-group .btn:last-child, -.input-append .uneditable-input + .btn-group .btn:last-child { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} -.input-append .add-on, -.input-append .btn, -.input-append .btn-group { - margin-left: -1px; -} -.input-append .add-on:last-child, -.input-append .btn:last-child, -.input-append .btn-group:last-child > .dropdown-toggle { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} -.input-prepend.input-append input, -.input-prepend.input-append select, -.input-prepend.input-append .uneditable-input { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.input-prepend.input-append input + .btn-group .btn, -.input-prepend.input-append select + .btn-group .btn, -.input-prepend.input-append .uneditable-input + .btn-group .btn { - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} -.input-prepend.input-append .add-on:first-child, -.input-prepend.input-append .btn:first-child { - margin-right: -1px; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; -} -.input-prepend.input-append .add-on:last-child, -.input-prepend.input-append .btn:last-child { - margin-left: -1px; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} -.input-prepend.input-append .btn-group:first-child { - margin-left: 0; -} -input.search-query { - padding-right: 14px; - padding-right: 4px \9; - padding-left: 14px; - padding-left: 4px \9; - /* IE7-8 doesn't have border-radius, so don't indent the padding */ - - margin-bottom: 0; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; -} -/* Allow for input prepend/append in search forms */ -.form-search .input-append .search-query, -.form-search .input-prepend .search-query { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.form-search .input-append .search-query { - -webkit-border-radius: 14px 0 0 14px; - -moz-border-radius: 14px 0 0 14px; - border-radius: 14px 0 0 14px; -} -.form-search .input-append .btn { - -webkit-border-radius: 0 14px 14px 0; - -moz-border-radius: 0 14px 14px 0; - border-radius: 0 14px 14px 0; -} -.form-search .input-prepend .search-query { - -webkit-border-radius: 0 14px 14px 0; - -moz-border-radius: 0 14px 14px 0; - border-radius: 0 14px 14px 0; -} -.form-search .input-prepend .btn { - -webkit-border-radius: 14px 0 0 14px; - -moz-border-radius: 14px 0 0 14px; - border-radius: 14px 0 0 14px; -} -.form-search input, -.form-inline input, -.form-horizontal input, -.form-search textarea, -.form-inline textarea, -.form-horizontal textarea, -.form-search select, -.form-inline select, -.form-horizontal select, -.form-search .help-inline, -.form-inline .help-inline, -.form-horizontal .help-inline, -.form-search .uneditable-input, -.form-inline .uneditable-input, -.form-horizontal .uneditable-input, -.form-search .input-prepend, -.form-inline .input-prepend, -.form-horizontal .input-prepend, -.form-search .input-append, -.form-inline .input-append, -.form-horizontal .input-append { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - margin-bottom: 0; - vertical-align: middle; -} -.form-search .hide, -.form-inline .hide, -.form-horizontal .hide { - display: none; -} -.form-search label, -.form-inline label, -.form-search .btn-group, -.form-inline .btn-group { - display: inline-block; -} -.form-search .input-append, -.form-inline .input-append, -.form-search .input-prepend, -.form-inline .input-prepend { - margin-bottom: 0; -} -.form-search .radio, -.form-search .checkbox, -.form-inline .radio, -.form-inline .checkbox { - padding-left: 0; - margin-bottom: 0; - vertical-align: middle; -} -.form-search .radio input[type="radio"], -.form-search .checkbox input[type="checkbox"], -.form-inline .radio input[type="radio"], -.form-inline .checkbox input[type="checkbox"] { - float: left; - margin-right: 3px; - margin-left: 0; -} -.control-group { - margin-bottom: 10px; -} -legend + .control-group { - margin-top: 20px; - -webkit-margin-top-collapse: separate; -} -.form-horizontal .control-group { - margin-bottom: 20px; - *zoom: 1; -} -.form-horizontal .control-group:before, -.form-horizontal .control-group:after { - display: table; - content: ""; - line-height: 0; -} -.form-horizontal .control-group:after { - clear: both; -} -.form-horizontal .control-label { - float: left; - width: 160px; - padding-top: 5px; - text-align: right; -} -.form-horizontal .controls { - *display: inline-block; - *padding-left: 20px; - margin-left: 180px; - *margin-left: 0; -} -.form-horizontal .controls:first-child { - *padding-left: 180px; -} -.form-horizontal .help-block { - margin-bottom: 0; -} -.form-horizontal input + .help-block, -.form-horizontal select + .help-block, -.form-horizontal textarea + .help-block, -.form-horizontal .uneditable-input + .help-block, -.form-horizontal .input-prepend + .help-block, -.form-horizontal .input-append + .help-block { - margin-top: 10px; -} -.form-horizontal .form-actions { - padding-left: 180px; -} -.btn { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - padding: 4px 12px; - margin-bottom: 0; - font-size: 13px; - line-height: 20px; - text-align: center; - vertical-align: middle; - cursor: pointer; - color: #333333; - text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); - background-color: #f5f5f5; - background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); - background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); - background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); - background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); - border-color: #e6e6e6 #e6e6e6 #bfbfbf; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #e6e6e6; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); - border: 1px solid #cccccc; - *border: 0; - border-bottom-color: #b3b3b3; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - *margin-left: .3em; - -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); - -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); - box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); -} -.btn:hover, -.btn:focus, -.btn:active, -.btn.active, -.btn.disabled, -.btn[disabled] { - color: #333333; - background-color: #e6e6e6; - *background-color: #d9d9d9; -} -.btn:active, -.btn.active { - background-color: #cccccc \9; -} -.btn:first-child { - *margin-left: 0; -} -.btn:hover, -.btn:focus { - color: #333333; - text-decoration: none; - background-position: 0 -15px; - -webkit-transition: background-position 0.1s linear; - -moz-transition: background-position 0.1s linear; - -o-transition: background-position 0.1s linear; - transition: background-position 0.1s linear; -} -.btn:focus { - outline: thin dotted #333; - outline: 5px auto -webkit-focus-ring-color; - outline-offset: -2px; -} -.btn.active, -.btn:active { - background-image: none; - outline: 0; - -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); - -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); - box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -} -.btn.disabled, -.btn[disabled] { - cursor: default; - background-image: none; - opacity: 0.65; - filter: alpha(opacity=65); - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; -} -.btn-large { - padding: 11px 19px; - font-size: 16.25px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} -.btn-large [class^="icon-"], -.btn-large [class*=" icon-"] { - margin-top: 4px; -} -.btn-small { - padding: 2px 10px; - font-size: 11.049999999999999px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} -.btn-small [class^="icon-"], -.btn-small [class*=" icon-"] { - margin-top: 0; -} -.btn-mini [class^="icon-"], -.btn-mini [class*=" icon-"] { - margin-top: -1px; -} -.btn-mini { - padding: 0 6px; - font-size: 9.75px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} -.btn-block { - display: block; - width: 100%; - padding-left: 0; - padding-right: 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; -} -.btn-block + .btn-block { - margin-top: 5px; -} -input[type="submit"].btn-block, -input[type="reset"].btn-block, -input[type="button"].btn-block { - width: 100%; -} -.btn-primary.active, -.btn-warning.active, -.btn-danger.active, -.btn-success.active, -.btn-info.active, -.btn-inverse.active { - color: rgba(255, 255, 255, 0.75); -} -.btn-primary { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #006dcc; - background-image: -moz-linear-gradient(top, #0088cc, #0044cc); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); - background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); - background-image: -o-linear-gradient(top, #0088cc, #0044cc); - background-image: linear-gradient(to bottom, #0088cc, #0044cc); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0); - border-color: #0044cc #0044cc #002a80; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #0044cc; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.btn-primary:hover, -.btn-primary:focus, -.btn-primary:active, -.btn-primary.active, -.btn-primary.disabled, -.btn-primary[disabled] { - color: #ffffff; - background-color: #0044cc; - *background-color: #003bb3; -} -.btn-primary:active, -.btn-primary.active { - background-color: #003399 \9; -} -.btn-warning { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #faa732; - background-image: -moz-linear-gradient(top, #fbb450, #f89406); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); - background-image: -webkit-linear-gradient(top, #fbb450, #f89406); - background-image: -o-linear-gradient(top, #fbb450, #f89406); - background-image: linear-gradient(to bottom, #fbb450, #f89406); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); - border-color: #f89406 #f89406 #ad6704; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #f89406; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.btn-warning:hover, -.btn-warning:focus, -.btn-warning:active, -.btn-warning.active, -.btn-warning.disabled, -.btn-warning[disabled] { - color: #ffffff; - background-color: #f89406; - *background-color: #df8505; -} -.btn-warning:active, -.btn-warning.active { - background-color: #c67605 \9; -} -.btn-danger { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #da4f49; - background-image: -moz-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f)); - background-image: -webkit-linear-gradient(top, #ee5f5b, #bd362f); - background-image: -o-linear-gradient(top, #ee5f5b, #bd362f); - background-image: linear-gradient(to bottom, #ee5f5b, #bd362f); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0); - border-color: #bd362f #bd362f #802420; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #bd362f; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.btn-danger:hover, -.btn-danger:focus, -.btn-danger:active, -.btn-danger.active, -.btn-danger.disabled, -.btn-danger[disabled] { - color: #ffffff; - background-color: #bd362f; - *background-color: #a9302a; -} -.btn-danger:active, -.btn-danger.active { - background-color: #942a25 \9; -} -.btn-success { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #5bb75b; - background-image: -moz-linear-gradient(top, #62c462, #51a351); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351)); - background-image: -webkit-linear-gradient(top, #62c462, #51a351); - background-image: -o-linear-gradient(top, #62c462, #51a351); - background-image: linear-gradient(to bottom, #62c462, #51a351); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0); - border-color: #51a351 #51a351 #387038; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #51a351; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.btn-success:hover, -.btn-success:focus, -.btn-success:active, -.btn-success.active, -.btn-success.disabled, -.btn-success[disabled] { - color: #ffffff; - background-color: #51a351; - *background-color: #499249; -} -.btn-success:active, -.btn-success.active { - background-color: #408140 \9; -} -.btn-info { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #49afcd; - background-image: -moz-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4)); - background-image: -webkit-linear-gradient(top, #5bc0de, #2f96b4); - background-image: -o-linear-gradient(top, #5bc0de, #2f96b4); - background-image: linear-gradient(to bottom, #5bc0de, #2f96b4); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0); - border-color: #2f96b4 #2f96b4 #1f6377; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #2f96b4; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.btn-info:hover, -.btn-info:focus, -.btn-info:active, -.btn-info.active, -.btn-info.disabled, -.btn-info[disabled] { - color: #ffffff; - background-color: #2f96b4; - *background-color: #2a85a0; -} -.btn-info:active, -.btn-info.active { - background-color: #24748c \9; -} -.btn-inverse { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #363636; - background-image: -moz-linear-gradient(top, #444444, #222222); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222)); - background-image: -webkit-linear-gradient(top, #444444, #222222); - background-image: -o-linear-gradient(top, #444444, #222222); - background-image: linear-gradient(to bottom, #444444, #222222); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0); - border-color: #222222 #222222 #000000; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #222222; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.btn-inverse:hover, -.btn-inverse:focus, -.btn-inverse:active, -.btn-inverse.active, -.btn-inverse.disabled, -.btn-inverse[disabled] { - color: #ffffff; - background-color: #222222; - *background-color: #151515; -} -.btn-inverse:active, -.btn-inverse.active { - background-color: #080808 \9; -} -button.btn, -input[type="submit"].btn { - *padding-top: 3px; - *padding-bottom: 3px; -} -button.btn::-moz-focus-inner, -input[type="submit"].btn::-moz-focus-inner { - padding: 0; - border: 0; -} -button.btn.btn-large, -input[type="submit"].btn.btn-large { - *padding-top: 7px; - *padding-bottom: 7px; -} -button.btn.btn-small, -input[type="submit"].btn.btn-small { - *padding-top: 3px; - *padding-bottom: 3px; -} -button.btn.btn-mini, -input[type="submit"].btn.btn-mini { - *padding-top: 1px; - *padding-bottom: 1px; -} -.btn-link, -.btn-link:active, -.btn-link[disabled] { - background-color: transparent; - background-image: none; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; -} -.btn-link { - border-color: transparent; - cursor: pointer; - color: #0088cc; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.btn-link:hover, -.btn-link:focus { - color: #005580; - text-decoration: underline; - background-color: transparent; -} -.btn-link[disabled]:hover, -.btn-link[disabled]:focus { - color: #333333; - text-decoration: none; -} -[class^="icon-"], -[class*=" icon-"] { - display: inline-block; - width: 14px; - height: 14px; - *margin-right: .3em; - line-height: 14px; - vertical-align: text-top; - background-image: url("../img/glyphicons-halflings.png"); - background-position: 14px 14px; - background-repeat: no-repeat; - margin-top: 1px; -} -/* White icons with optional class, or on hover/focus/active states of certain elements */ -.icon-white, -.nav-pills > .active > a > [class^="icon-"], -.nav-pills > .active > a > [class*=" icon-"], -.nav-list > .active > a > [class^="icon-"], -.nav-list > .active > a > [class*=" icon-"], -.navbar-inverse .nav > .active > a > [class^="icon-"], -.navbar-inverse .nav > .active > a > [class*=" icon-"], -.dropdown-menu > li > a:hover > [class^="icon-"], -.dropdown-menu > li > a:focus > [class^="icon-"], -.dropdown-menu > li > a:hover > [class*=" icon-"], -.dropdown-menu > li > a:focus > [class*=" icon-"], -.dropdown-menu > .active > a > [class^="icon-"], -.dropdown-menu > .active > a > [class*=" icon-"], -.dropdown-submenu:hover > a > [class^="icon-"], -.dropdown-submenu:focus > a > [class^="icon-"], -.dropdown-submenu:hover > a > [class*=" icon-"], -.dropdown-submenu:focus > a > [class*=" icon-"] { - background-image: url("../img/glyphicons-halflings-white.png"); -} -.icon-glass { - background-position: 0 0; -} -.icon-music { - background-position: -24px 0; -} -.icon-search { - background-position: -48px 0; -} -.icon-envelope { - background-position: -72px 0; -} -.icon-heart { - background-position: -96px 0; -} -.icon-star { - background-position: -120px 0; -} -.icon-star-empty { - background-position: -144px 0; -} -.icon-user { - background-position: -168px 0; -} -.icon-film { - background-position: -192px 0; -} -.icon-th-large { - background-position: -216px 0; -} -.icon-th { - background-position: -240px 0; -} -.icon-th-list { - background-position: -264px 0; -} -.icon-ok { - background-position: -288px 0; -} -.icon-remove { - background-position: -312px 0; -} -.icon-zoom-in { - background-position: -336px 0; -} -.icon-zoom-out { - background-position: -360px 0; -} -.icon-off { - background-position: -384px 0; -} -.icon-signal { - background-position: -408px 0; -} -.icon-cog { - background-position: -432px 0; -} -.icon-trash { - background-position: -456px 0; -} -.icon-home { - background-position: 0 -24px; -} -.icon-file { - background-position: -24px -24px; -} -.icon-time { - background-position: -48px -24px; -} -.icon-road { - background-position: -72px -24px; -} -.icon-download-alt { - background-position: -96px -24px; -} -.icon-download { - background-position: -120px -24px; -} -.icon-upload { - background-position: -144px -24px; -} -.icon-inbox { - background-position: -168px -24px; -} -.icon-play-circle { - background-position: -192px -24px; -} -.icon-repeat { - background-position: -216px -24px; -} -.icon-refresh { - background-position: -240px -24px; -} -.icon-list-alt { - background-position: -264px -24px; -} -.icon-lock { - background-position: -287px -24px; -} -.icon-flag { - background-position: -312px -24px; -} -.icon-headphones { - background-position: -336px -24px; -} -.icon-volume-off { - background-position: -360px -24px; -} -.icon-volume-down { - background-position: -384px -24px; -} -.icon-volume-up { - background-position: -408px -24px; -} -.icon-qrcode { - background-position: -432px -24px; -} -.icon-barcode { - background-position: -456px -24px; -} -.icon-tag { - background-position: 0 -48px; -} -.icon-tags { - background-position: -25px -48px; -} -.icon-book { - background-position: -48px -48px; -} -.icon-bookmark { - background-position: -72px -48px; -} -.icon-print { - background-position: -96px -48px; -} -.icon-camera { - background-position: -120px -48px; -} -.icon-font { - background-position: -144px -48px; -} -.icon-bold { - background-position: -167px -48px; -} -.icon-italic { - background-position: -192px -48px; -} -.icon-text-height { - background-position: -216px -48px; -} -.icon-text-width { - background-position: -240px -48px; -} -.icon-align-left { - background-position: -264px -48px; -} -.icon-align-center { - background-position: -288px -48px; -} -.icon-align-right { - background-position: -312px -48px; -} -.icon-align-justify { - background-position: -336px -48px; -} -.icon-list { - background-position: -360px -48px; -} -.icon-indent-left { - background-position: -384px -48px; -} -.icon-indent-right { - background-position: -408px -48px; -} -.icon-facetime-video { - background-position: -432px -48px; -} -.icon-picture { - background-position: -456px -48px; -} -.icon-pencil { - background-position: 0 -72px; -} -.icon-map-marker { - background-position: -24px -72px; -} -.icon-adjust { - background-position: -48px -72px; -} -.icon-tint { - background-position: -72px -72px; -} -.icon-edit { - background-position: -96px -72px; -} -.icon-share { - background-position: -120px -72px; -} -.icon-check { - background-position: -144px -72px; -} -.icon-move { - background-position: -168px -72px; -} -.icon-step-backward { - background-position: -192px -72px; -} -.icon-fast-backward { - background-position: -216px -72px; -} -.icon-backward { - background-position: -240px -72px; -} -.icon-play { - background-position: -264px -72px; -} -.icon-pause { - background-position: -288px -72px; -} -.icon-stop { - background-position: -312px -72px; -} -.icon-forward { - background-position: -336px -72px; -} -.icon-fast-forward { - background-position: -360px -72px; -} -.icon-step-forward { - background-position: -384px -72px; -} -.icon-eject { - background-position: -408px -72px; -} -.icon-chevron-left { - background-position: -432px -72px; -} -.icon-chevron-right { - background-position: -456px -72px; -} -.icon-plus-sign { - background-position: 0 -96px; -} -.icon-minus-sign { - background-position: -24px -96px; -} -.icon-remove-sign { - background-position: -48px -96px; -} -.icon-ok-sign { - background-position: -72px -96px; -} -.icon-question-sign { - background-position: -96px -96px; -} -.icon-info-sign { - background-position: -120px -96px; -} -.icon-screenshot { - background-position: -144px -96px; -} -.icon-remove-circle { - background-position: -168px -96px; -} -.icon-ok-circle { - background-position: -192px -96px; -} -.icon-ban-circle { - background-position: -216px -96px; -} -.icon-arrow-left { - background-position: -240px -96px; -} -.icon-arrow-right { - background-position: -264px -96px; -} -.icon-arrow-up { - background-position: -289px -96px; -} -.icon-arrow-down { - background-position: -312px -96px; -} -.icon-share-alt { - background-position: -336px -96px; -} -.icon-resize-full { - background-position: -360px -96px; -} -.icon-resize-small { - background-position: -384px -96px; -} -.icon-plus { - background-position: -408px -96px; -} -.icon-minus { - background-position: -433px -96px; -} -.icon-asterisk { - background-position: -456px -96px; -} -.icon-exclamation-sign { - background-position: 0 -120px; -} -.icon-gift { - background-position: -24px -120px; -} -.icon-leaf { - background-position: -48px -120px; -} -.icon-fire { - background-position: -72px -120px; -} -.icon-eye-open { - background-position: -96px -120px; -} -.icon-eye-close { - background-position: -120px -120px; -} -.icon-warning-sign { - background-position: -144px -120px; -} -.icon-plane { - background-position: -168px -120px; -} -.icon-calendar { - background-position: -192px -120px; -} -.icon-random { - background-position: -216px -120px; - width: 16px; -} -.icon-comment { - background-position: -240px -120px; -} -.icon-magnet { - background-position: -264px -120px; -} -.icon-chevron-up { - background-position: -288px -120px; -} -.icon-chevron-down { - background-position: -313px -119px; -} -.icon-retweet { - background-position: -336px -120px; -} -.icon-shopping-cart { - background-position: -360px -120px; -} -.icon-folder-close { - background-position: -384px -120px; - width: 16px; -} -.icon-folder-open { - background-position: -408px -120px; - width: 16px; -} -.icon-resize-vertical { - background-position: -432px -119px; -} -.icon-resize-horizontal { - background-position: -456px -118px; -} -.icon-hdd { - background-position: 0 -144px; -} -.icon-bullhorn { - background-position: -24px -144px; -} -.icon-bell { - background-position: -48px -144px; -} -.icon-certificate { - background-position: -72px -144px; -} -.icon-thumbs-up { - background-position: -96px -144px; -} -.icon-thumbs-down { - background-position: -120px -144px; -} -.icon-hand-right { - background-position: -144px -144px; -} -.icon-hand-left { - background-position: -168px -144px; -} -.icon-hand-up { - background-position: -192px -144px; -} -.icon-hand-down { - background-position: -216px -144px; -} -.icon-circle-arrow-right { - background-position: -240px -144px; -} -.icon-circle-arrow-left { - background-position: -264px -144px; -} -.icon-circle-arrow-up { - background-position: -288px -144px; -} -.icon-circle-arrow-down { - background-position: -312px -144px; -} -.icon-globe { - background-position: -336px -144px; -} -.icon-wrench { - background-position: -360px -144px; -} -.icon-tasks { - background-position: -384px -144px; -} -.icon-filter { - background-position: -408px -144px; -} -.icon-briefcase { - background-position: -432px -144px; -} -.icon-fullscreen { - background-position: -456px -144px; -} -.btn-group { - position: relative; - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - font-size: 0; - vertical-align: middle; - white-space: nowrap; - *margin-left: .3em; -} -.btn-group:first-child { - *margin-left: 0; -} -.btn-group + .btn-group { - margin-left: 5px; -} -.btn-toolbar { - font-size: 0; - margin-top: 10px; - margin-bottom: 10px; -} -.btn-toolbar > .btn + .btn, -.btn-toolbar > .btn-group + .btn, -.btn-toolbar > .btn + .btn-group { - margin-left: 5px; -} -.btn-group > .btn { - position: relative; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.btn-group > .btn + .btn { - margin-left: -1px; -} -.btn-group > .btn, -.btn-group > .dropdown-menu, -.btn-group > .popover { - font-size: 13px; -} -.btn-group > .btn-mini { - font-size: 9.75px; -} -.btn-group > .btn-small { - font-size: 11.049999999999999px; -} -.btn-group > .btn-large { - font-size: 16.25px; -} -.btn-group > .btn:first-child { - margin-left: 0; - -webkit-border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; - border-top-left-radius: 4px; - -webkit-border-bottom-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - border-bottom-left-radius: 4px; -} -.btn-group > .btn:last-child, -.btn-group > .dropdown-toggle { - -webkit-border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; - border-top-right-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - -moz-border-radius-bottomright: 4px; - border-bottom-right-radius: 4px; -} -.btn-group > .btn.large:first-child { - margin-left: 0; - -webkit-border-top-left-radius: 6px; - -moz-border-radius-topleft: 6px; - border-top-left-radius: 6px; - -webkit-border-bottom-left-radius: 6px; - -moz-border-radius-bottomleft: 6px; - border-bottom-left-radius: 6px; -} -.btn-group > .btn.large:last-child, -.btn-group > .large.dropdown-toggle { - -webkit-border-top-right-radius: 6px; - -moz-border-radius-topright: 6px; - border-top-right-radius: 6px; - -webkit-border-bottom-right-radius: 6px; - -moz-border-radius-bottomright: 6px; - border-bottom-right-radius: 6px; -} -.btn-group > .btn:hover, -.btn-group > .btn:focus, -.btn-group > .btn:active, -.btn-group > .btn.active { - z-index: 2; -} -.btn-group .dropdown-toggle:active, -.btn-group.open .dropdown-toggle { - outline: 0; -} -.btn-group > .btn + .dropdown-toggle { - padding-left: 8px; - padding-right: 8px; - -webkit-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); - -moz-box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); - box-shadow: inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); - *padding-top: 5px; - *padding-bottom: 5px; -} -.btn-group > .btn-mini + .dropdown-toggle { - padding-left: 5px; - padding-right: 5px; - *padding-top: 2px; - *padding-bottom: 2px; -} -.btn-group > .btn-small + .dropdown-toggle { - *padding-top: 5px; - *padding-bottom: 4px; -} -.btn-group > .btn-large + .dropdown-toggle { - padding-left: 12px; - padding-right: 12px; - *padding-top: 7px; - *padding-bottom: 7px; -} -.btn-group.open .dropdown-toggle { - background-image: none; - -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); - -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); - box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -} -.btn-group.open .btn.dropdown-toggle { - background-color: #e6e6e6; -} -.btn-group.open .btn-primary.dropdown-toggle { - background-color: #0044cc; -} -.btn-group.open .btn-warning.dropdown-toggle { - background-color: #f89406; -} -.btn-group.open .btn-danger.dropdown-toggle { - background-color: #bd362f; -} -.btn-group.open .btn-success.dropdown-toggle { - background-color: #51a351; -} -.btn-group.open .btn-info.dropdown-toggle { - background-color: #2f96b4; -} -.btn-group.open .btn-inverse.dropdown-toggle { - background-color: #222222; -} -.btn .caret { - margin-top: 8px; - margin-left: 0; -} -.btn-large .caret { - margin-top: 6px; -} -.btn-large .caret { - border-left-width: 5px; - border-right-width: 5px; - border-top-width: 5px; -} -.btn-mini .caret, -.btn-small .caret { - margin-top: 8px; -} -.dropup .btn-large .caret { - border-bottom-width: 5px; -} -.btn-primary .caret, -.btn-warning .caret, -.btn-danger .caret, -.btn-info .caret, -.btn-success .caret, -.btn-inverse .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; -} -.btn-group-vertical { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; -} -.btn-group-vertical > .btn { - display: block; - float: none; - max-width: 100%; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.btn-group-vertical > .btn + .btn { - margin-left: 0; - margin-top: -1px; -} -.btn-group-vertical > .btn:first-child { - -webkit-border-radius: 4px 4px 0 0; - -moz-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; -} -.btn-group-vertical > .btn:last-child { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius: 0 0 4px 4px; - border-radius: 0 0 4px 4px; -} -.btn-group-vertical > .btn-large:first-child { - -webkit-border-radius: 6px 6px 0 0; - -moz-border-radius: 6px 6px 0 0; - border-radius: 6px 6px 0 0; -} -.btn-group-vertical > .btn-large:last-child { - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; -} -.nav { - margin-left: 0; - margin-bottom: 20px; - list-style: none; -} -.nav > li > a { - display: block; -} -.nav > li > a:hover, -.nav > li > a:focus { - text-decoration: none; - background-color: #eeeeee; -} -.nav > li > a > img { - max-width: none; -} -.nav > .pull-right { - float: right; -} -.nav-header { - display: block; - padding: 3px 15px; - font-size: 11px; - font-weight: bold; - line-height: 20px; - color: #999999; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); - text-transform: uppercase; -} -.nav li + .nav-header { - margin-top: 9px; -} -.nav-list { - padding-left: 15px; - padding-right: 15px; - margin-bottom: 0; -} -.nav-list > li > a, -.nav-list .nav-header { - margin-left: -15px; - margin-right: -15px; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); -} -.nav-list > li > a { - padding: 3px 15px; -} -.nav-list > .active > a, -.nav-list > .active > a:hover, -.nav-list > .active > a:focus { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); - background-color: #0088cc; -} -.nav-list [class^="icon-"], -.nav-list [class*=" icon-"] { - margin-right: 2px; -} -.nav-list .divider { - *width: 100%; - height: 1px; - margin: 9px 1px; - *margin: -5px 0 5px; - overflow: hidden; - background-color: #e5e5e5; - border-bottom: 1px solid #ffffff; -} -.nav-tabs, -.nav-pills { - *zoom: 1; -} -.nav-tabs:before, -.nav-pills:before, -.nav-tabs:after, -.nav-pills:after { - display: table; - content: ""; - line-height: 0; -} -.nav-tabs:after, -.nav-pills:after { - clear: both; -} -.nav-tabs > li, -.nav-pills > li { - float: left; -} -.nav-tabs > li > a, -.nav-pills > li > a { - padding-right: 12px; - padding-left: 12px; - margin-right: 2px; - line-height: 14px; -} -.nav-tabs { - border-bottom: 1px solid #ddd; -} -.nav-tabs > li { - margin-bottom: -1px; -} -.nav-tabs > li > a { - padding-top: 8px; - padding-bottom: 8px; - line-height: 20px; - border: 1px solid transparent; - -webkit-border-radius: 4px 4px 0 0; - -moz-border-radius: 4px 4px 0 0; - border-radius: 4px 4px 0 0; -} -.nav-tabs > li > a:hover, -.nav-tabs > li > a:focus { - border-color: #eeeeee #eeeeee #dddddd; -} -.nav-tabs > .active > a, -.nav-tabs > .active > a:hover, -.nav-tabs > .active > a:focus { - color: #555555; - background-color: #ffffff; - border: 1px solid #ddd; - border-bottom-color: transparent; - cursor: default; -} -.nav-pills > li > a { - padding-top: 8px; - padding-bottom: 8px; - margin-top: 2px; - margin-bottom: 2px; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; -} -.nav-pills > .active > a, -.nav-pills > .active > a:hover, -.nav-pills > .active > a:focus { - color: #ffffff; - background-color: #0088cc; -} -.nav-stacked > li { - float: none; -} -.nav-stacked > li > a { - margin-right: 0; -} -.nav-tabs.nav-stacked { - border-bottom: 0; -} -.nav-tabs.nav-stacked > li > a { - border: 1px solid #ddd; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.nav-tabs.nav-stacked > li:first-child > a { - -webkit-border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; - border-top-right-radius: 4px; - -webkit-border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; - border-top-left-radius: 4px; -} -.nav-tabs.nav-stacked > li:last-child > a { - -webkit-border-bottom-right-radius: 4px; - -moz-border-radius-bottomright: 4px; - border-bottom-right-radius: 4px; - -webkit-border-bottom-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - border-bottom-left-radius: 4px; -} -.nav-tabs.nav-stacked > li > a:hover, -.nav-tabs.nav-stacked > li > a:focus { - border-color: #ddd; - z-index: 2; -} -.nav-pills.nav-stacked > li > a { - margin-bottom: 3px; -} -.nav-pills.nav-stacked > li:last-child > a { - margin-bottom: 1px; -} -.nav-tabs .dropdown-menu { - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; -} -.nav-pills .dropdown-menu { - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} -.nav .dropdown-toggle .caret { - border-top-color: #0088cc; - border-bottom-color: #0088cc; - margin-top: 6px; -} -.nav .dropdown-toggle:hover .caret, -.nav .dropdown-toggle:focus .caret { - border-top-color: #005580; - border-bottom-color: #005580; -} -/* move down carets for tabs */ -.nav-tabs .dropdown-toggle .caret { - margin-top: 8px; -} -.nav .active .dropdown-toggle .caret { - border-top-color: #fff; - border-bottom-color: #fff; -} -.nav-tabs .active .dropdown-toggle .caret { - border-top-color: #555555; - border-bottom-color: #555555; -} -.nav > .dropdown.active > a:hover, -.nav > .dropdown.active > a:focus { - cursor: pointer; -} -.nav-tabs .open .dropdown-toggle, -.nav-pills .open .dropdown-toggle, -.nav > li.dropdown.open.active > a:hover, -.nav > li.dropdown.open.active > a:focus { - color: #ffffff; - background-color: #999999; - border-color: #999999; -} -.nav li.dropdown.open .caret, -.nav li.dropdown.open.active .caret, -.nav li.dropdown.open a:hover .caret, -.nav li.dropdown.open a:focus .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; - opacity: 1; - filter: alpha(opacity=100); -} -.tabs-stacked .open > a:hover, -.tabs-stacked .open > a:focus { - border-color: #999999; -} -.tabbable { - *zoom: 1; -} -.tabbable:before, -.tabbable:after { - display: table; - content: ""; - line-height: 0; -} -.tabbable:after { - clear: both; -} -.tab-content { - overflow: auto; -} -.tabs-below > .nav-tabs, -.tabs-right > .nav-tabs, -.tabs-left > .nav-tabs { - border-bottom: 0; -} -.tab-content > .tab-pane, -.pill-content > .pill-pane { - display: none; -} -.tab-content > .active, -.pill-content > .active { - display: block; -} -.tabs-below > .nav-tabs { - border-top: 1px solid #ddd; -} -.tabs-below > .nav-tabs > li { - margin-top: -1px; - margin-bottom: 0; -} -.tabs-below > .nav-tabs > li > a { - -webkit-border-radius: 0 0 4px 4px; - -moz-border-radius: 0 0 4px 4px; - border-radius: 0 0 4px 4px; -} -.tabs-below > .nav-tabs > li > a:hover, -.tabs-below > .nav-tabs > li > a:focus { - border-bottom-color: transparent; - border-top-color: #ddd; -} -.tabs-below > .nav-tabs > .active > a, -.tabs-below > .nav-tabs > .active > a:hover, -.tabs-below > .nav-tabs > .active > a:focus { - border-color: transparent #ddd #ddd #ddd; -} -.tabs-left > .nav-tabs > li, -.tabs-right > .nav-tabs > li { - float: none; -} -.tabs-left > .nav-tabs > li > a, -.tabs-right > .nav-tabs > li > a { - min-width: 74px; - margin-right: 0; - margin-bottom: 3px; -} -.tabs-left > .nav-tabs { - float: left; - margin-right: 19px; - border-right: 1px solid #ddd; -} -.tabs-left > .nav-tabs > li > a { - margin-right: -1px; - -webkit-border-radius: 4px 0 0 4px; - -moz-border-radius: 4px 0 0 4px; - border-radius: 4px 0 0 4px; -} -.tabs-left > .nav-tabs > li > a:hover, -.tabs-left > .nav-tabs > li > a:focus { - border-color: #eeeeee #dddddd #eeeeee #eeeeee; -} -.tabs-left > .nav-tabs .active > a, -.tabs-left > .nav-tabs .active > a:hover, -.tabs-left > .nav-tabs .active > a:focus { - border-color: #ddd transparent #ddd #ddd; - *border-right-color: #ffffff; -} -.tabs-right > .nav-tabs { - float: right; - margin-left: 19px; - border-left: 1px solid #ddd; -} -.tabs-right > .nav-tabs > li > a { - margin-left: -1px; - -webkit-border-radius: 0 4px 4px 0; - -moz-border-radius: 0 4px 4px 0; - border-radius: 0 4px 4px 0; -} -.tabs-right > .nav-tabs > li > a:hover, -.tabs-right > .nav-tabs > li > a:focus { - border-color: #eeeeee #eeeeee #eeeeee #dddddd; -} -.tabs-right > .nav-tabs .active > a, -.tabs-right > .nav-tabs .active > a:hover, -.tabs-right > .nav-tabs .active > a:focus { - border-color: #ddd #ddd #ddd transparent; - *border-left-color: #ffffff; -} -.nav > .disabled > a { - color: #999999; -} -.nav > .disabled > a:hover, -.nav > .disabled > a:focus { - text-decoration: none; - background-color: transparent; - cursor: default; -} -.navbar { - overflow: visible; - margin-bottom: 20px; - *position: relative; - *z-index: 2; -} -.navbar-inner { - min-height: 40px; - padding-left: 20px; - padding-right: 20px; - background-color: #fafafa; - background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); - background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); - background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); - background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0); - border: 1px solid #d4d4d4; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); - -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); - box-shadow: 0 1px 4px rgba(0, 0, 0, 0.065); - *zoom: 1; -} -.navbar-inner:before, -.navbar-inner:after { - display: table; - content: ""; - line-height: 0; -} -.navbar-inner:after { - clear: both; -} -.navbar .container { - width: auto; -} -.nav-collapse.collapse { - height: auto; - overflow: visible; -} -.navbar .brand { - float: left; - display: block; - padding: 10px 20px 10px; - margin-left: -20px; - font-size: 20px; - font-weight: 200; - color: #777777; - text-shadow: 0 1px 0 #ffffff; -} -.navbar .brand:hover, -.navbar .brand:focus { - text-decoration: none; -} -.navbar-text { - margin-bottom: 0; - line-height: 40px; - color: #777777; -} -.navbar-link { - color: #777777; -} -.navbar-link:hover, -.navbar-link:focus { - color: #333333; -} -.navbar .divider-vertical { - height: 40px; - margin: 0 9px; - border-left: 1px solid #f2f2f2; - border-right: 1px solid #ffffff; -} -.navbar .btn, -.navbar .btn-group { - margin-top: 5px; -} -.navbar .btn-group .btn, -.navbar .input-prepend .btn, -.navbar .input-append .btn, -.navbar .input-prepend .btn-group, -.navbar .input-append .btn-group { - margin-top: 0; -} -.navbar-form { - margin-bottom: 0; - *zoom: 1; -} -.navbar-form:before, -.navbar-form:after { - display: table; - content: ""; - line-height: 0; -} -.navbar-form:after { - clear: both; -} -.navbar-form input, -.navbar-form select, -.navbar-form .radio, -.navbar-form .checkbox { - margin-top: 5px; -} -.navbar-form input, -.navbar-form select, -.navbar-form .btn { - display: inline-block; - margin-bottom: 0; -} -.navbar-form input[type="image"], -.navbar-form input[type="checkbox"], -.navbar-form input[type="radio"] { - margin-top: 3px; -} -.navbar-form .input-append, -.navbar-form .input-prepend { - margin-top: 5px; - white-space: nowrap; -} -.navbar-form .input-append input, -.navbar-form .input-prepend input { - margin-top: 0; -} -.navbar-search { - position: relative; - float: left; - margin-top: 5px; - margin-bottom: 0; -} -.navbar-search .search-query { - margin-bottom: 0; - padding: 4px 14px; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - font-weight: normal; - line-height: 1; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; -} -.navbar-static-top { - position: static; - margin-bottom: 0; -} -.navbar-static-top .navbar-inner { - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.navbar-fixed-top, -.navbar-fixed-bottom { - position: fixed; - right: 0; - left: 0; - z-index: 1030; - margin-bottom: 0; -} -.navbar-fixed-top .navbar-inner, -.navbar-static-top .navbar-inner { - border-width: 0 0 1px; -} -.navbar-fixed-bottom .navbar-inner { - border-width: 1px 0 0; -} -.navbar-fixed-top .navbar-inner, -.navbar-fixed-bottom .navbar-inner { - padding-left: 0; - padding-right: 0; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; -} -.navbar-static-top .container, -.navbar-fixed-top .container, -.navbar-fixed-bottom .container { - width: 940px; -} -.navbar-fixed-top { - top: 0; -} -.navbar-fixed-top .navbar-inner, -.navbar-static-top .navbar-inner { - -webkit-box-shadow: 0 1px 10px rgba(0,0,0,.1); - -moz-box-shadow: 0 1px 10px rgba(0,0,0,.1); - box-shadow: 0 1px 10px rgba(0,0,0,.1); -} -.navbar-fixed-bottom { - bottom: 0; -} -.navbar-fixed-bottom .navbar-inner { - -webkit-box-shadow: 0 -1px 10px rgba(0,0,0,.1); - -moz-box-shadow: 0 -1px 10px rgba(0,0,0,.1); - box-shadow: 0 -1px 10px rgba(0,0,0,.1); -} -.navbar .nav { - position: relative; - left: 0; - display: block; - float: left; - margin: 0 10px 0 0; -} -.navbar .nav.pull-right { - float: right; - margin-right: 0; -} -.navbar .nav > li { - float: left; -} -.navbar .nav > li > a { - float: none; - padding: 10px 15px 10px; - color: #777777; - text-decoration: none; - text-shadow: 0 1px 0 #ffffff; -} -.navbar .nav .dropdown-toggle .caret { - margin-top: 8px; -} -.navbar .nav > li > a:focus, -.navbar .nav > li > a:hover { - background-color: transparent; - color: #333333; - text-decoration: none; -} -.navbar .nav > .active > a, -.navbar .nav > .active > a:hover, -.navbar .nav > .active > a:focus { - color: #555555; - text-decoration: none; - background-color: #e5e5e5; - -webkit-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); - -moz-box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); - box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); -} -.navbar .btn-navbar { - display: none; - float: right; - padding: 7px 10px; - margin-left: 5px; - margin-right: 5px; - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #ededed; - background-image: -moz-linear-gradient(top, #f2f2f2, #e5e5e5); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5)); - background-image: -webkit-linear-gradient(top, #f2f2f2, #e5e5e5); - background-image: -o-linear-gradient(top, #f2f2f2, #e5e5e5); - background-image: linear-gradient(to bottom, #f2f2f2, #e5e5e5); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0); - border-color: #e5e5e5 #e5e5e5 #bfbfbf; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #e5e5e5; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); - -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); - -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); - box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075); -} -.navbar .btn-navbar:hover, -.navbar .btn-navbar:focus, -.navbar .btn-navbar:active, -.navbar .btn-navbar.active, -.navbar .btn-navbar.disabled, -.navbar .btn-navbar[disabled] { - color: #ffffff; - background-color: #e5e5e5; - *background-color: #d9d9d9; -} -.navbar .btn-navbar:active, -.navbar .btn-navbar.active { - background-color: #cccccc \9; -} -.navbar .btn-navbar .icon-bar { - display: block; - width: 18px; - height: 2px; - background-color: #f5f5f5; - -webkit-border-radius: 1px; - -moz-border-radius: 1px; - border-radius: 1px; - -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); - -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); - box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -} -.btn-navbar .icon-bar + .icon-bar { - margin-top: 3px; -} -.navbar .nav > li > .dropdown-menu:before { - content: ''; - display: inline-block; - border-left: 7px solid transparent; - border-right: 7px solid transparent; - border-bottom: 7px solid #ccc; - border-bottom-color: rgba(0, 0, 0, 0.2); - position: absolute; - top: -7px; - left: 9px; -} -.navbar .nav > li > .dropdown-menu:after { - content: ''; - display: inline-block; - border-left: 6px solid transparent; - border-right: 6px solid transparent; - border-bottom: 6px solid #ffffff; - position: absolute; - top: -6px; - left: 10px; -} -.navbar-fixed-bottom .nav > li > .dropdown-menu:before { - border-top: 7px solid #ccc; - border-top-color: rgba(0, 0, 0, 0.2); - border-bottom: 0; - bottom: -7px; - top: auto; -} -.navbar-fixed-bottom .nav > li > .dropdown-menu:after { - border-top: 6px solid #ffffff; - border-bottom: 0; - bottom: -6px; - top: auto; -} -.navbar .nav li.dropdown > a:hover .caret, -.navbar .nav li.dropdown > a:focus .caret { - border-top-color: #333333; - border-bottom-color: #333333; -} -.navbar .nav li.dropdown.open > .dropdown-toggle, -.navbar .nav li.dropdown.active > .dropdown-toggle, -.navbar .nav li.dropdown.open.active > .dropdown-toggle { - background-color: #e5e5e5; - color: #555555; -} -.navbar .nav li.dropdown > .dropdown-toggle .caret { - border-top-color: #777777; - border-bottom-color: #777777; -} -.navbar .nav li.dropdown.open > .dropdown-toggle .caret, -.navbar .nav li.dropdown.active > .dropdown-toggle .caret, -.navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { - border-top-color: #555555; - border-bottom-color: #555555; -} -.navbar .pull-right > li > .dropdown-menu, -.navbar .nav > li > .dropdown-menu.pull-right { - left: auto; - right: 0; -} -.navbar .pull-right > li > .dropdown-menu:before, -.navbar .nav > li > .dropdown-menu.pull-right:before { - left: auto; - right: 12px; -} -.navbar .pull-right > li > .dropdown-menu:after, -.navbar .nav > li > .dropdown-menu.pull-right:after { - left: auto; - right: 13px; -} -.navbar .pull-right > li > .dropdown-menu .dropdown-menu, -.navbar .nav > li > .dropdown-menu.pull-right .dropdown-menu { - left: auto; - right: 100%; - margin-left: 0; - margin-right: -1px; - -webkit-border-radius: 6px 0 6px 6px; - -moz-border-radius: 6px 0 6px 6px; - border-radius: 6px 0 6px 6px; -} -.navbar-inverse .navbar-inner { - background-color: #1b1b1b; - background-image: -moz-linear-gradient(top, #222222, #111111); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111)); - background-image: -webkit-linear-gradient(top, #222222, #111111); - background-image: -o-linear-gradient(top, #222222, #111111); - background-image: linear-gradient(to bottom, #222222, #111111); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0); - border-color: #252525; -} -.navbar-inverse .brand, -.navbar-inverse .nav > li > a { - color: #999999; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); -} -.navbar-inverse .brand:hover, -.navbar-inverse .nav > li > a:hover, -.navbar-inverse .brand:focus, -.navbar-inverse .nav > li > a:focus { - color: #ffffff; -} -.navbar-inverse .brand { - color: #999999; -} -.navbar-inverse .navbar-text { - color: #999999; -} -.navbar-inverse .nav > li > a:focus, -.navbar-inverse .nav > li > a:hover { - background-color: transparent; - color: #ffffff; -} -.navbar-inverse .nav .active > a, -.navbar-inverse .nav .active > a:hover, -.navbar-inverse .nav .active > a:focus { - color: #ffffff; - background-color: #111111; -} -.navbar-inverse .navbar-link { - color: #999999; -} -.navbar-inverse .navbar-link:hover, -.navbar-inverse .navbar-link:focus { - color: #ffffff; -} -.navbar-inverse .divider-vertical { - border-left-color: #111111; - border-right-color: #222222; -} -.navbar-inverse .nav li.dropdown.open > .dropdown-toggle, -.navbar-inverse .nav li.dropdown.active > .dropdown-toggle, -.navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle { - background-color: #111111; - color: #ffffff; -} -.navbar-inverse .nav li.dropdown > a:hover .caret, -.navbar-inverse .nav li.dropdown > a:focus .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; -} -.navbar-inverse .nav li.dropdown > .dropdown-toggle .caret { - border-top-color: #999999; - border-bottom-color: #999999; -} -.navbar-inverse .nav li.dropdown.open > .dropdown-toggle .caret, -.navbar-inverse .nav li.dropdown.active > .dropdown-toggle .caret, -.navbar-inverse .nav li.dropdown.open.active > .dropdown-toggle .caret { - border-top-color: #ffffff; - border-bottom-color: #ffffff; -} -.navbar-inverse .navbar-search .search-query { - color: #ffffff; - background-color: #515151; - border-color: #111111; - -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); - -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); - box-shadow: inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15); - -webkit-transition: none; - -moz-transition: none; - -o-transition: none; - transition: none; -} -.navbar-inverse .navbar-search .search-query:-moz-placeholder { - color: #cccccc; -} -.navbar-inverse .navbar-search .search-query:-ms-input-placeholder { - color: #cccccc; -} -.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder { - color: #cccccc; -} -.navbar-inverse .navbar-search .search-query:focus, -.navbar-inverse .navbar-search .search-query.focused { - padding: 5px 15px; - color: #333333; - text-shadow: 0 1px 0 #ffffff; - background-color: #ffffff; - border: 0; - -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - outline: 0; -} -.navbar-inverse .btn-navbar { - color: #ffffff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #0e0e0e; - background-image: -moz-linear-gradient(top, #151515, #040404); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404)); - background-image: -webkit-linear-gradient(top, #151515, #040404); - background-image: -o-linear-gradient(top, #151515, #040404); - background-image: linear-gradient(to bottom, #151515, #040404); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0); - border-color: #040404 #040404 #000000; - border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); - *background-color: #040404; - /* Darken IE7 buttons by default so they stand out more given they won't have borders */ - - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); -} -.navbar-inverse .btn-navbar:hover, -.navbar-inverse .btn-navbar:focus, -.navbar-inverse .btn-navbar:active, -.navbar-inverse .btn-navbar.active, -.navbar-inverse .btn-navbar.disabled, -.navbar-inverse .btn-navbar[disabled] { - color: #ffffff; - background-color: #040404; - *background-color: #000000; -} -.navbar-inverse .btn-navbar:active, -.navbar-inverse .btn-navbar.active { - background-color: #000000 \9; -} -.breadcrumb { - padding: 8px 15px; - margin: 0 0 20px; - list-style: none; - background-color: #f5f5f5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.breadcrumb > li { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - text-shadow: 0 1px 0 #ffffff; -} -.breadcrumb > li > .divider { - padding: 0 5px; - color: #ccc; -} -.breadcrumb > .active { - color: #999999; -} -.pagination { - margin: 20px 0; -} -.pagination ul { - display: inline-block; - *display: inline; - /* IE7 inline-block hack */ - - *zoom: 1; - margin-left: 0; - margin-bottom: 0; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); -} -.pagination ul > li { - display: inline; -} -.pagination ul > li > a, -.pagination ul > li > span { - float: left; - padding: 4px 12px; - line-height: 20px; - text-decoration: none; - background-color: #ffffff; - border: 1px solid #dddddd; - border-left-width: 0; -} -.pagination ul > li > a:hover, -.pagination ul > li > a:focus, -.pagination ul > .active > a, -.pagination ul > .active > span { - background-color: #f5f5f5; -} -.pagination ul > .active > a, -.pagination ul > .active > span { - color: #999999; - cursor: default; -} -.pagination ul > .disabled > span, -.pagination ul > .disabled > a, -.pagination ul > .disabled > a:hover, -.pagination ul > .disabled > a:focus { - color: #999999; - background-color: transparent; - cursor: default; -} -.pagination ul > li:first-child > a, -.pagination ul > li:first-child > span { - border-left-width: 1px; - -webkit-border-top-left-radius: 4px; - -moz-border-radius-topleft: 4px; - border-top-left-radius: 4px; - -webkit-border-bottom-left-radius: 4px; - -moz-border-radius-bottomleft: 4px; - border-bottom-left-radius: 4px; -} -.pagination ul > li:last-child > a, -.pagination ul > li:last-child > span { - -webkit-border-top-right-radius: 4px; - -moz-border-radius-topright: 4px; - border-top-right-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - -moz-border-radius-bottomright: 4px; - border-bottom-right-radius: 4px; -} -.pagination-centered { - text-align: center; -} -.pagination-right { - text-align: right; -} -.pagination-large ul > li > a, -.pagination-large ul > li > span { - padding: 11px 19px; - font-size: 16.25px; -} -.pagination-large ul > li:first-child > a, -.pagination-large ul > li:first-child > span { - -webkit-border-top-left-radius: 6px; - -moz-border-radius-topleft: 6px; - border-top-left-radius: 6px; - -webkit-border-bottom-left-radius: 6px; - -moz-border-radius-bottomleft: 6px; - border-bottom-left-radius: 6px; -} -.pagination-large ul > li:last-child > a, -.pagination-large ul > li:last-child > span { - -webkit-border-top-right-radius: 6px; - -moz-border-radius-topright: 6px; - border-top-right-radius: 6px; - -webkit-border-bottom-right-radius: 6px; - -moz-border-radius-bottomright: 6px; - border-bottom-right-radius: 6px; -} -.pagination-mini ul > li:first-child > a, -.pagination-small ul > li:first-child > a, -.pagination-mini ul > li:first-child > span, -.pagination-small ul > li:first-child > span { - -webkit-border-top-left-radius: 3px; - -moz-border-radius-topleft: 3px; - border-top-left-radius: 3px; - -webkit-border-bottom-left-radius: 3px; - -moz-border-radius-bottomleft: 3px; - border-bottom-left-radius: 3px; -} -.pagination-mini ul > li:last-child > a, -.pagination-small ul > li:last-child > a, -.pagination-mini ul > li:last-child > span, -.pagination-small ul > li:last-child > span { - -webkit-border-top-right-radius: 3px; - -moz-border-radius-topright: 3px; - border-top-right-radius: 3px; - -webkit-border-bottom-right-radius: 3px; - -moz-border-radius-bottomright: 3px; - border-bottom-right-radius: 3px; -} -.pagination-small ul > li > a, -.pagination-small ul > li > span { - padding: 2px 10px; - font-size: 11.049999999999999px; -} -.pagination-mini ul > li > a, -.pagination-mini ul > li > span { - padding: 0 6px; - font-size: 9.75px; -} -.pager { - margin: 20px 0; - list-style: none; - text-align: center; - *zoom: 1; -} -.pager:before, -.pager:after { - display: table; - content: ""; - line-height: 0; -} -.pager:after { - clear: both; -} -.pager li { - display: inline; -} -.pager li > a, -.pager li > span { - display: inline-block; - padding: 5px 14px; - background-color: #fff; - border: 1px solid #ddd; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - border-radius: 15px; -} -.pager li > a:hover, -.pager li > a:focus { - text-decoration: none; - background-color: #f5f5f5; -} -.pager .next > a, -.pager .next > span { - float: right; -} -.pager .previous > a, -.pager .previous > span { - float: left; -} -.pager .disabled > a, -.pager .disabled > a:hover, -.pager .disabled > a:focus, -.pager .disabled > span { - color: #999999; - background-color: #fff; - cursor: default; -} -.thumbnails { - margin-left: -20px; - list-style: none; - *zoom: 1; -} -.thumbnails:before, -.thumbnails:after { - display: table; - content: ""; - line-height: 0; -} -.thumbnails:after { - clear: both; -} -.row-fluid .thumbnails { - margin-left: 0; -} -.thumbnails > li { - float: left; - margin-bottom: 20px; - margin-left: 20px; -} -.thumbnail { - display: block; - padding: 4px; - line-height: 20px; - border: 1px solid #ddd; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); - -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.055); - -webkit-transition: all 0.2s ease-in-out; - -moz-transition: all 0.2s ease-in-out; - -o-transition: all 0.2s ease-in-out; - transition: all 0.2s ease-in-out; -} -a.thumbnail:hover, -a.thumbnail:focus { - border-color: #0088cc; - -webkit-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); - -moz-box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); - box-shadow: 0 1px 4px rgba(0, 105, 214, 0.25); -} -.thumbnail > img { - display: block; - max-width: 100%; - margin-left: auto; - margin-right: auto; -} -.thumbnail .caption { - padding: 9px; - color: #555555; -} -.alert { - padding: 8px 35px 8px 14px; - margin-bottom: 20px; - text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); - background-color: #fcf8e3; - border: 1px solid #fbeed5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.alert, -.alert h4 { - color: #c09853; -} -.alert h4 { - margin: 0; -} -.alert .close { - position: relative; - top: -2px; - right: -21px; - line-height: 20px; -} -.alert-success { - background-color: #dff0d8; - border-color: #d6e9c6; - color: #468847; -} -.alert-success h4 { - color: #468847; -} -.alert-danger, -.alert-error { - background-color: #f2dede; - border-color: #eed3d7; - color: #b94a48; -} -.alert-danger h4, -.alert-error h4 { - color: #b94a48; -} -.alert-info { - background-color: #d9edf7; - border-color: #bce8f1; - color: #3a87ad; -} -.alert-info h4 { - color: #3a87ad; -} -.alert-block { - padding-top: 14px; - padding-bottom: 14px; -} -.alert-block > p, -.alert-block > ul { - margin-bottom: 0; -} -.alert-block p + p { - margin-top: 5px; -} -@-webkit-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} -@-moz-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} -@-ms-keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} -@-o-keyframes progress-bar-stripes { - from { - background-position: 0 0; - } - to { - background-position: 40px 0; - } -} -@keyframes progress-bar-stripes { - from { - background-position: 40px 0; - } - to { - background-position: 0 0; - } -} -.progress { - overflow: hidden; - height: 20px; - margin-bottom: 20px; - background-color: #f7f7f7; - background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); - background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); - background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.progress .bar { - width: 0%; - height: 100%; - color: #ffffff; - float: left; - font-size: 12px; - text-align: center; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); - background-color: #0e90d2; - background-image: -moz-linear-gradient(top, #149bdf, #0480be); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); - background-image: -webkit-linear-gradient(top, #149bdf, #0480be); - background-image: -o-linear-gradient(top, #149bdf, #0480be); - background-image: linear-gradient(to bottom, #149bdf, #0480be); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); - -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - -webkit-transition: width 0.6s ease; - -moz-transition: width 0.6s ease; - -o-transition: width 0.6s ease; - transition: width 0.6s ease; -} -.progress .bar + .bar { - -webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); - -moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); - box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); -} -.progress-striped .bar { - background-color: #149bdf; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - -webkit-background-size: 40px 40px; - -moz-background-size: 40px 40px; - -o-background-size: 40px 40px; - background-size: 40px 40px; -} -.progress.active .bar { - -webkit-animation: progress-bar-stripes 2s linear infinite; - -moz-animation: progress-bar-stripes 2s linear infinite; - -ms-animation: progress-bar-stripes 2s linear infinite; - -o-animation: progress-bar-stripes 2s linear infinite; - animation: progress-bar-stripes 2s linear infinite; -} -.progress-danger .bar, -.progress .bar-danger { - background-color: #dd514c; - background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35)); - background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35); - background-image: -o-linear-gradient(top, #ee5f5b, #c43c35); - background-image: linear-gradient(to bottom, #ee5f5b, #c43c35); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0); -} -.progress-danger.progress-striped .bar, -.progress-striped .bar-danger { - background-color: #ee5f5b; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} -.progress-success .bar, -.progress .bar-success { - background-color: #5eb95e; - background-image: -moz-linear-gradient(top, #62c462, #57a957); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957)); - background-image: -webkit-linear-gradient(top, #62c462, #57a957); - background-image: -o-linear-gradient(top, #62c462, #57a957); - background-image: linear-gradient(to bottom, #62c462, #57a957); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0); -} -.progress-success.progress-striped .bar, -.progress-striped .bar-success { - background-color: #62c462; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} -.progress-info .bar, -.progress .bar-info { - background-color: #4bb1cf; - background-image: -moz-linear-gradient(top, #5bc0de, #339bb9); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9)); - background-image: -webkit-linear-gradient(top, #5bc0de, #339bb9); - background-image: -o-linear-gradient(top, #5bc0de, #339bb9); - background-image: linear-gradient(to bottom, #5bc0de, #339bb9); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0); -} -.progress-info.progress-striped .bar, -.progress-striped .bar-info { - background-color: #5bc0de; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} -.progress-warning .bar, -.progress .bar-warning { - background-color: #faa732; - background-image: -moz-linear-gradient(top, #fbb450, #f89406); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406)); - background-image: -webkit-linear-gradient(top, #fbb450, #f89406); - background-image: -o-linear-gradient(top, #fbb450, #f89406); - background-image: linear-gradient(to bottom, #fbb450, #f89406); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0); -} -.progress-warning.progress-striped .bar, -.progress-striped .bar-warning { - background-color: #fbb450; - background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); - background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); - background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -} -.hero-unit { - padding: 60px; - margin-bottom: 30px; - font-size: 18px; - font-weight: 200; - line-height: 30px; - color: inherit; - background-color: #eeeeee; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} -.hero-unit h1 { - margin-bottom: 0; - font-size: 60px; - line-height: 1; - color: inherit; - letter-spacing: -1px; -} -.hero-unit li { - line-height: 30px; -} -.media, -.media-body { - overflow: hidden; - *overflow: visible; - zoom: 1; -} -.media, -.media .media { - margin-top: 15px; -} -.media:first-child { - margin-top: 0; -} -.media-object { - display: block; -} -.media-heading { - margin: 0 0 5px; -} -.media > .pull-left { - margin-right: 10px; -} -.media > .pull-right { - margin-left: 10px; -} -.media-list { - margin-left: 0; - list-style: none; -} -.tooltip { - position: absolute; - z-index: 1030; - display: block; - visibility: visible; - font-size: 11px; - line-height: 1.4; - opacity: 0; - filter: alpha(opacity=0); -} -.tooltip.in { - opacity: 0.8; - filter: alpha(opacity=80); -} -.tooltip.top { - margin-top: -3px; - padding: 5px 0; -} -.tooltip.right { - margin-left: 3px; - padding: 0 5px; -} -.tooltip.bottom { - margin-top: 3px; - padding: 5px 0; -} -.tooltip.left { - margin-left: -3px; - padding: 0 5px; -} -.tooltip-inner { - max-width: 200px; - padding: 8px; - color: #ffffff; - text-align: center; - text-decoration: none; - background-color: #000000; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.tooltip-arrow { - position: absolute; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; -} -.tooltip.top .tooltip-arrow { - bottom: 0; - left: 50%; - margin-left: -5px; - border-width: 5px 5px 0; - border-top-color: #000000; -} -.tooltip.right .tooltip-arrow { - top: 50%; - left: 0; - margin-top: -5px; - border-width: 5px 5px 5px 0; - border-right-color: #000000; -} -.tooltip.left .tooltip-arrow { - top: 50%; - right: 0; - margin-top: -5px; - border-width: 5px 0 5px 5px; - border-left-color: #000000; -} -.tooltip.bottom .tooltip-arrow { - top: 0; - left: 50%; - margin-left: -5px; - border-width: 0 5px 5px; - border-bottom-color: #000000; -} -.popover { - position: absolute; - top: 0; - left: 0; - z-index: 1010; - display: none; - max-width: 276px; - padding: 1px; - text-align: left; - background-color: #ffffff; - -webkit-background-clip: padding-box; - -moz-background-clip: padding; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - white-space: normal; -} -.popover.top { - margin-top: -10px; -} -.popover.right { - margin-left: 10px; -} -.popover.bottom { - margin-top: 10px; -} -.popover.left { - margin-left: -10px; -} -.popover-title { - margin: 0; - padding: 8px 14px; - font-size: 14px; - font-weight: normal; - line-height: 18px; - background-color: #f7f7f7; - border-bottom: 1px solid #ebebeb; - -webkit-border-radius: 5px 5px 0 0; - -moz-border-radius: 5px 5px 0 0; - border-radius: 5px 5px 0 0; -} -.popover-title:empty { - display: none; -} -.popover-content { - padding: 9px 14px; -} -.popover .arrow, -.popover .arrow:after { - position: absolute; - display: block; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; -} -.popover .arrow { - border-width: 11px; -} -.popover .arrow:after { - border-width: 10px; - content: ""; -} -.popover.top .arrow { - left: 50%; - margin-left: -11px; - border-bottom-width: 0; - border-top-color: #999; - border-top-color: rgba(0, 0, 0, 0.25); - bottom: -11px; -} -.popover.top .arrow:after { - bottom: 1px; - margin-left: -10px; - border-bottom-width: 0; - border-top-color: #ffffff; -} -.popover.right .arrow { - top: 50%; - left: -11px; - margin-top: -11px; - border-left-width: 0; - border-right-color: #999; - border-right-color: rgba(0, 0, 0, 0.25); -} -.popover.right .arrow:after { - left: 1px; - bottom: -10px; - border-left-width: 0; - border-right-color: #ffffff; -} -.popover.bottom .arrow { - left: 50%; - margin-left: -11px; - border-top-width: 0; - border-bottom-color: #999; - border-bottom-color: rgba(0, 0, 0, 0.25); - top: -11px; -} -.popover.bottom .arrow:after { - top: 1px; - margin-left: -10px; - border-top-width: 0; - border-bottom-color: #ffffff; -} -.popover.left .arrow { - top: 50%; - right: -11px; - margin-top: -11px; - border-right-width: 0; - border-left-color: #999; - border-left-color: rgba(0, 0, 0, 0.25); -} -.popover.left .arrow:after { - right: 1px; - border-right-width: 0; - border-left-color: #ffffff; - bottom: -10px; -} -.modal-backdrop { - position: fixed; - top: 0; - right: 0; - bottom: 0; - left: 0; - z-index: 1040; - background-color: #000000; -} -.modal-backdrop.fade { - opacity: 0; -} -.modal-backdrop, -.modal-backdrop.fade.in { - opacity: 0.8; - filter: alpha(opacity=80); -} -.modal { - position: fixed; - top: 10%; - left: 50%; - z-index: 1050; - width: 560px; - margin-left: -280px; - background-color: #ffffff; - border: 1px solid #999; - border: 1px solid rgba(0, 0, 0, 0.3); - *border: 1px solid #999; - /* IE6-7 */ - - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); - -webkit-background-clip: padding-box; - -moz-background-clip: padding-box; - background-clip: padding-box; - outline: none; -} -.modal.fade { - -webkit-transition: opacity .3s linear, top .3s ease-out; - -moz-transition: opacity .3s linear, top .3s ease-out; - -o-transition: opacity .3s linear, top .3s ease-out; - transition: opacity .3s linear, top .3s ease-out; - top: -25%; -} -.modal.fade.in { - top: 10%; -} -.modal-header { - padding: 9px 15px; - border-bottom: 1px solid #eee; -} -.modal-header .close { - margin-top: 2px; -} -.modal-header h3 { - margin: 0; - line-height: 30px; -} -.modal-body { - position: relative; - overflow-y: auto; - max-height: 400px; - padding: 15px; -} -.modal-form { - margin-bottom: 0; -} -.modal-footer { - padding: 14px 15px 15px; - margin-bottom: 0; - text-align: right; - background-color: #f5f5f5; - border-top: 1px solid #ddd; - -webkit-border-radius: 0 0 6px 6px; - -moz-border-radius: 0 0 6px 6px; - border-radius: 0 0 6px 6px; - -webkit-box-shadow: inset 0 1px 0 #ffffff; - -moz-box-shadow: inset 0 1px 0 #ffffff; - box-shadow: inset 0 1px 0 #ffffff; - *zoom: 1; -} -.modal-footer:before, -.modal-footer:after { - display: table; - content: ""; - line-height: 0; -} -.modal-footer:after { - clear: both; -} -.modal-footer .btn + .btn { - margin-left: 5px; - margin-bottom: 0; -} -.modal-footer .btn-group .btn + .btn { - margin-left: -1px; -} -.modal-footer .btn-block + .btn-block { - margin-left: 0; -} -.dropup, -.dropdown { - position: relative; -} -.dropdown-toggle { - *margin-bottom: -3px; -} -.dropdown-toggle:active, -.open .dropdown-toggle { - outline: 0; -} -.caret { - display: inline-block; - width: 0; - height: 0; - vertical-align: top; - border-top: 4px solid #000000; - border-right: 4px solid transparent; - border-left: 4px solid transparent; - content: ""; -} -.dropdown .caret { - margin-top: 8px; - margin-left: 2px; -} -.dropdown-menu { - position: absolute; - top: 100%; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - padding: 5px 0; - margin: 2px 0 0; - list-style: none; - background-color: #ffffff; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, 0.2); - *border-right-width: 2px; - *border-bottom-width: 2px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; - -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); - -webkit-background-clip: padding-box; - -moz-background-clip: padding; - background-clip: padding-box; -} -.dropdown-menu.pull-right { - right: 0; - left: auto; -} -.dropdown-menu .divider { - *width: 100%; - height: 1px; - margin: 9px 1px; - *margin: -5px 0 5px; - overflow: hidden; - background-color: #e5e5e5; - border-bottom: 1px solid #ffffff; -} -.dropdown-menu > li > a { - display: block; - padding: 3px 20px; - clear: both; - font-weight: normal; - line-height: 20px; - color: #333333; - white-space: nowrap; -} -.dropdown-menu > li > a:hover, -.dropdown-menu > li > a:focus, -.dropdown-submenu:hover > a, -.dropdown-submenu:focus > a { - text-decoration: none; - color: #ffffff; - background-color: #0081c2; - background-image: -moz-linear-gradient(top, #0088cc, #0077b3); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); - background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); - background-image: -o-linear-gradient(top, #0088cc, #0077b3); - background-image: linear-gradient(to bottom, #0088cc, #0077b3); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); -} -.dropdown-menu > .active > a, -.dropdown-menu > .active > a:hover, -.dropdown-menu > .active > a:focus { - color: #ffffff; - text-decoration: none; - outline: 0; - background-color: #0081c2; - background-image: -moz-linear-gradient(top, #0088cc, #0077b3); - background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3)); - background-image: -webkit-linear-gradient(top, #0088cc, #0077b3); - background-image: -o-linear-gradient(top, #0088cc, #0077b3); - background-image: linear-gradient(to bottom, #0088cc, #0077b3); - background-repeat: repeat-x; - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0); -} -.dropdown-menu > .disabled > a, -.dropdown-menu > .disabled > a:hover, -.dropdown-menu > .disabled > a:focus { - color: #999999; -} -.dropdown-menu > .disabled > a:hover, -.dropdown-menu > .disabled > a:focus { - text-decoration: none; - background-color: transparent; - background-image: none; - filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); - cursor: default; -} -.open { - *z-index: 1000; -} -.open > .dropdown-menu { - display: block; -} -.dropdown-backdrop { - position: fixed; - left: 0; - right: 0; - bottom: 0; - top: 0; - z-index: 990; -} -.pull-right > .dropdown-menu { - right: 0; - left: auto; -} -.dropup .caret, -.navbar-fixed-bottom .dropdown .caret { - border-top: 0; - border-bottom: 4px solid #000000; - content: ""; -} -.dropup .dropdown-menu, -.navbar-fixed-bottom .dropdown .dropdown-menu { - top: auto; - bottom: 100%; - margin-bottom: 1px; -} -.dropdown-submenu { - position: relative; -} -.dropdown-submenu > .dropdown-menu { - top: 0; - left: 100%; - margin-top: -6px; - margin-left: -1px; - -webkit-border-radius: 0 6px 6px 6px; - -moz-border-radius: 0 6px 6px 6px; - border-radius: 0 6px 6px 6px; -} -.dropdown-submenu:hover > .dropdown-menu { - display: block; -} -.dropup .dropdown-submenu > .dropdown-menu { - top: auto; - bottom: 0; - margin-top: 0; - margin-bottom: -2px; - -webkit-border-radius: 5px 5px 5px 0; - -moz-border-radius: 5px 5px 5px 0; - border-radius: 5px 5px 5px 0; -} -.dropdown-submenu > a:after { - display: block; - content: " "; - float: right; - width: 0; - height: 0; - border-color: transparent; - border-style: solid; - border-width: 5px 0 5px 5px; - border-left-color: #cccccc; - margin-top: 5px; - margin-right: -10px; -} -.dropdown-submenu:hover > a:after { - border-left-color: #ffffff; -} -.dropdown-submenu.pull-left { - float: none; -} -.dropdown-submenu.pull-left > .dropdown-menu { - left: -100%; - margin-left: 10px; - -webkit-border-radius: 6px 0 6px 6px; - -moz-border-radius: 6px 0 6px 6px; - border-radius: 6px 0 6px 6px; -} -.dropdown .dropdown-menu .nav-header { - padding-left: 20px; - padding-right: 20px; -} -.typeahead { - z-index: 1051; - margin-top: 2px; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.accordion { - margin-bottom: 20px; -} -.accordion-group { - margin-bottom: 2px; - border: 1px solid #e5e5e5; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; -} -.accordion-heading { - border-bottom: 0; -} -.accordion-heading .accordion-toggle { - display: block; - padding: 8px 15px; -} -.accordion-toggle { - cursor: pointer; -} -.accordion-inner { - padding: 9px 15px; - border-top: 1px solid #e5e5e5; -} -.carousel { - position: relative; - margin-bottom: 20px; - line-height: 1; -} -.carousel-inner { - overflow: hidden; - width: 100%; - position: relative; -} -.carousel-inner > .item { - display: none; - position: relative; - -webkit-transition: 0.6s ease-in-out left; - -moz-transition: 0.6s ease-in-out left; - -o-transition: 0.6s ease-in-out left; - transition: 0.6s ease-in-out left; -} -.carousel-inner > .item > img, -.carousel-inner > .item > a > img { - display: block; - line-height: 1; -} -.carousel-inner > .active, -.carousel-inner > .next, -.carousel-inner > .prev { - display: block; -} -.carousel-inner > .active { - left: 0; -} -.carousel-inner > .next, -.carousel-inner > .prev { - position: absolute; - top: 0; - width: 100%; -} -.carousel-inner > .next { - left: 100%; -} -.carousel-inner > .prev { - left: -100%; -} -.carousel-inner > .next.left, -.carousel-inner > .prev.right { - left: 0; -} -.carousel-inner > .active.left { - left: -100%; -} -.carousel-inner > .active.right { - left: 100%; -} -.carousel-control { - position: absolute; - top: 40%; - left: 15px; - width: 40px; - height: 40px; - margin-top: -20px; - font-size: 60px; - font-weight: 100; - line-height: 30px; - color: #ffffff; - text-align: center; - background: #222222; - border: 3px solid #ffffff; - -webkit-border-radius: 23px; - -moz-border-radius: 23px; - border-radius: 23px; - opacity: 0.5; - filter: alpha(opacity=50); -} -.carousel-control.right { - left: auto; - right: 15px; -} -.carousel-control:hover, -.carousel-control:focus { - color: #ffffff; - text-decoration: none; - opacity: 0.9; - filter: alpha(opacity=90); -} -.carousel-indicators { - position: absolute; - top: 15px; - right: 15px; - z-index: 5; - margin: 0; - list-style: none; -} -.carousel-indicators li { - display: block; - float: left; - width: 10px; - height: 10px; - margin-left: 5px; - text-indent: -999px; - background-color: #ccc; - background-color: rgba(255, 255, 255, 0.25); - border-radius: 5px; -} -.carousel-indicators .active { - background-color: #fff; -} -.carousel-caption { - position: absolute; - left: 0; - right: 0; - bottom: 0; - padding: 15px; - background: #333333; - background: rgba(0, 0, 0, 0.75); -} -.carousel-caption h4, -.carousel-caption p { - color: #ffffff; - line-height: 20px; -} -.carousel-caption h4 { - margin: 0 0 5px; -} -.carousel-caption p { - margin-bottom: 0; -} -.well { - min-height: 20px; - padding: 19px; - margin-bottom: 20px; - background-color: #f5f5f5; - border: 1px solid #e3e3e3; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); -} -.well blockquote { - border-color: #ddd; - border-color: rgba(0, 0, 0, 0.15); -} -.well-large { - padding: 24px; - -webkit-border-radius: 6px; - -moz-border-radius: 6px; - border-radius: 6px; -} -.well-small { - padding: 9px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} -.close { - float: right; - font-size: 20px; - font-weight: bold; - line-height: 20px; - color: #000000; - text-shadow: 0 1px 0 #ffffff; - opacity: 0.2; - filter: alpha(opacity=20); -} -.close:hover, -.close:focus { - color: #000000; - text-decoration: none; - cursor: pointer; - opacity: 0.4; - filter: alpha(opacity=40); -} -button.close { - padding: 0; - cursor: pointer; - background: transparent; - border: 0; - -webkit-appearance: none; -} -.pull-right { - float: right; -} -.pull-left { - float: left; -} -.hide { - display: none; -} -.show { - display: block; -} -.invisible { - visibility: hidden; -} -.affix { - position: fixed; -} -.fade { - opacity: 0; - -webkit-transition: opacity 0.15s linear; - -moz-transition: opacity 0.15s linear; - -o-transition: opacity 0.15s linear; - transition: opacity 0.15s linear; -} -.fade.in { - opacity: 1; -} -.collapse { - position: relative; - height: 0; - overflow: hidden; - -webkit-transition: height 0.35s ease; - -moz-transition: height 0.35s ease; - -o-transition: height 0.35s ease; - transition: height 0.35s ease; -} -.collapse.in { - height: auto; -} -@-ms-viewport { - width: device-width; -} -.hidden { - display: none; - visibility: hidden; -} -.visible-phone { - display: none !important; -} -.visible-tablet { - display: none !important; -} -.hidden-desktop { - display: none !important; -} -.visible-desktop { - display: inherit !important; -} -@media (min-width: 768px) and (max-width: 979px) { - .hidden-desktop { - display: inherit !important; - } - .visible-desktop { - display: none !important ; - } - .visible-tablet { - display: inherit !important; - } - .hidden-tablet { - display: none !important; - } -} -@media (max-width: 767px) { - .hidden-desktop { - display: inherit !important; - } - .visible-desktop { - display: none !important; - } - .visible-phone { - display: inherit !important; - } - .hidden-phone { - display: none !important; - } -} -.visible-print { - display: none !important; -} -@media print { - .visible-print { - display: inherit !important; - } - .hidden-print { - display: none !important; - } -} -@media (max-width: 767px) { - body { - padding-left: 20px; - padding-right: 20px; - } - .navbar-fixed-top, - .navbar-fixed-bottom, - .navbar-static-top { - margin-left: -20px; - margin-right: -20px; - } - .container-fluid { - padding: 0; - } - .dl-horizontal dt { - float: none; - clear: none; - width: auto; - text-align: left; - } - .dl-horizontal dd { - margin-left: 0; - } - .container { - width: auto; - } - .row-fluid { - width: 100%; - } - .row, - .thumbnails { - margin-left: 0; - } - .thumbnails > li { - float: none; - margin-left: 0; - } - [class*="span"], - .uneditable-input[class*="span"], - .row-fluid [class*="span"] { - float: none; - display: block; - width: 100%; - margin-left: 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .span12, - .row-fluid .span12 { - width: 100%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .row-fluid [class*="offset"]:first-child { - margin-left: 0; - } - .input-large, - .input-xlarge, - .input-xxlarge, - input[class*="span"], - select[class*="span"], - textarea[class*="span"], - .uneditable-input { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - } - .input-prepend input, - .input-append input, - .input-prepend input[class*="span"], - .input-append input[class*="span"] { - display: inline-block; - width: auto; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 0; - } - .modal { - position: fixed; - top: 20px; - left: 20px; - right: 20px; - width: auto; - margin: 0; - } - .modal.fade { - top: -100px; - } - .modal.fade.in { - top: 20px; - } -} -@media (max-width: 480px) { - .nav-collapse { - -webkit-transform: translate3d(0, 0, 0); - } - .page-header h1 small { - display: block; - line-height: 20px; - } - input[type="checkbox"], - input[type="radio"] { - border: 1px solid #ccc; - } - .form-horizontal .control-label { - float: none; - width: auto; - padding-top: 0; - text-align: left; - } - .form-horizontal .controls { - margin-left: 0; - } - .form-horizontal .control-list { - padding-top: 0; - } - .form-horizontal .form-actions { - padding-left: 10px; - padding-right: 10px; - } - .media .pull-left, - .media .pull-right { - float: none; - display: block; - margin-bottom: 10px; - } - .media-object { - margin-right: 0; - margin-left: 0; - } - .modal { - top: 10px; - left: 10px; - right: 10px; - } - .modal-header .close { - padding: 10px; - margin: -10px; - } - .carousel-caption { - position: static; - } -} -@media (min-width: 768px) and (max-width: 979px) { - .row { - margin-left: -20px; - *zoom: 1; - } - .row:before, - .row:after { - display: table; - content: ""; - line-height: 0; - } - .row:after { - clear: both; - } - [class*="span"] { - float: left; - min-height: 1px; - margin-left: 20px; - } - .container, - .navbar-static-top .container, - .navbar-fixed-top .container, - .navbar-fixed-bottom .container { - width: 724px; - } - .span12 { - width: 724px; - } - .span11 { - width: 662px; - } - .span10 { - width: 600px; - } - .span9 { - width: 538px; - } - .span8 { - width: 476px; - } - .span7 { - width: 414px; - } - .span6 { - width: 352px; - } - .span5 { - width: 290px; - } - .span4 { - width: 228px; - } - .span3 { - width: 166px; - } - .span2 { - width: 104px; - } - .span1 { - width: 42px; - } - .offset12 { - margin-left: 764px; - } - .offset11 { - margin-left: 702px; - } - .offset10 { - margin-left: 640px; - } - .offset9 { - margin-left: 578px; - } - .offset8 { - margin-left: 516px; - } - .offset7 { - margin-left: 454px; - } - .offset6 { - margin-left: 392px; - } - .offset5 { - margin-left: 330px; - } - .offset4 { - margin-left: 268px; - } - .offset3 { - margin-left: 206px; - } - .offset2 { - margin-left: 144px; - } - .offset1 { - margin-left: 82px; - } - .row-fluid { - width: 100%; - *zoom: 1; - } - .row-fluid:before, - .row-fluid:after { - display: table; - content: ""; - line-height: 0; - } - .row-fluid:after { - clear: both; - } - .row-fluid [class*="span"] { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - float: left; - margin-left: 2.7624309392265194%; - *margin-left: 2.709239449864817%; - } - .row-fluid [class*="span"]:first-child { - margin-left: 0; - } - .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.7624309392265194%; - } - .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; - } - .row-fluid .span11 { - width: 91.43646408839778%; - *width: 91.38327259903608%; - } - .row-fluid .span10 { - width: 82.87292817679558%; - *width: 82.81973668743387%; - } - .row-fluid .span9 { - width: 74.30939226519337%; - *width: 74.25620077583166%; - } - .row-fluid .span8 { - width: 65.74585635359117%; - *width: 65.69266486422946%; - } - .row-fluid .span7 { - width: 57.18232044198895%; - *width: 57.12912895262725%; - } - .row-fluid .span6 { - width: 48.61878453038674%; - *width: 48.56559304102504%; - } - .row-fluid .span5 { - width: 40.05524861878453%; - *width: 40.00205712942283%; - } - .row-fluid .span4 { - width: 31.491712707182323%; - *width: 31.43852121782062%; - } - .row-fluid .span3 { - width: 22.92817679558011%; - *width: 22.87498530621841%; - } - .row-fluid .span2 { - width: 14.3646408839779%; - *width: 14.311449394616199%; - } - .row-fluid .span1 { - width: 5.801104972375691%; - *width: 5.747913483013988%; - } - .row-fluid .offset12 { - margin-left: 105.52486187845304%; - *margin-left: 105.41847889972962%; - } - .row-fluid .offset12:first-child { - margin-left: 102.76243093922652%; - *margin-left: 102.6560479605031%; - } - .row-fluid .offset11 { - margin-left: 96.96132596685082%; - *margin-left: 96.8549429881274%; - } - .row-fluid .offset11:first-child { - margin-left: 94.1988950276243%; - *margin-left: 94.09251204890089%; - } - .row-fluid .offset10 { - margin-left: 88.39779005524862%; - *margin-left: 88.2914070765252%; - } - .row-fluid .offset10:first-child { - margin-left: 85.6353591160221%; - *margin-left: 85.52897613729868%; - } - .row-fluid .offset9 { - margin-left: 79.8342541436464%; - *margin-left: 79.72787116492299%; - } - .row-fluid .offset9:first-child { - margin-left: 77.07182320441989%; - *margin-left: 76.96544022569647%; - } - .row-fluid .offset8 { - margin-left: 71.2707182320442%; - *margin-left: 71.16433525332079%; - } - .row-fluid .offset8:first-child { - margin-left: 68.50828729281768%; - *margin-left: 68.40190431409427%; - } - .row-fluid .offset7 { - margin-left: 62.70718232044199%; - *margin-left: 62.600799341718584%; - } - .row-fluid .offset7:first-child { - margin-left: 59.94475138121547%; - *margin-left: 59.838368402492065%; - } - .row-fluid .offset6 { - margin-left: 54.14364640883978%; - *margin-left: 54.037263430116376%; - } - .row-fluid .offset6:first-child { - margin-left: 51.38121546961326%; - *margin-left: 51.27483249088986%; - } - .row-fluid .offset5 { - margin-left: 45.58011049723757%; - *margin-left: 45.47372751851417%; - } - .row-fluid .offset5:first-child { - margin-left: 42.81767955801105%; - *margin-left: 42.71129657928765%; - } - .row-fluid .offset4 { - margin-left: 37.01657458563536%; - *margin-left: 36.91019160691196%; - } - .row-fluid .offset4:first-child { - margin-left: 34.25414364640884%; - *margin-left: 34.14776066768544%; - } - .row-fluid .offset3 { - margin-left: 28.45303867403315%; - *margin-left: 28.346655695309746%; - } - .row-fluid .offset3:first-child { - margin-left: 25.69060773480663%; - *margin-left: 25.584224756083227%; - } - .row-fluid .offset2 { - margin-left: 19.88950276243094%; - *margin-left: 19.783119783707537%; - } - .row-fluid .offset2:first-child { - margin-left: 17.12707182320442%; - *margin-left: 17.02068884448102%; - } - .row-fluid .offset1 { - margin-left: 11.32596685082873%; - *margin-left: 11.219583872105325%; - } - .row-fluid .offset1:first-child { - margin-left: 8.56353591160221%; - *margin-left: 8.457152932878806%; - } - input, - textarea, - .uneditable-input { - margin-left: 0; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 20px; - } - input.span12, - textarea.span12, - .uneditable-input.span12 { - width: 710px; - } - input.span11, - textarea.span11, - .uneditable-input.span11 { - width: 648px; - } - input.span10, - textarea.span10, - .uneditable-input.span10 { - width: 586px; - } - input.span9, - textarea.span9, - .uneditable-input.span9 { - width: 524px; - } - input.span8, - textarea.span8, - .uneditable-input.span8 { - width: 462px; - } - input.span7, - textarea.span7, - .uneditable-input.span7 { - width: 400px; - } - input.span6, - textarea.span6, - .uneditable-input.span6 { - width: 338px; - } - input.span5, - textarea.span5, - .uneditable-input.span5 { - width: 276px; - } - input.span4, - textarea.span4, - .uneditable-input.span4 { - width: 214px; - } - input.span3, - textarea.span3, - .uneditable-input.span3 { - width: 152px; - } - input.span2, - textarea.span2, - .uneditable-input.span2 { - width: 90px; - } - input.span1, - textarea.span1, - .uneditable-input.span1 { - width: 28px; - } -} -@media (min-width: 1200px) { - .row { - margin-left: -30px; - *zoom: 1; - } - .row:before, - .row:after { - display: table; - content: ""; - line-height: 0; - } - .row:after { - clear: both; - } - [class*="span"] { - float: left; - min-height: 1px; - margin-left: 30px; - } - .container, - .navbar-static-top .container, - .navbar-fixed-top .container, - .navbar-fixed-bottom .container { - width: 1170px; - } - .span12 { - width: 1170px; - } - .span11 { - width: 1070px; - } - .span10 { - width: 970px; - } - .span9 { - width: 870px; - } - .span8 { - width: 770px; - } - .span7 { - width: 670px; - } - .span6 { - width: 570px; - } - .span5 { - width: 470px; - } - .span4 { - width: 370px; - } - .span3 { - width: 270px; - } - .span2 { - width: 170px; - } - .span1 { - width: 70px; - } - .offset12 { - margin-left: 1230px; - } - .offset11 { - margin-left: 1130px; - } - .offset10 { - margin-left: 1030px; - } - .offset9 { - margin-left: 930px; - } - .offset8 { - margin-left: 830px; - } - .offset7 { - margin-left: 730px; - } - .offset6 { - margin-left: 630px; - } - .offset5 { - margin-left: 530px; - } - .offset4 { - margin-left: 430px; - } - .offset3 { - margin-left: 330px; - } - .offset2 { - margin-left: 230px; - } - .offset1 { - margin-left: 130px; - } - .row-fluid { - width: 100%; - *zoom: 1; - } - .row-fluid:before, - .row-fluid:after { - display: table; - content: ""; - line-height: 0; - } - .row-fluid:after { - clear: both; - } - .row-fluid [class*="span"] { - display: block; - width: 100%; - min-height: 30px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - float: left; - margin-left: 2.564102564102564%; - *margin-left: 2.5109110747408616%; - } - .row-fluid [class*="span"]:first-child { - margin-left: 0; - } - .row-fluid .controls-row [class*="span"] + [class*="span"] { - margin-left: 2.564102564102564%; - } - .row-fluid .span12 { - width: 100%; - *width: 99.94680851063829%; - } - .row-fluid .span11 { - width: 91.45299145299145%; - *width: 91.39979996362975%; - } - .row-fluid .span10 { - width: 82.90598290598291%; - *width: 82.8527914166212%; - } - .row-fluid .span9 { - width: 74.35897435897436%; - *width: 74.30578286961266%; - } - .row-fluid .span8 { - width: 65.81196581196582%; - *width: 65.75877432260411%; - } - .row-fluid .span7 { - width: 57.26495726495726%; - *width: 57.21176577559556%; - } - .row-fluid .span6 { - width: 48.717948717948715%; - *width: 48.664757228587014%; - } - .row-fluid .span5 { - width: 40.17094017094017%; - *width: 40.11774868157847%; - } - .row-fluid .span4 { - width: 31.623931623931625%; - *width: 31.570740134569924%; - } - .row-fluid .span3 { - width: 23.076923076923077%; - *width: 23.023731587561375%; - } - .row-fluid .span2 { - width: 14.52991452991453%; - *width: 14.476723040552828%; - } - .row-fluid .span1 { - width: 5.982905982905983%; - *width: 5.929714493544281%; - } - .row-fluid .offset12 { - margin-left: 105.12820512820512%; - *margin-left: 105.02182214948171%; - } - .row-fluid .offset12:first-child { - margin-left: 102.56410256410257%; - *margin-left: 102.45771958537915%; - } - .row-fluid .offset11 { - margin-left: 96.58119658119658%; - *margin-left: 96.47481360247316%; - } - .row-fluid .offset11:first-child { - margin-left: 94.01709401709402%; - *margin-left: 93.91071103837061%; - } - .row-fluid .offset10 { - margin-left: 88.03418803418803%; - *margin-left: 87.92780505546462%; - } - .row-fluid .offset10:first-child { - margin-left: 85.47008547008548%; - *margin-left: 85.36370249136206%; - } - .row-fluid .offset9 { - margin-left: 79.48717948717949%; - *margin-left: 79.38079650845607%; - } - .row-fluid .offset9:first-child { - margin-left: 76.92307692307693%; - *margin-left: 76.81669394435352%; - } - .row-fluid .offset8 { - margin-left: 70.94017094017094%; - *margin-left: 70.83378796144753%; - } - .row-fluid .offset8:first-child { - margin-left: 68.37606837606839%; - *margin-left: 68.26968539734497%; - } - .row-fluid .offset7 { - margin-left: 62.393162393162385%; - *margin-left: 62.28677941443899%; - } - .row-fluid .offset7:first-child { - margin-left: 59.82905982905982%; - *margin-left: 59.72267685033642%; - } - .row-fluid .offset6 { - margin-left: 53.84615384615384%; - *margin-left: 53.739770867430444%; - } - .row-fluid .offset6:first-child { - margin-left: 51.28205128205128%; - *margin-left: 51.175668303327875%; - } - .row-fluid .offset5 { - margin-left: 45.299145299145295%; - *margin-left: 45.1927623204219%; - } - .row-fluid .offset5:first-child { - margin-left: 42.73504273504273%; - *margin-left: 42.62865975631933%; - } - .row-fluid .offset4 { - margin-left: 36.75213675213675%; - *margin-left: 36.645753773413354%; - } - .row-fluid .offset4:first-child { - margin-left: 34.18803418803419%; - *margin-left: 34.081651209310785%; - } - .row-fluid .offset3 { - margin-left: 28.205128205128204%; - *margin-left: 28.0987452264048%; - } - .row-fluid .offset3:first-child { - margin-left: 25.641025641025642%; - *margin-left: 25.53464266230224%; - } - .row-fluid .offset2 { - margin-left: 19.65811965811966%; - *margin-left: 19.551736679396257%; - } - .row-fluid .offset2:first-child { - margin-left: 17.094017094017094%; - *margin-left: 16.98763411529369%; - } - .row-fluid .offset1 { - margin-left: 11.11111111111111%; - *margin-left: 11.004728132387708%; - } - .row-fluid .offset1:first-child { - margin-left: 8.547008547008547%; - *margin-left: 8.440625568285142%; - } - input, - textarea, - .uneditable-input { - margin-left: 0; - } - .controls-row [class*="span"] + [class*="span"] { - margin-left: 30px; - } - input.span12, - textarea.span12, - .uneditable-input.span12 { - width: 1156px; - } - input.span11, - textarea.span11, - .uneditable-input.span11 { - width: 1056px; - } - input.span10, - textarea.span10, - .uneditable-input.span10 { - width: 956px; - } - input.span9, - textarea.span9, - .uneditable-input.span9 { - width: 856px; - } - input.span8, - textarea.span8, - .uneditable-input.span8 { - width: 756px; - } - input.span7, - textarea.span7, - .uneditable-input.span7 { - width: 656px; - } - input.span6, - textarea.span6, - .uneditable-input.span6 { - width: 556px; - } - input.span5, - textarea.span5, - .uneditable-input.span5 { - width: 456px; - } - input.span4, - textarea.span4, - .uneditable-input.span4 { - width: 356px; - } - input.span3, - textarea.span3, - .uneditable-input.span3 { - width: 256px; - } - input.span2, - textarea.span2, - .uneditable-input.span2 { - width: 156px; - } - input.span1, - textarea.span1, - .uneditable-input.span1 { - width: 56px; - } - .thumbnails { - margin-left: -30px; - } - .thumbnails > li { - margin-left: 30px; - } - .row-fluid .thumbnails { - margin-left: 0; - } -} -@media (max-width: 979px) { - body { - padding-top: 0; - } - .navbar-fixed-top, - .navbar-fixed-bottom { - position: static; - } - .navbar-fixed-top { - margin-bottom: 20px; - } - .navbar-fixed-bottom { - margin-top: 20px; - } - .navbar-fixed-top .navbar-inner, - .navbar-fixed-bottom .navbar-inner { - padding: 5px; - } - .navbar .container { - width: auto; - padding: 0; - } - .navbar .brand { - padding-left: 10px; - padding-right: 10px; - margin: 0 0 0 -5px; - } - .nav-collapse { - clear: both; - } - .nav-collapse .nav { - float: none; - margin: 0 0 10px; - } - .nav-collapse .nav > li { - float: none; - } - .nav-collapse .nav > li > a { - margin-bottom: 2px; - } - .nav-collapse .nav > .divider-vertical { - display: none; - } - .nav-collapse .nav .nav-header { - color: #777777; - text-shadow: none; - } - .nav-collapse .nav > li > a, - .nav-collapse .dropdown-menu a { - padding: 9px 15px; - font-weight: bold; - color: #777777; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - } - .nav-collapse .btn { - padding: 4px 10px 4px; - font-weight: normal; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - } - .nav-collapse .dropdown-menu li + li a { - margin-bottom: 2px; - } - .nav-collapse .nav > li > a:hover, - .nav-collapse .nav > li > a:focus, - .nav-collapse .dropdown-menu a:hover, - .nav-collapse .dropdown-menu a:focus { - background-color: #f2f2f2; - } - .navbar-inverse .nav-collapse .nav > li > a, - .navbar-inverse .nav-collapse .dropdown-menu a { - color: #999999; - } - .navbar-inverse .nav-collapse .nav > li > a:hover, - .navbar-inverse .nav-collapse .nav > li > a:focus, - .navbar-inverse .nav-collapse .dropdown-menu a:hover, - .navbar-inverse .nav-collapse .dropdown-menu a:focus { - background-color: #111111; - } - .nav-collapse.in .btn-group { - margin-top: 5px; - padding: 0; - } - .nav-collapse .dropdown-menu { - position: static; - top: auto; - left: auto; - float: none; - display: none; - max-width: none; - margin: 0 15px; - padding: 0; - background-color: transparent; - border: none; - -webkit-border-radius: 0; - -moz-border-radius: 0; - border-radius: 0; - -webkit-box-shadow: none; - -moz-box-shadow: none; - box-shadow: none; - } - .nav-collapse .open > .dropdown-menu { - display: block; - } - .nav-collapse .dropdown-menu:before, - .nav-collapse .dropdown-menu:after { - display: none; - } - .nav-collapse .dropdown-menu .divider { - display: none; - } - .nav-collapse .nav > li > .dropdown-menu:before, - .nav-collapse .nav > li > .dropdown-menu:after { - display: none; - } - .nav-collapse .navbar-form, - .nav-collapse .navbar-search { - float: none; - padding: 10px 15px; - margin: 10px 0; - border-top: 1px solid #f2f2f2; - border-bottom: 1px solid #f2f2f2; - -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); - -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); - box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1); - } - .navbar-inverse .nav-collapse .navbar-form, - .navbar-inverse .nav-collapse .navbar-search { - border-top-color: #111111; - border-bottom-color: #111111; - } - .navbar .nav-collapse .nav.pull-right { - float: none; - margin-left: 0; - } - .nav-collapse, - .nav-collapse.collapse { - overflow: hidden; - height: 0; - } - .navbar .btn-navbar { - display: block; - } - .navbar-static .navbar-inner { - padding-left: 10px; - padding-right: 10px; - } -} -@media (min-width: 980px) { - .nav-collapse.collapse { - height: auto !important; - overflow: visible !important; - } -} diff --git a/tools/ngui/static/bootstrap/css/bootstrap.min.css b/tools/ngui/static/bootstrap/css/bootstrap.min.css deleted file mode 100644 index 622b27fb02f9..000000000000 --- a/tools/ngui/static/bootstrap/css/bootstrap.min.css +++ /dev/null @@ -1,874 +0,0 @@ -/*! - * Bootstrap v2.3.2 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */ -.clearfix{*zoom:1;}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0;} -.clearfix:after{clear:both;} -.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;} -.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} -article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block;} -audio,canvas,video{display:inline-block;*display:inline;*zoom:1;} -audio:not([controls]){display:none;} -html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;} -a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} -a:hover,a:active{outline:0;} -sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline;} -sup{top:-0.5em;} -sub{bottom:-0.25em;} -img{max-width:100%;width:auto\9;height:auto;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;} -#map_canvas img,.google-maps img{max-width:none;} -button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle;} -button,input{*overflow:visible;line-height:normal;} -button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0;} -button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;} -label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer;} -input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield;} -input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none;} -textarea{overflow:auto;vertical-align:top;} -@media print{*{text-shadow:none !important;color:#000 !important;background:transparent !important;box-shadow:none !important;} a,a:visited{text-decoration:underline;} a[href]:after{content:" (" attr(href) ")";} abbr[title]:after{content:" (" attr(title) ")";} .ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:"";} pre,blockquote{border:1px solid #999;page-break-inside:avoid;} thead{display:table-header-group;} tr,img{page-break-inside:avoid;} img{max-width:100% !important;} @page {margin:0.5cm;}p,h2,h3{orphans:3;widows:3;} h2,h3{page-break-after:avoid;}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;line-height:20px;color:#333333;background-color:#ffffff;} -a{color:#0088cc;text-decoration:none;} -a:hover,a:focus{color:#005580;text-decoration:underline;} -.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);} -.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px;} -.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} -.row:after{clear:both;} -[class*="span"]{float:left;min-height:1px;margin-left:20px;} -.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;} -.span12{width:940px;} -.span11{width:860px;} -.span10{width:780px;} -.span9{width:700px;} -.span8{width:620px;} -.span7{width:540px;} -.span6{width:460px;} -.span5{width:380px;} -.span4{width:300px;} -.span3{width:220px;} -.span2{width:140px;} -.span1{width:60px;} -.offset12{margin-left:980px;} -.offset11{margin-left:900px;} -.offset10{margin-left:820px;} -.offset9{margin-left:740px;} -.offset8{margin-left:660px;} -.offset7{margin-left:580px;} -.offset6{margin-left:500px;} -.offset5{margin-left:420px;} -.offset4{margin-left:340px;} -.offset3{margin-left:260px;} -.offset2{margin-left:180px;} -.offset1{margin-left:100px;} -.row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} -.row-fluid:after{clear:both;} -.row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;} -.row-fluid [class*="span"]:first-child{margin-left:0;} -.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%;} -.row-fluid .span12{width:100%;*width:99.94680851063829%;} -.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%;} -.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%;} -.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%;} -.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%;} -.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%;} -.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%;} -.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%;} -.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%;} -.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%;} -.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%;} -.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%;} -.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%;} -.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%;} -.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%;} -.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%;} -.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%;} -.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%;} -.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%;} -.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%;} -.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%;} -.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%;} -.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%;} -.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%;} -.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%;} -.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%;} -.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%;} -.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%;} -.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%;} -.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%;} -.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%;} -.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%;} -.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%;} -.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%;} -.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%;} -.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%;} -[class*="span"].hide,.row-fluid [class*="span"].hide{display:none;} -[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right;} -.container{margin-right:auto;margin-left:auto;*zoom:1;}.container:before,.container:after{display:table;content:"";line-height:0;} -.container:after{clear:both;} -.container-fluid{padding-right:20px;padding-left:20px;*zoom:1;}.container-fluid:before,.container-fluid:after{display:table;content:"";line-height:0;} -.container-fluid:after{clear:both;} -p{margin:0 0 10px;} -.lead{margin-bottom:20px;font-size:19.5px;font-weight:200;line-height:30px;} -small{font-size:85%;} -strong{font-weight:bold;} -em{font-style:italic;} -cite{font-style:normal;} -.muted{color:#999999;} -a.muted:hover,a.muted:focus{color:#808080;} -.text-warning{color:#c09853;} -a.text-warning:hover,a.text-warning:focus{color:#a47e3c;} -.text-error{color:#b94a48;} -a.text-error:hover,a.text-error:focus{color:#953b39;} -.text-info{color:#3a87ad;} -a.text-info:hover,a.text-info:focus{color:#2d6987;} -.text-success{color:#468847;} -a.text-success:hover,a.text-success:focus{color:#356635;} -.text-left{text-align:left;} -.text-right{text-align:right;} -.text-center{text-align:center;} -h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility;}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999999;} -h1,h2,h3{line-height:40px;} -h1{font-size:35.75px;} -h2{font-size:29.25px;} -h3{font-size:22.75px;} -h4{font-size:16.25px;} -h5{font-size:13px;} -h6{font-size:11.049999999999999px;} -h1 small{font-size:22.75px;} -h2 small{font-size:16.25px;} -h3 small{font-size:13px;} -h4 small{font-size:13px;} -.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eeeeee;} -ul,ol{padding:0;margin:0 0 10px 25px;} -ul ul,ul ol,ol ol,ol ul{margin-bottom:0;} -li{line-height:20px;} -ul.unstyled,ol.unstyled{margin-left:0;list-style:none;} -ul.inline,ol.inline{margin-left:0;list-style:none;}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;*zoom:1;padding-left:5px;padding-right:5px;} -dl{margin-bottom:20px;} -dt,dd{line-height:20px;} -dt{font-weight:bold;} -dd{margin-left:10px;} -.dl-horizontal{*zoom:1;}.dl-horizontal:before,.dl-horizontal:after{display:table;content:"";line-height:0;} -.dl-horizontal:after{clear:both;} -.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} -.dl-horizontal dd{margin-left:180px;} -hr{margin:20px 0;border:0;border-top:1px solid #eeeeee;border-bottom:1px solid #ffffff;} -abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999999;} -abbr.initialism{font-size:90%;text-transform:uppercase;} -blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eeeeee;}blockquote p{margin-bottom:0;font-size:16.25px;font-weight:300;line-height:1.25;} -blockquote small{display:block;line-height:20px;color:#999999;}blockquote small:before{content:'\2014 \00A0';} -blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eeeeee;border-left:0;}blockquote.pull-right p,blockquote.pull-right small{text-align:right;} -blockquote.pull-right small:before{content:'';} -blockquote.pull-right small:after{content:'\00A0 \2014';} -q:before,q:after,blockquote:before,blockquote:after{content:"";} -address{display:block;margin-bottom:20px;font-style:normal;line-height:20px;} -code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:11px;color:#333333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -code{padding:2px 4px;color:#d14;background-color:#f7f7f9;border:1px solid #e1e1e8;white-space:nowrap;} -pre{display:block;padding:9.5px;margin:0 0 10px;font-size:12px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}pre.prettyprint{margin-bottom:20px;} -pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0;} -.pre-scrollable{max-height:340px;overflow-y:scroll;} -.label,.badge{display:inline-block;padding:2px 4px;font-size:10.998px;font-weight:bold;line-height:14px;color:#ffffff;vertical-align:baseline;white-space:nowrap;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#999999;} -.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -.badge{padding-left:9px;padding-right:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px;} -.label:empty,.badge:empty{display:none;} -a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#ffffff;text-decoration:none;cursor:pointer;} -.label-important,.badge-important{background-color:#b94a48;} -.label-important[href],.badge-important[href]{background-color:#953b39;} -.label-warning,.badge-warning{background-color:#f89406;} -.label-warning[href],.badge-warning[href]{background-color:#c67605;} -.label-success,.badge-success{background-color:#468847;} -.label-success[href],.badge-success[href]{background-color:#356635;} -.label-info,.badge-info{background-color:#3a87ad;} -.label-info[href],.badge-info[href]{background-color:#2d6987;} -.label-inverse,.badge-inverse{background-color:#333333;} -.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a;} -.btn .label,.btn .badge{position:relative;top:-1px;} -.btn-mini .label,.btn-mini .badge{top:0;} -table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;} -.table{width:100%;margin-bottom:20px;}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #dddddd;} -.table th{font-weight:bold;} -.table thead th{vertical-align:bottom;} -.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0;} -.table tbody+tbody{border-top:2px solid #dddddd;} -.table .table{background-color:#ffffff;} -.table-condensed th,.table-condensed td{padding:4px 5px;} -.table-bordered{border:1px solid #dddddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.table-bordered th,.table-bordered td{border-left:1px solid #dddddd;} -.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0;} -.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} -.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;} -.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} -.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} -.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;-moz-border-radius-bottomleft:0;border-bottom-left-radius:0;} -.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;-moz-border-radius-bottomright:0;border-bottom-right-radius:0;} -.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} -.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;} -.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9;} -.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5;} -table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0;} -.table td.span1,.table th.span1{float:none;width:44px;margin-left:0;} -.table td.span2,.table th.span2{float:none;width:124px;margin-left:0;} -.table td.span3,.table th.span3{float:none;width:204px;margin-left:0;} -.table td.span4,.table th.span4{float:none;width:284px;margin-left:0;} -.table td.span5,.table th.span5{float:none;width:364px;margin-left:0;} -.table td.span6,.table th.span6{float:none;width:444px;margin-left:0;} -.table td.span7,.table th.span7{float:none;width:524px;margin-left:0;} -.table td.span8,.table th.span8{float:none;width:604px;margin-left:0;} -.table td.span9,.table th.span9{float:none;width:684px;margin-left:0;} -.table td.span10,.table th.span10{float:none;width:764px;margin-left:0;} -.table td.span11,.table th.span11{float:none;width:844px;margin-left:0;} -.table td.span12,.table th.span12{float:none;width:924px;margin-left:0;} -.table tbody tr.success>td{background-color:#dff0d8;} -.table tbody tr.error>td{background-color:#f2dede;} -.table tbody tr.warning>td{background-color:#fcf8e3;} -.table tbody tr.info>td{background-color:#d9edf7;} -.table-hover tbody tr.success:hover>td{background-color:#d0e9c6;} -.table-hover tbody tr.error:hover>td{background-color:#ebcccc;} -.table-hover tbody tr.warning:hover>td{background-color:#faf2cc;} -.table-hover tbody tr.info:hover>td{background-color:#c4e3f3;} -form{margin:0 0 20px;} -fieldset{padding:0;margin:0;border:0;} -legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:19.5px;line-height:40px;color:#333333;border:0;border-bottom:1px solid #e5e5e5;}legend small{font-size:15px;color:#999999;} -label,input,button,select,textarea{font-size:13px;font-weight:normal;line-height:20px;} -input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;} -label{display:block;margin-bottom:5px;} -select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:13px;line-height:20px;color:#555555;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;vertical-align:middle;} -input,textarea,.uneditable-input{width:206px;} -textarea{height:auto;} -textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear .2s, box-shadow linear .2s;-moz-transition:border linear .2s, box-shadow linear .2s;-o-transition:border linear .2s, box-shadow linear .2s;transition:border linear .2s, box-shadow linear .2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);} -input[type="radio"],input[type="checkbox"]{margin:4px 0 0;*margin-top:0;margin-top:1px \9;line-height:normal;} -input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;} -select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px;} -select{width:220px;border:1px solid #cccccc;background-color:#ffffff;} -select[multiple],select[size]{height:auto;} -select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} -.uneditable-input,.uneditable-textarea{color:#999999;background-color:#fcfcfc;border-color:#cccccc;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);cursor:not-allowed;} -.uneditable-input{overflow:hidden;white-space:nowrap;} -.uneditable-textarea{width:auto;height:auto;} -input:-moz-placeholder,textarea:-moz-placeholder{color:#999999;} -input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999999;} -input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999999;} -.radio,.checkbox{min-height:20px;padding-left:20px;} -.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px;} -.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px;} -.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle;} -.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px;} -.input-mini{width:60px;} -.input-small{width:90px;} -.input-medium{width:150px;} -.input-large{width:210px;} -.input-xlarge{width:270px;} -.input-xxlarge{width:530px;} -input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0;} -.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block;} -input,textarea,.uneditable-input{margin-left:0;} -.controls-row [class*="span"]+[class*="span"]{margin-left:20px;} -input.span12,textarea.span12,.uneditable-input.span12{width:926px;} -input.span11,textarea.span11,.uneditable-input.span11{width:846px;} -input.span10,textarea.span10,.uneditable-input.span10{width:766px;} -input.span9,textarea.span9,.uneditable-input.span9{width:686px;} -input.span8,textarea.span8,.uneditable-input.span8{width:606px;} -input.span7,textarea.span7,.uneditable-input.span7{width:526px;} -input.span6,textarea.span6,.uneditable-input.span6{width:446px;} -input.span5,textarea.span5,.uneditable-input.span5{width:366px;} -input.span4,textarea.span4,.uneditable-input.span4{width:286px;} -input.span3,textarea.span3,.uneditable-input.span3{width:206px;} -input.span2,textarea.span2,.uneditable-input.span2{width:126px;} -input.span1,textarea.span1,.uneditable-input.span1{width:46px;} -.controls-row{*zoom:1;}.controls-row:before,.controls-row:after{display:table;content:"";line-height:0;} -.controls-row:after{clear:both;} -.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left;} -.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px;} -input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eeeeee;} -input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent;} -.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853;} -.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853;} -.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #dbc59e;} -.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853;} -.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48;} -.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48;} -.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #d59392;} -.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48;} -.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847;} -.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847;} -.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7aba7b;} -.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847;} -.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad;} -.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad;} -.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 6px #7ab5d3;} -.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad;} -input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b;}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7;} -.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1;}.form-actions:before,.form-actions:after{display:table;content:"";line-height:0;} -.form-actions:after{clear:both;} -.help-block,.help-inline{color:#595959;} -.help-block{display:block;margin-bottom:10px;} -.help-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;padding-left:5px;} -.input-append,.input-prepend{display:inline-block;margin-bottom:10px;vertical-align:middle;font-size:0;white-space:nowrap;}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:13px;} -.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2;} -.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:13px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #ffffff;background-color:#eeeeee;border:1px solid #ccc;} -.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546;} -.input-prepend .add-on,.input-prepend .btn{margin-right:-1px;} -.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} -.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} -.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px;} -.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} -.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} -.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} -.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} -.input-prepend.input-append .btn-group:first-child{margin-left:0;} -input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} -.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;} -.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;} -.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;} -.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;} -.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;*zoom:1;margin-bottom:0;vertical-align:middle;} -.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none;} -.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block;} -.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0;} -.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle;} -.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0;} -.control-group{margin-bottom:10px;} -legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate;} -.form-horizontal .control-group{margin-bottom:20px;*zoom:1;}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;content:"";line-height:0;} -.form-horizontal .control-group:after{clear:both;} -.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right;} -.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0;}.form-horizontal .controls:first-child{*padding-left:180px;} -.form-horizontal .help-block{margin-bottom:0;} -.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px;} -.form-horizontal .form-actions{padding-left:180px;} -.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:13px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333333;text-shadow:0 1px 1px rgba(255, 255, 255, 0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #ffffff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #ffffff, #e6e6e6);background-image:-o-linear-gradient(top, #ffffff, #e6e6e6);background-image:linear-gradient(to bottom, #ffffff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #cccccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333333;background-color:#e6e6e6;*background-color:#d9d9d9;} -.btn:active,.btn.active{background-color:#cccccc \9;} -.btn:first-child{*margin-left:0;} -.btn:hover,.btn:focus{color:#333333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position 0.1s linear;-moz-transition:background-position 0.1s linear;-o-transition:background-position 0.1s linear;transition:background-position 0.1s linear;} -.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;} -.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);} -.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:0.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} -.btn-large{padding:11px 19px;font-size:16.25px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px;} -.btn-small{padding:2px 10px;font-size:11.049999999999999px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0;} -.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px;} -.btn-mini{padding:0 6px;font-size:9.75px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} -.btn-block+.btn-block{margin-top:5px;} -input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%;} -.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255, 255, 255, 0.75);} -.btn-primary{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #0088cc, #0044cc);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));background-image:-webkit-linear-gradient(top, #0088cc, #0044cc);background-image:-o-linear-gradient(top, #0088cc, #0044cc);background-image:linear-gradient(to bottom, #0088cc, #0044cc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#0044cc #0044cc #002a80;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#0044cc;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#ffffff;background-color:#0044cc;*background-color:#003bb3;} -.btn-primary:active,.btn-primary.active{background-color:#003399 \9;} -.btn-warning{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#ffffff;background-color:#f89406;*background-color:#df8505;} -.btn-warning:active,.btn-warning.active{background-color:#c67605 \9;} -.btn-danger{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top, #ee5f5b, #bd362f);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f));background-image:-webkit-linear-gradient(top, #ee5f5b, #bd362f);background-image:-o-linear-gradient(top, #ee5f5b, #bd362f);background-image:linear-gradient(to bottom, #ee5f5b, #bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#ffffff;background-color:#bd362f;*background-color:#a9302a;} -.btn-danger:active,.btn-danger.active{background-color:#942a25 \9;} -.btn-success{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top, #62c462, #51a351);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351));background-image:-webkit-linear-gradient(top, #62c462, #51a351);background-image:-o-linear-gradient(top, #62c462, #51a351);background-image:linear-gradient(to bottom, #62c462, #51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#ffffff;background-color:#51a351;*background-color:#499249;} -.btn-success:active,.btn-success.active{background-color:#408140 \9;} -.btn-info{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top, #5bc0de, #2f96b4);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4));background-image:-webkit-linear-gradient(top, #5bc0de, #2f96b4);background-image:-o-linear-gradient(top, #5bc0de, #2f96b4);background-image:linear-gradient(to bottom, #5bc0de, #2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#ffffff;background-color:#2f96b4;*background-color:#2a85a0;} -.btn-info:active,.btn-info.active{background-color:#24748c \9;} -.btn-inverse{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#363636;background-image:-moz-linear-gradient(top, #444444, #222222);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222));background-image:-webkit-linear-gradient(top, #444444, #222222);background-image:-o-linear-gradient(top, #444444, #222222);background-image:linear-gradient(to bottom, #444444, #222222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0);border-color:#222222 #222222 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#222222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#ffffff;background-color:#222222;*background-color:#151515;} -.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9;} -button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px;}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0;} -button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px;} -button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px;} -button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px;} -.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} -.btn-link{border-color:transparent;cursor:pointer;color:#0088cc;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent;} -.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333333;text-decoration:none;} -[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat;margin-top:1px;} -.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png");} -.icon-glass{background-position:0 0;} -.icon-music{background-position:-24px 0;} -.icon-search{background-position:-48px 0;} -.icon-envelope{background-position:-72px 0;} -.icon-heart{background-position:-96px 0;} -.icon-star{background-position:-120px 0;} -.icon-star-empty{background-position:-144px 0;} -.icon-user{background-position:-168px 0;} -.icon-film{background-position:-192px 0;} -.icon-th-large{background-position:-216px 0;} -.icon-th{background-position:-240px 0;} -.icon-th-list{background-position:-264px 0;} -.icon-ok{background-position:-288px 0;} -.icon-remove{background-position:-312px 0;} -.icon-zoom-in{background-position:-336px 0;} -.icon-zoom-out{background-position:-360px 0;} -.icon-off{background-position:-384px 0;} -.icon-signal{background-position:-408px 0;} -.icon-cog{background-position:-432px 0;} -.icon-trash{background-position:-456px 0;} -.icon-home{background-position:0 -24px;} -.icon-file{background-position:-24px -24px;} -.icon-time{background-position:-48px -24px;} -.icon-road{background-position:-72px -24px;} -.icon-download-alt{background-position:-96px -24px;} -.icon-download{background-position:-120px -24px;} -.icon-upload{background-position:-144px -24px;} -.icon-inbox{background-position:-168px -24px;} -.icon-play-circle{background-position:-192px -24px;} -.icon-repeat{background-position:-216px -24px;} -.icon-refresh{background-position:-240px -24px;} -.icon-list-alt{background-position:-264px -24px;} -.icon-lock{background-position:-287px -24px;} -.icon-flag{background-position:-312px -24px;} -.icon-headphones{background-position:-336px -24px;} -.icon-volume-off{background-position:-360px -24px;} -.icon-volume-down{background-position:-384px -24px;} -.icon-volume-up{background-position:-408px -24px;} -.icon-qrcode{background-position:-432px -24px;} -.icon-barcode{background-position:-456px -24px;} -.icon-tag{background-position:0 -48px;} -.icon-tags{background-position:-25px -48px;} -.icon-book{background-position:-48px -48px;} -.icon-bookmark{background-position:-72px -48px;} -.icon-print{background-position:-96px -48px;} -.icon-camera{background-position:-120px -48px;} -.icon-font{background-position:-144px -48px;} -.icon-bold{background-position:-167px -48px;} -.icon-italic{background-position:-192px -48px;} -.icon-text-height{background-position:-216px -48px;} -.icon-text-width{background-position:-240px -48px;} -.icon-align-left{background-position:-264px -48px;} -.icon-align-center{background-position:-288px -48px;} -.icon-align-right{background-position:-312px -48px;} -.icon-align-justify{background-position:-336px -48px;} -.icon-list{background-position:-360px -48px;} -.icon-indent-left{background-position:-384px -48px;} -.icon-indent-right{background-position:-408px -48px;} -.icon-facetime-video{background-position:-432px -48px;} -.icon-picture{background-position:-456px -48px;} -.icon-pencil{background-position:0 -72px;} -.icon-map-marker{background-position:-24px -72px;} -.icon-adjust{background-position:-48px -72px;} -.icon-tint{background-position:-72px -72px;} -.icon-edit{background-position:-96px -72px;} -.icon-share{background-position:-120px -72px;} -.icon-check{background-position:-144px -72px;} -.icon-move{background-position:-168px -72px;} -.icon-step-backward{background-position:-192px -72px;} -.icon-fast-backward{background-position:-216px -72px;} -.icon-backward{background-position:-240px -72px;} -.icon-play{background-position:-264px -72px;} -.icon-pause{background-position:-288px -72px;} -.icon-stop{background-position:-312px -72px;} -.icon-forward{background-position:-336px -72px;} -.icon-fast-forward{background-position:-360px -72px;} -.icon-step-forward{background-position:-384px -72px;} -.icon-eject{background-position:-408px -72px;} -.icon-chevron-left{background-position:-432px -72px;} -.icon-chevron-right{background-position:-456px -72px;} -.icon-plus-sign{background-position:0 -96px;} -.icon-minus-sign{background-position:-24px -96px;} -.icon-remove-sign{background-position:-48px -96px;} -.icon-ok-sign{background-position:-72px -96px;} -.icon-question-sign{background-position:-96px -96px;} -.icon-info-sign{background-position:-120px -96px;} -.icon-screenshot{background-position:-144px -96px;} -.icon-remove-circle{background-position:-168px -96px;} -.icon-ok-circle{background-position:-192px -96px;} -.icon-ban-circle{background-position:-216px -96px;} -.icon-arrow-left{background-position:-240px -96px;} -.icon-arrow-right{background-position:-264px -96px;} -.icon-arrow-up{background-position:-289px -96px;} -.icon-arrow-down{background-position:-312px -96px;} -.icon-share-alt{background-position:-336px -96px;} -.icon-resize-full{background-position:-360px -96px;} -.icon-resize-small{background-position:-384px -96px;} -.icon-plus{background-position:-408px -96px;} -.icon-minus{background-position:-433px -96px;} -.icon-asterisk{background-position:-456px -96px;} -.icon-exclamation-sign{background-position:0 -120px;} -.icon-gift{background-position:-24px -120px;} -.icon-leaf{background-position:-48px -120px;} -.icon-fire{background-position:-72px -120px;} -.icon-eye-open{background-position:-96px -120px;} -.icon-eye-close{background-position:-120px -120px;} -.icon-warning-sign{background-position:-144px -120px;} -.icon-plane{background-position:-168px -120px;} -.icon-calendar{background-position:-192px -120px;} -.icon-random{background-position:-216px -120px;width:16px;} -.icon-comment{background-position:-240px -120px;} -.icon-magnet{background-position:-264px -120px;} -.icon-chevron-up{background-position:-288px -120px;} -.icon-chevron-down{background-position:-313px -119px;} -.icon-retweet{background-position:-336px -120px;} -.icon-shopping-cart{background-position:-360px -120px;} -.icon-folder-close{background-position:-384px -120px;width:16px;} -.icon-folder-open{background-position:-408px -120px;width:16px;} -.icon-resize-vertical{background-position:-432px -119px;} -.icon-resize-horizontal{background-position:-456px -118px;} -.icon-hdd{background-position:0 -144px;} -.icon-bullhorn{background-position:-24px -144px;} -.icon-bell{background-position:-48px -144px;} -.icon-certificate{background-position:-72px -144px;} -.icon-thumbs-up{background-position:-96px -144px;} -.icon-thumbs-down{background-position:-120px -144px;} -.icon-hand-right{background-position:-144px -144px;} -.icon-hand-left{background-position:-168px -144px;} -.icon-hand-up{background-position:-192px -144px;} -.icon-hand-down{background-position:-216px -144px;} -.icon-circle-arrow-right{background-position:-240px -144px;} -.icon-circle-arrow-left{background-position:-264px -144px;} -.icon-circle-arrow-up{background-position:-288px -144px;} -.icon-circle-arrow-down{background-position:-312px -144px;} -.icon-globe{background-position:-336px -144px;} -.icon-wrench{background-position:-360px -144px;} -.icon-tasks{background-position:-384px -144px;} -.icon-filter{background-position:-408px -144px;} -.icon-briefcase{background-position:-432px -144px;} -.icon-fullscreen{background-position:-456px -144px;} -.btn-group{position:relative;display:inline-block;*display:inline;*zoom:1;font-size:0;vertical-align:middle;white-space:nowrap;*margin-left:.3em;}.btn-group:first-child{*margin-left:0;} -.btn-group+.btn-group{margin-left:5px;} -.btn-toolbar{font-size:0;margin-top:10px;margin-bottom:10px;}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px;} -.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.btn-group>.btn+.btn{margin-left:-1px;} -.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:13px;} -.btn-group>.btn-mini{font-size:9.75px;} -.btn-group>.btn-small{font-size:11.049999999999999px;} -.btn-group>.btn-large{font-size:16.25px;} -.btn-group>.btn:first-child{margin-left:0;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} -.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} -.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;} -.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;} -.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2;} -.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0;} -.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);*padding-top:5px;*padding-bottom:5px;} -.btn-group>.btn-mini+.dropdown-toggle{padding-left:5px;padding-right:5px;*padding-top:2px;*padding-bottom:2px;} -.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px;} -.btn-group>.btn-large+.dropdown-toggle{padding-left:12px;padding-right:12px;*padding-top:7px;*padding-bottom:7px;} -.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05);} -.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6;} -.btn-group.open .btn-primary.dropdown-toggle{background-color:#0044cc;} -.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406;} -.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f;} -.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351;} -.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4;} -.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222222;} -.btn .caret{margin-top:8px;margin-left:0;} -.btn-large .caret{margin-top:6px;} -.btn-large .caret{border-left-width:5px;border-right-width:5px;border-top-width:5px;} -.btn-mini .caret,.btn-small .caret{margin-top:8px;} -.dropup .btn-large .caret{border-bottom-width:5px;} -.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} -.btn-group-vertical{display:inline-block;*display:inline;*zoom:1;} -.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.btn-group-vertical>.btn+.btn{margin-left:0;margin-top:-1px;} -.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;} -.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;} -.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0;} -.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;} -.nav{margin-left:0;margin-bottom:20px;list-style:none;} -.nav>li>a{display:block;} -.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eeeeee;} -.nav>li>a>img{max-width:none;} -.nav>.pull-right{float:right;} -.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999999;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);text-transform:uppercase;} -.nav li+.nav-header{margin-top:9px;} -.nav-list{padding-left:15px;padding-right:15px;margin-bottom:0;} -.nav-list>li>a,.nav-list .nav-header{margin-left:-15px;margin-right:-15px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);} -.nav-list>li>a{padding:3px 15px;} -.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.2);background-color:#0088cc;} -.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px;} -.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;} -.nav-tabs,.nav-pills{*zoom:1;}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;content:"";line-height:0;} -.nav-tabs:after,.nav-pills:after{clear:both;} -.nav-tabs>li,.nav-pills>li{float:left;} -.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px;} -.nav-tabs{border-bottom:1px solid #ddd;} -.nav-tabs>li{margin-bottom:-1px;} -.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eeeeee #eeeeee #dddddd;} -.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555555;background-color:#ffffff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default;} -.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;} -.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#ffffff;background-color:#0088cc;} -.nav-stacked>li{float:none;} -.nav-stacked>li>a{margin-right:0;} -.nav-tabs.nav-stacked{border-bottom:0;} -.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;} -.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} -.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{border-color:#ddd;z-index:2;} -.nav-pills.nav-stacked>li>a{margin-bottom:3px;} -.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px;} -.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;} -.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.nav .dropdown-toggle .caret{border-top-color:#0088cc;border-bottom-color:#0088cc;margin-top:6px;} -.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580;} -.nav-tabs .dropdown-toggle .caret{margin-top:8px;} -.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff;} -.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;} -.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer;} -.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#ffffff;background-color:#999999;border-color:#999999;} -.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;opacity:1;filter:alpha(opacity=100);} -.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999999;} -.tabbable{*zoom:1;}.tabbable:before,.tabbable:after{display:table;content:"";line-height:0;} -.tabbable:after{clear:both;} -.tab-content{overflow:auto;} -.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0;} -.tab-content>.tab-pane,.pill-content>.pill-pane{display:none;} -.tab-content>.active,.pill-content>.active{display:block;} -.tabs-below>.nav-tabs{border-top:1px solid #ddd;} -.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0;} -.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-bottom-color:transparent;border-top-color:#ddd;} -.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd;} -.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none;} -.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px;} -.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd;} -.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;} -.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eeeeee #dddddd #eeeeee #eeeeee;} -.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#ffffff;} -.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd;} -.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;} -.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eeeeee #eeeeee #eeeeee #dddddd;} -.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#ffffff;} -.nav>.disabled>a{color:#999999;} -.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;background-color:transparent;cursor:default;} -.navbar{overflow:visible;margin-bottom:20px;*position:relative;*z-index:2;} -.navbar-inner{min-height:40px;padding-left:20px;padding-right:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top, #ffffff, #f2f2f2);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2));background-image:-webkit-linear-gradient(top, #ffffff, #f2f2f2);background-image:-o-linear-gradient(top, #ffffff, #f2f2f2);background-image:linear-gradient(to bottom, #ffffff, #f2f2f2);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0);border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);*zoom:1;}.navbar-inner:before,.navbar-inner:after{display:table;content:"";line-height:0;} -.navbar-inner:after{clear:both;} -.navbar .container{width:auto;} -.nav-collapse.collapse{height:auto;overflow:visible;} -.navbar .brand{float:left;display:block;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777777;text-shadow:0 1px 0 #ffffff;}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none;} -.navbar-text{margin-bottom:0;line-height:40px;color:#777777;} -.navbar-link{color:#777777;}.navbar-link:hover,.navbar-link:focus{color:#333333;} -.navbar .divider-vertical{height:40px;margin:0 9px;border-left:1px solid #f2f2f2;border-right:1px solid #ffffff;} -.navbar .btn,.navbar .btn-group{margin-top:5px;} -.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0;} -.navbar-form{margin-bottom:0;*zoom:1;}.navbar-form:before,.navbar-form:after{display:table;content:"";line-height:0;} -.navbar-form:after{clear:both;} -.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px;} -.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0;} -.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px;} -.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap;}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0;} -.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0;}.navbar-search .search-query{margin-bottom:0;padding:4px 14px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} -.navbar-static-top{position:static;margin-bottom:0;}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0;} -.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px;} -.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0;} -.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-left:0;padding-right:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;} -.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;} -.navbar-fixed-top{top:0;} -.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,.1);box-shadow:0 1px 10px rgba(0,0,0,.1);} -.navbar-fixed-bottom{bottom:0;}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,.1);box-shadow:0 -1px 10px rgba(0,0,0,.1);} -.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0;} -.navbar .nav.pull-right{float:right;margin-right:0;} -.navbar .nav>li{float:left;} -.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777777;text-decoration:none;text-shadow:0 1px 0 #ffffff;} -.navbar .nav .dropdown-toggle .caret{margin-top:8px;} -.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{background-color:transparent;color:#333333;text-decoration:none;} -.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);-moz-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);} -.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-left:5px;margin-right:5px;color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#ededed;background-image:-moz-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5));background-image:-webkit-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-o-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:linear-gradient(to bottom, #f2f2f2, #e5e5e5);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0);border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e5e5e5;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075);box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075);}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#ffffff;background-color:#e5e5e5;*background-color:#d9d9d9;} -.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#cccccc \9;} -.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);-moz-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);} -.btn-navbar .icon-bar+.icon-bar{margin-top:3px;} -.navbar .nav>li>.dropdown-menu:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-bottom-color:rgba(0, 0, 0, 0.2);position:absolute;top:-7px;left:9px;} -.navbar .nav>li>.dropdown-menu:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid #ffffff;position:absolute;top:-6px;left:10px;} -.navbar-fixed-bottom .nav>li>.dropdown-menu:before{border-top:7px solid #ccc;border-top-color:rgba(0, 0, 0, 0.2);border-bottom:0;bottom:-7px;top:auto;} -.navbar-fixed-bottom .nav>li>.dropdown-menu:after{border-top:6px solid #ffffff;border-bottom:0;bottom:-6px;top:auto;} -.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333333;border-bottom-color:#333333;} -.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e5e5e5;color:#555555;} -.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777777;border-bottom-color:#777777;} -.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;} -.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{left:auto;right:0;}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{left:auto;right:12px;} -.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{left:auto;right:13px;} -.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{left:auto;right:100%;margin-left:0;margin-right:-1px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;} -.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top, #222222, #111111);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111));background-image:-webkit-linear-gradient(top, #222222, #111111);background-image:-o-linear-gradient(top, #222222, #111111);background-image:linear-gradient(to bottom, #222222, #111111);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0);border-color:#252525;} -.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999999;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#ffffff;} -.navbar-inverse .brand{color:#999999;} -.navbar-inverse .navbar-text{color:#999999;} -.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{background-color:transparent;color:#ffffff;} -.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#ffffff;background-color:#111111;} -.navbar-inverse .navbar-link{color:#999999;}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#ffffff;} -.navbar-inverse .divider-vertical{border-left-color:#111111;border-right-color:#222222;} -.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{background-color:#111111;color:#ffffff;} -.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} -.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999999;border-bottom-color:#999999;} -.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;} -.navbar-inverse .navbar-search .search-query{color:#ffffff;background-color:#515151;border-color:#111111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15);box-shadow:inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none;}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#cccccc;} -.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#cccccc;} -.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#cccccc;} -.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333333;text-shadow:0 1px 0 #ffffff;background-color:#ffffff;border:0;-webkit-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);-moz-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);box-shadow:0 0 3px rgba(0, 0, 0, 0.15);outline:0;} -.navbar-inverse .btn-navbar{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e0e0e;background-image:-moz-linear-gradient(top, #151515, #040404);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404));background-image:-webkit-linear-gradient(top, #151515, #040404);background-image:-o-linear-gradient(top, #151515, #040404);background-image:linear-gradient(to bottom, #151515, #040404);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0);border-color:#040404 #040404 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#040404;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#ffffff;background-color:#040404;*background-color:#000000;} -.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000000 \9;} -.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.breadcrumb>li{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 0 #ffffff;}.breadcrumb>li>.divider{padding:0 5px;color:#ccc;} -.breadcrumb>.active{color:#999999;} -.pagination{margin:20px 0;} -.pagination ul{display:inline-block;*display:inline;*zoom:1;margin-left:0;margin-bottom:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);} -.pagination ul>li{display:inline;} -.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#ffffff;border:1px solid #dddddd;border-left-width:0;} -.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5;} -.pagination ul>.active>a,.pagination ul>.active>span{color:#999999;cursor:default;} -.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999999;background-color:transparent;cursor:default;} -.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;} -.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;} -.pagination-centered{text-align:center;} -.pagination-right{text-align:right;} -.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:16.25px;} -.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;} -.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;} -.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-top-left-radius:3px;-moz-border-radius-topleft:3px;border-top-left-radius:3px;-webkit-border-bottom-left-radius:3px;-moz-border-radius-bottomleft:3px;border-bottom-left-radius:3px;} -.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;-moz-border-radius-topright:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;-moz-border-radius-bottomright:3px;border-bottom-right-radius:3px;} -.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.049999999999999px;} -.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:9.75px;} -.pager{margin:20px 0;list-style:none;text-align:center;*zoom:1;}.pager:before,.pager:after{display:table;content:"";line-height:0;} -.pager:after{clear:both;} -.pager li{display:inline;} -.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;} -.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5;} -.pager .next>a,.pager .next>span{float:right;} -.pager .previous>a,.pager .previous>span{float:left;} -.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999999;background-color:#fff;cursor:default;} -.thumbnails{margin-left:-20px;list-style:none;*zoom:1;}.thumbnails:before,.thumbnails:after{display:table;content:"";line-height:0;} -.thumbnails:after{clear:both;} -.row-fluid .thumbnails{margin-left:0;} -.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px;} -.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-webkit-transition:all 0.2s ease-in-out;-moz-transition:all 0.2s ease-in-out;-o-transition:all 0.2s ease-in-out;transition:all 0.2s ease-in-out;} -a.thumbnail:hover,a.thumbnail:focus{border-color:#0088cc;-webkit-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);-moz-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);} -.thumbnail>img{display:block;max-width:100%;margin-left:auto;margin-right:auto;} -.thumbnail .caption{padding:9px;color:#555555;} -.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.alert,.alert h4{color:#c09853;} -.alert h4{margin:0;} -.alert .close{position:relative;top:-2px;right:-21px;line-height:20px;} -.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#468847;} -.alert-success h4{color:#468847;} -.alert-danger,.alert-error{background-color:#f2dede;border-color:#eed3d7;color:#b94a48;} -.alert-danger h4,.alert-error h4{color:#b94a48;} -.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#3a87ad;} -.alert-info h4{color:#3a87ad;} -.alert-block{padding-top:14px;padding-bottom:14px;} -.alert-block>p,.alert-block>ul{margin-bottom:0;} -.alert-block p+p{margin-top:5px;} -@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-o-keyframes progress-bar-stripes{from{background-position:0 0;} to{background-position:40px 0;}}@keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f7f7f7;background-image:-moz-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9));background-image:-webkit-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-o-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:linear-gradient(to bottom, #f5f5f5, #f9f9f9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.progress .bar{width:0%;height:100%;color:#ffffff;float:left;font-size:12px;text-align:center;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top, #149bdf, #0480be);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be));background-image:-webkit-linear-gradient(top, #149bdf, #0480be);background-image:-o-linear-gradient(top, #149bdf, #0480be);background-image:linear-gradient(to bottom, #149bdf, #0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width 0.6s ease;-moz-transition:width 0.6s ease;-o-transition:width 0.6s ease;transition:width 0.6s ease;} -.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15);} -.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px;} -.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite;} -.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top, #ee5f5b, #c43c35);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35));background-image:-webkit-linear-gradient(top, #ee5f5b, #c43c35);background-image:-o-linear-gradient(top, #ee5f5b, #c43c35);background-image:linear-gradient(to bottom, #ee5f5b, #c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0);} -.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top, #62c462, #57a957);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957));background-image:-webkit-linear-gradient(top, #62c462, #57a957);background-image:-o-linear-gradient(top, #62c462, #57a957);background-image:linear-gradient(to bottom, #62c462, #57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0);} -.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top, #5bc0de, #339bb9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9));background-image:-webkit-linear-gradient(top, #5bc0de, #339bb9);background-image:-o-linear-gradient(top, #5bc0de, #339bb9);background-image:linear-gradient(to bottom, #5bc0de, #339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0);} -.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);} -.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);} -.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eeeeee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;color:inherit;letter-spacing:-1px;} -.hero-unit li{line-height:30px;} -.media,.media-body{overflow:hidden;*overflow:visible;zoom:1;} -.media,.media .media{margin-top:15px;} -.media:first-child{margin-top:0;} -.media-object{display:block;} -.media-heading{margin:0 0 5px;} -.media>.pull-left{margin-right:10px;} -.media>.pull-right{margin-left:10px;} -.media-list{margin-left:0;list-style:none;} -.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);}.tooltip.in{opacity:0.8;filter:alpha(opacity=80);} -.tooltip.top{margin-top:-3px;padding:5px 0;} -.tooltip.right{margin-left:3px;padding:0 5px;} -.tooltip.bottom{margin-top:3px;padding:5px 0;} -.tooltip.left{margin-left:-3px;padding:0 5px;} -.tooltip-inner{max-width:200px;padding:8px;color:#ffffff;text-align:center;text-decoration:none;background-color:#000000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid;} -.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000000;} -.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000000;} -.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000000;} -.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000000;} -.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;background-color:#ffffff;-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);white-space:normal;}.popover.top{margin-top:-10px;} -.popover.right{margin-left:10px;} -.popover.bottom{margin-top:10px;} -.popover.left{margin-left:-10px;} -.popover-title{margin:0;padding:8px 14px;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0;}.popover-title:empty{display:none;} -.popover-content{padding:9px 14px;} -.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid;} -.popover .arrow{border-width:11px;} -.popover .arrow:after{border-width:10px;content:"";} -.popover.top .arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0, 0, 0, 0.25);bottom:-11px;}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#ffffff;} -.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0, 0, 0, 0.25);}.popover.right .arrow:after{left:1px;bottom:-10px;border-left-width:0;border-right-color:#ffffff;} -.popover.bottom .arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0, 0, 0, 0.25);top:-11px;}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#ffffff;} -.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0, 0, 0, 0.25);}.popover.left .arrow:after{right:1px;border-right-width:0;border-left-color:#ffffff;bottom:-10px;} -.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000000;}.modal-backdrop.fade{opacity:0;} -.modal-backdrop,.modal-backdrop.fade.in{opacity:0.8;filter:alpha(opacity=80);} -.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#ffffff;border:1px solid #999;border:1px solid rgba(0, 0, 0, 0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-moz-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box;outline:none;}.modal.fade{-webkit-transition:opacity .3s linear, top .3s ease-out;-moz-transition:opacity .3s linear, top .3s ease-out;-o-transition:opacity .3s linear, top .3s ease-out;transition:opacity .3s linear, top .3s ease-out;top:-25%;} -.modal.fade.in{top:10%;} -.modal-header{padding:9px 15px;border-bottom:1px solid #eee;}.modal-header .close{margin-top:2px;} -.modal-header h3{margin:0;line-height:30px;} -.modal-body{position:relative;overflow-y:auto;max-height:400px;padding:15px;} -.modal-form{margin-bottom:0;} -.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #ffffff;-moz-box-shadow:inset 0 1px 0 #ffffff;box-shadow:inset 0 1px 0 #ffffff;*zoom:1;}.modal-footer:before,.modal-footer:after{display:table;content:"";line-height:0;} -.modal-footer:after{clear:both;} -.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0;} -.modal-footer .btn-group .btn+.btn{margin-left:-1px;} -.modal-footer .btn-block+.btn-block{margin-left:0;} -.dropup,.dropdown{position:relative;} -.dropdown-toggle{*margin-bottom:-3px;} -.dropdown-toggle:active,.open .dropdown-toggle{outline:0;} -.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000000;border-right:4px solid transparent;border-left:4px solid transparent;content:"";} -.dropdown .caret{margin-top:8px;margin-left:2px;} -.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#ffffff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;}.dropdown-menu.pull-right{right:0;left:auto;} -.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;} -.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333333;white-space:nowrap;} -.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{text-decoration:none;color:#ffffff;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);} -.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#ffffff;text-decoration:none;outline:0;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);} -.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999999;} -.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);cursor:default;} -.open{*z-index:1000;}.open>.dropdown-menu{display:block;} -.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990;} -.pull-right>.dropdown-menu{right:0;left:auto;} -.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000000;content:"";} -.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px;} -.dropdown-submenu{position:relative;} -.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px;} -.dropdown-submenu:hover>.dropdown-menu{display:block;} -.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0;} -.dropdown-submenu>a:after{display:block;content:" ";float:right;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 0 5px 5px;border-left-color:#cccccc;margin-top:5px;margin-right:-10px;} -.dropdown-submenu:hover>a:after{border-left-color:#ffffff;} -.dropdown-submenu.pull-left{float:none;}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;} -.dropdown .dropdown-menu .nav-header{padding-left:20px;padding-right:20px;} -.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.accordion{margin-bottom:20px;} -.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} -.accordion-heading{border-bottom:0;} -.accordion-heading .accordion-toggle{display:block;padding:8px 15px;} -.accordion-toggle{cursor:pointer;} -.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5;} -.carousel{position:relative;margin-bottom:20px;line-height:1;} -.carousel-inner{overflow:hidden;width:100%;position:relative;} -.carousel-inner>.item{display:none;position:relative;-webkit-transition:0.6s ease-in-out left;-moz-transition:0.6s ease-in-out left;-o-transition:0.6s ease-in-out left;transition:0.6s ease-in-out left;}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1;} -.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block;} -.carousel-inner>.active{left:0;} -.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%;} -.carousel-inner>.next{left:100%;} -.carousel-inner>.prev{left:-100%;} -.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0;} -.carousel-inner>.active.left{left:-100%;} -.carousel-inner>.active.right{left:100%;} -.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#ffffff;text-align:center;background:#222222;border:3px solid #ffffff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:0.5;filter:alpha(opacity=50);}.carousel-control.right{left:auto;right:15px;} -.carousel-control:hover,.carousel-control:focus{color:#ffffff;text-decoration:none;opacity:0.9;filter:alpha(opacity=90);} -.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none;}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255, 255, 255, 0.25);border-radius:5px;} -.carousel-indicators .active{background-color:#fff;} -.carousel-caption{position:absolute;left:0;right:0;bottom:0;padding:15px;background:#333333;background:rgba(0, 0, 0, 0.75);} -.carousel-caption h4,.carousel-caption p{color:#ffffff;line-height:20px;} -.carousel-caption h4{margin:0 0 5px;} -.carousel-caption p{margin-bottom:0;} -.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);}.well blockquote{border-color:#ddd;border-color:rgba(0, 0, 0, 0.15);} -.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;} -.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} -.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000000;text-shadow:0 1px 0 #ffffff;opacity:0.2;filter:alpha(opacity=20);}.close:hover,.close:focus{color:#000000;text-decoration:none;cursor:pointer;opacity:0.4;filter:alpha(opacity=40);} -button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none;} -.pull-right{float:right;} -.pull-left{float:left;} -.hide{display:none;} -.show{display:block;} -.invisible{visibility:hidden;} -.affix{position:fixed;} -.fade{opacity:0;-webkit-transition:opacity 0.15s linear;-moz-transition:opacity 0.15s linear;-o-transition:opacity 0.15s linear;transition:opacity 0.15s linear;}.fade.in{opacity:1;} -.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height 0.35s ease;-moz-transition:height 0.35s ease;-o-transition:height 0.35s ease;transition:height 0.35s ease;}.collapse.in{height:auto;} -@-ms-viewport{width:device-width;}.hidden{display:none;visibility:hidden;} -.visible-phone{display:none !important;} -.visible-tablet{display:none !important;} -.hidden-desktop{display:none !important;} -.visible-desktop{display:inherit !important;} -@media (min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important ;} .visible-tablet{display:inherit !important;} .hidden-tablet{display:none !important;}}@media (max-width:767px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important;} .visible-phone{display:inherit !important;} .hidden-phone{display:none !important;}}.visible-print{display:none !important;} -@media print{.visible-print{display:inherit !important;} .hidden-print{display:none !important;}}@media (max-width:767px){body{padding-left:20px;padding-right:20px;} .navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-left:-20px;margin-right:-20px;} .container-fluid{padding:0;} .dl-horizontal dt{float:none;clear:none;width:auto;text-align:left;} .dl-horizontal dd{margin-left:0;} .container{width:auto;} .row-fluid{width:100%;} .row,.thumbnails{margin-left:0;} .thumbnails>li{float:none;margin-left:0;} [class*="span"],.uneditable-input[class*="span"],.row-fluid [class*="span"]{float:none;display:block;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .row-fluid [class*="offset"]:first-child{margin-left:0;} .input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto;} .controls-row [class*="span"]+[class*="span"]{margin-left:0;} .modal{position:fixed;top:20px;left:20px;right:20px;width:auto;margin:0;}.modal.fade{top:-100px;} .modal.fade.in{top:20px;}}@media (max-width:480px){.nav-collapse{-webkit-transform:translate3d(0, 0, 0);} .page-header h1 small{display:block;line-height:20px;} input[type="checkbox"],input[type="radio"]{border:1px solid #ccc;} .form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left;} .form-horizontal .controls{margin-left:0;} .form-horizontal .control-list{padding-top:0;} .form-horizontal .form-actions{padding-left:10px;padding-right:10px;} .media .pull-left,.media .pull-right{float:none;display:block;margin-bottom:10px;} .media-object{margin-right:0;margin-left:0;} .modal{top:10px;left:10px;right:10px;} .modal-header .close{padding:10px;margin:-10px;} .carousel-caption{position:static;}}@media (min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:20px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px;} .span12{width:724px;} .span11{width:662px;} .span10{width:600px;} .span9{width:538px;} .span8{width:476px;} .span7{width:414px;} .span6{width:352px;} .span5{width:290px;} .span4{width:228px;} .span3{width:166px;} .span2{width:104px;} .span1{width:42px;} .offset12{margin-left:764px;} .offset11{margin-left:702px;} .offset10{margin-left:640px;} .offset9{margin-left:578px;} .offset8{margin-left:516px;} .offset7{margin-left:454px;} .offset6{margin-left:392px;} .offset5{margin-left:330px;} .offset4{margin-left:268px;} .offset3{margin-left:206px;} .offset2{margin-left:144px;} .offset1{margin-left:82px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%;} .row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%;} .row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%;} .row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%;} .row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%;} .row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%;} .row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%;} .row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%;} .row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%;} .row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%;} .row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%;} .row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%;} .row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%;} .row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%;} .row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%;} .row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%;} .row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%;} .row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%;} .row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%;} .row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%;} .row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%;} .row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%;} .row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%;} .row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%;} .row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%;} .row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%;} .row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%;} .row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%;} .row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%;} .row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%;} .row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%;} .row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%;} .row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%;} .row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%;} .row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:20px;} input.span12,textarea.span12,.uneditable-input.span12{width:710px;} input.span11,textarea.span11,.uneditable-input.span11{width:648px;} input.span10,textarea.span10,.uneditable-input.span10{width:586px;} input.span9,textarea.span9,.uneditable-input.span9{width:524px;} input.span8,textarea.span8,.uneditable-input.span8{width:462px;} input.span7,textarea.span7,.uneditable-input.span7{width:400px;} input.span6,textarea.span6,.uneditable-input.span6{width:338px;} input.span5,textarea.span5,.uneditable-input.span5{width:276px;} input.span4,textarea.span4,.uneditable-input.span4{width:214px;} input.span3,textarea.span3,.uneditable-input.span3{width:152px;} input.span2,textarea.span2,.uneditable-input.span2{width:90px;} input.span1,textarea.span1,.uneditable-input.span1{width:28px;}}@media (min-width:1200px){.row{margin-left:-30px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:30px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px;} .span12{width:1170px;} .span11{width:1070px;} .span10{width:970px;} .span9{width:870px;} .span8{width:770px;} .span7{width:670px;} .span6{width:570px;} .span5{width:470px;} .span4{width:370px;} .span3{width:270px;} .span2{width:170px;} .span1{width:70px;} .offset12{margin-left:1230px;} .offset11{margin-left:1130px;} .offset10{margin-left:1030px;} .offset9{margin-left:930px;} .offset8{margin-left:830px;} .offset7{margin-left:730px;} .offset6{margin-left:630px;} .offset5{margin-left:530px;} .offset4{margin-left:430px;} .offset3{margin-left:330px;} .offset2{margin-left:230px;} .offset1{margin-left:130px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%;} .row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%;} .row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%;} .row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%;} .row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%;} .row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%;} .row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%;} .row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%;} .row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%;} .row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%;} .row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%;} .row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%;} .row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%;} .row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%;} .row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%;} .row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%;} .row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%;} .row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%;} .row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%;} .row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%;} .row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%;} .row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%;} .row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%;} .row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%;} .row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%;} .row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%;} .row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%;} .row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%;} .row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%;} .row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%;} .row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%;} .row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%;} .row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%;} .row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%;} .row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:30px;} input.span12,textarea.span12,.uneditable-input.span12{width:1156px;} input.span11,textarea.span11,.uneditable-input.span11{width:1056px;} input.span10,textarea.span10,.uneditable-input.span10{width:956px;} input.span9,textarea.span9,.uneditable-input.span9{width:856px;} input.span8,textarea.span8,.uneditable-input.span8{width:756px;} input.span7,textarea.span7,.uneditable-input.span7{width:656px;} input.span6,textarea.span6,.uneditable-input.span6{width:556px;} input.span5,textarea.span5,.uneditable-input.span5{width:456px;} input.span4,textarea.span4,.uneditable-input.span4{width:356px;} input.span3,textarea.span3,.uneditable-input.span3{width:256px;} input.span2,textarea.span2,.uneditable-input.span2{width:156px;} input.span1,textarea.span1,.uneditable-input.span1{width:56px;} .thumbnails{margin-left:-30px;} .thumbnails>li{margin-left:30px;} .row-fluid .thumbnails{margin-left:0;}}@media (max-width:979px){body{padding-top:0;} .navbar-fixed-top,.navbar-fixed-bottom{position:static;} .navbar-fixed-top{margin-bottom:20px;} .navbar-fixed-bottom{margin-top:20px;} .navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px;} .navbar .container{width:auto;padding:0;} .navbar .brand{padding-left:10px;padding-right:10px;margin:0 0 0 -5px;} .nav-collapse{clear:both;} .nav-collapse .nav{float:none;margin:0 0 10px;} .nav-collapse .nav>li{float:none;} .nav-collapse .nav>li>a{margin-bottom:2px;} .nav-collapse .nav>.divider-vertical{display:none;} .nav-collapse .nav .nav-header{color:#777777;text-shadow:none;} .nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} .nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} .nav-collapse .dropdown-menu li+li a{margin-bottom:2px;} .nav-collapse .nav>li>a:hover,.nav-collapse .nav>li>a:focus,.nav-collapse .dropdown-menu a:hover,.nav-collapse .dropdown-menu a:focus{background-color:#f2f2f2;} .navbar-inverse .nav-collapse .nav>li>a,.navbar-inverse .nav-collapse .dropdown-menu a{color:#999999;} .navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .nav>li>a:focus,.navbar-inverse .nav-collapse .dropdown-menu a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:focus{background-color:#111111;} .nav-collapse.in .btn-group{margin-top:5px;padding:0;} .nav-collapse .dropdown-menu{position:static;top:auto;left:auto;float:none;display:none;max-width:none;margin:0 15px;padding:0;background-color:transparent;border:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} .nav-collapse .open>.dropdown-menu{display:block;} .nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none;} .nav-collapse .dropdown-menu .divider{display:none;} .nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none;} .nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1);} .navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111111;border-bottom-color:#111111;} .navbar .nav-collapse .nav.pull-right{float:none;margin-left:0;} .nav-collapse,.nav-collapse.collapse{overflow:hidden;height:0;} .navbar .btn-navbar{display:block;} .navbar-static .navbar-inner{padding-left:10px;padding-right:10px;}}@media (min-width:980px){.nav-collapse.collapse{height:auto !important;overflow:visible !important;}} diff --git a/tools/ngui/static/bootstrap/img/glyphicons-halflings-white.png b/tools/ngui/static/bootstrap/img/glyphicons-halflings-white.png deleted file mode 100644 index 484e020c0ac5e5e963631f27d5d1469a6d6951f9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8660 zcmZXZWmME*)9{x@kOoDhQ;?Pp>24NW1Qw8xE@44B1Zj{G5DBGOSh~AGI+kvvyBnVW z`*_ZC&V9f0;W{&O&HN^=vmbUhOjBI}4~GH=1OnkHDavYtKqyE+&%j0l&gAh5FAxZI zQd3n&4lo}dAA$4w`r6*!9?rwu7F6O*7o)`pzQAM z0<@Ep6TrW|zP`M?d~k3O6cqIN^XLBlejsdbZ?Ctv_xSjDad9y}KOeYVU0nq@K=8)K zMq^_mU;E4uAjt-O|zmz=1H}JUuZUNxGhXbAfm;zW1 z(DuI)m6es<-Q6Q2Bfu5F&&kOF5`m?qrl$7w_5C9N`xzS>15iMF3kwSX0q|E>R|Dk$ zxP^s(?)Te}8}vvBg>>At*C#PSiU`1 zsLuyIKDPG)S_q`rQR&m)p zCL95b6|%W1mh7*Xm4dnHW!`9ZR3({6eKH7iCUdH0W}?$7lUDoXIBHDHL!Gz$fp0{B zXdF8;2aKuF`n<%p%THoy6|IG$5wonu-SW+S4JMBrFki@7s9v>EWk~X+AUq&rZ7hKP?J<767F(il1#;iy$;E zGp(YE?Y-bqSnZR(u8vsK$6GJS(`gVcIOtadN+4Am+i^cKY3y(2osvO3($3jg#1>Dn zonFbWHe^*|c>UNBs8;T@GD{;5yTSApASLoL@eJ!DEnq69mJ$)`$s$)DK1HU>uwE;T zHc?~Ko;402JYO#Li}su>D;vmwq4p9aJY^^@hN1l6KCiKcj=8TIM<%DS^8s^VvH7-O z{D3SJ!g=H~Ke_DcGtY9kkw#wwn(>jYkkWNuHkbet#XK`WFP``%hA`Z9wlT0nNU^|47LMv>NOTgQ941GW;BE*1%goPu} zR5sSz1~Xx3Y;r_r#DDlh>!zufnc4G()-$tT>GlYDM7SyfhwkPvnL5^_@VM|`**r4; zI)I>GBhDAQM|v%Kh1(f~)Ft5l{+-P~&#g)LMkcn{zgtH-iZL|ILbH`0scUU(#b(vY z!m}J-8M11DM%Qi5gAmlfR*6j2jv=B3UkE}%Buc7l#H`sw<@&(SAr`*N9VhYmsn22w zWxor@cOknmotlv%sCJc!2thf&SDmQrtNwh5cca)BWNNTe_=E4wZ7t3oe?cIW%{g8_ zE8-h_w0`&l2&WRU6~}WGd0a<9*Q)+zWleJvSsi5*mcmx&iT8F25%+@z1v`Z%_m;cK zT07|d(CW^uItl>^6hqyIu1(i%YXedJ^0>OB)qyY(vCNs{lDAtF8CfK>fNw>ha05QU zW^E*kbEHE&4h#+3x(3F`i&A7ZVNyRd-k_q^78ntrh{voeV1Li(Y=kPLqR!U8VRA>t zRZN@;_%l>VRKW2Qs@K(BV>KOmT$glAEHIAjEwI?q$@-`yNov#hZl0><3byxecfTEi z7q1M%9hE42H44kik`gjhZ!%22pb8wZyf6p1>31~Ew7M43fH zo$5R7kSWS<^rpoEJ_#(O%6C>?>SsXS;5`QFSgZwi-kFa^V7ht#YC_A(uS!S(BhYip z8!eoxA|(xrbXZu`opnM7>y${`!Z3xl)(9(fEo~Zv`4w35BF|NC1a9mIobi61H~x5g z=gDDOmw!+`; zIMi>ZZbD7x?|(9_MS9yZQ+X+lhO`*#+U+ZXUo2=D!xS14erC8r<;hEu2Y0UWQ}+r3 zZ^t+|c~pav8Aq3LqHvt!9D-me`?kczgWoy*RfwnlWJidbPj>WtID{-9RIJU138o@Q z%u*}lvCcE?e@ z@b{!Ts{A#!n!URlsy9sCv$)9iEo-+$_sFv^F^OmA+XU;I;NmnYzXmL^{H_;i>u*g@5O~T9u|m z4htVa-6YG?uI$j8_p*LRa&-&3?n#hXP*zre12-1O6+0tz68K-pTQnm76rV1h06URR zPEEE|9;QiG#4M=V-IM*HJ&sTXcPm!8fs3apAv;Nv7AgJ>J0lJXBV4tDT6m%)KEX9t z(@7XiB-B!NP3(~(4A~wZSLJHU1fkhaW+>8xY*~OhVO%2~^^ByBPACyJB9JO@L-cXo zGc8+(pH!8*{;nmm6jXThX%2pwE?P51w6xyJZpb#y=po$;(Ic7K;K0u{ug>8bsCouy zN9MobV)%NL1%m!x3njvENu5wMN`;!L1=P>_y;tjBZm~n#75ctMLHASi!_E%QSN#y=D}!Jj}TZjUgPWQH6+3BL+rR=1@jcXUqkEi7_BuP8mj zaQjV5j4I7oKT9?(=UP!a%hw@Lyxl z`C^!>!1)ie-1J;!NLg94L*4)~5+Sg50wz5s<>T~uegw@PeVk?-+o8SV*_R4B2yozo z)OpS88nv(mY3@P}B{M|NkXB+tJj=BJ4e=p{L39Tf>Rq+&W!eAGCye_oLrD_ zL;d%Alh$V}4zdUp z4g~m`DURD`<29Echp(l~H!6ocHlm!`ANnoz_!+ySSk;prNLk|>#2FVgThpDC@W^C#<9So3j0Pe2`u$@v>7q;_ z-Y6d;80%<@2OnN;aSkschecbd7b}vX#jTo;by4&7%uuG9cqWBc)IXSl=6IlK#hK_q zq0|KUMw^CkYuq2}G_jAS3@rb@U^1%zKG=Hq7MbMc#NYk_wlh;!Xa2s%m7?X5)z5d6X5bJ?u{M=#`+oY!xVPLUcg%t3^p#A5HP{IbxRCt*_oU zX1_X3W-(L4mJH?pg2@fTh8Wy_s)ErXm@$cbB+>Uk1Cxp|c2q-17DA_F)9Ed<`1Tcd z@>f=ur-hZNrxs#eo+MF|?az^>r+OuE*mTi~_NH;~SaKC41x`i^5F*F4_&fJW^ZAs? zbM=0ZfDUXSjM9UzDDzKC(dOn_2tr_pYKSHio_~M#Lj<`#uvFL5tV1cP0FoLn1_)KY z)W^`qG=YHpcoSQekGtH6p-}%9&6jJN!!foOCw;l+_mWB(mr0@H^1;oEh-yOaJEG4b zgUIcm8O$yu{sDan)*PCaVB4g_{3M;B+Pv4=cxxWs!A_SuAGP2Sme`@`Hag;S=atIU z)d(USMODL&`~jPCS|)5IY#B7N?xG8;dcDy|?N4obQLIfPXAJe>Fl@TuK04yR2**VI z$oH;NopV*nbUwmSw6^ZYwM~I5p@IqBvj$q~X0BfiuYx#zYqDy0kSa@G{F^QcA}sM; zEvr)dbj|vvW8j|;$Hu&_@tf?h>Aw4a9SUD+r!)Q8Ed%TxMEcde3dXIl>``9^=gZ(8 za$w1=sR=lglQgG!!#_p_1{?Cr>oZ`w>&jYPJp3VRPNF_YVui0-9M}|Sb~AK>n)wHH z)5`|B+zaqJjL}@mxVGm7UcZ%v${mi^#H3Jcqk-$-RI?F|g)hBt0zE#+Xq%Fy+{6u# zdH?WUEcP|pd^){8mbqR+e4HV@Wx0Ol(48A%P;il15^(N}O;OXs>>WDRy|m8_zV)Qz zO>Cf;$|+#9*HtLH1!KR9E#T-YLaQ#Sv%DA5^XuIiH$BPJTmt z8mpeO$h|l>6`cEJ(-{>GS85|hk^9s6^RS$(*-EuyVUVIAQaL52@sVE6n3O1Dfo_WC zZ9YS3=3gPkS7gl#UpjIe@i%TCV;^n)`$M&vd8Ew8XW&86Qg-C&W>7J*|L)|b=_lqS z>kG%UuU*ccvM#<{-tkY@@7M{|!+fsY(Nz%3^v|bi=)C%;_>-Gun0)*i)L_s0mGTt` z@oWbcmW{_G}QxYlFrN;wdr`Vc~oc_id z+vRx1rVZQZV=l%IA;-TvP_B8ssW4Gx^qRz_LYH!^s07!4W?=-8;Y)-o9XbkcT7+jI ze#fM-3$=dFyWn!`VGr?nQZ`QJza=8p&~`rdg(^{Uh8~YK-dQMwI?f9Xs`Yac%;Hq&{YJ(ie%oB7h1Y@+j5tDH$Nowt|6?9eYdV=q`Ju|yjY5mH@F~n1xByRJ&~N( zaj-2f(7|xq5pBh2e#-y}Mi!-hsZeOU71+%$~;6Qm&F~WLSq1({ zjdRWPy#9OSF2GyD1J+Fo9)p{LXj&eIavg1+bYG^qD8=y4c*j;T75B{5&+`NfSwxt! z8{0^aHCBoxq#IU0MHl^%eZtJ@Vd#h$tR}YMWp&wp+t=thuTv00Fd&ip>FVm-U7%r3 zyoS$nEQhg3ZCk4w=3}tHLs!qv)1N9`UMKbwz_7~}JxwVnQc~ue60~&%1;s+ssKrYK zu_5F3$fX(C+_G_$h zyYYQvyZgK`8oL5k5)MTb?Ahi`&X}#Pfdv~n3NQP9R(}0-e$8vwDt~>Q$vY7eio8^Y zw!>UH_uUqVz*9?~9Vk@=zYkY(FqnCtI2jNLU8nOFzZ3iCx3AL+oJw(H1Fh!qqL6#fzN8xnbqxQz}gf{Da9a zA%vfp3?`}e%GDyTyL!c_x7Q;rR1z|KZUo&85^ok|#o1EcuisqH2F+F1;Wug<1gNtF z7RqSDrG8J+m0->Z^oRR0=O>waS{3GO%_+K&%@qZa`0KYSiQijDp*4_m*&se`))lA| zLR|^Qkh?2y;D?FzLAx99zo&(LH^#^2^ly4b9U+uGOejS#Rk{R`zXBpu*Po%IE#u#G z^;Efna@lSox&bA`H)3{;1WlQFrU|ShVK}GnxB1P7m#P z{#2obC|NXb)El6G~Tx#otlZB{IU-*c0%vpWg!Pm zW}q=EPj*Y}F9{E6&=;{xj&IGj{yA5Chyg$JS#V9cSZl42v!^QOxFyI^36ICLHgU+# zabNW3(ZF$8=`K!y8@lO=Rl*N?EpSUYV``Pon@X}col%&n&An}dga)F{&ZuqES;QUw z=yEo&Q7`I#GGIinn$NyjoPt<(m0`WiU=eSU+QKrouYUDn56L~fU+l^ zIwhR5+n<$La|tfEf*-f5{yqVB##>kX;uh~0>6_X4-iAsKECpf5P#2 zqW7vH~rM6XFCPCKBW{Rmat@xyKKW=@44vYYs)trp%;ji_CT-SZhAUgi%M z*Zfg{vAyUKp!M)mmADl}X9#`w8|892!Qj2ell)5cmGq_?e&a{sJLBJyG@6p94FQJ^ zzgu^!8Qny4rOzI}wI9xMw_K3O!Yd^pbp?Zr1~aR_`6V-MmSkls68n%JkLfYz6L)sl zZi<+vcE^f+UUfeoxV2Yg+c~Os-XXgZQ%Boi%cr^K)fCoNu;9!U)qZ3b=1FVhZT|ZX zevqVjp#z443dbf@U8*?LnpQ8nzt?actY5 z#F7klsl5Ij*mz89)h;%7%+ZQ?`O^%F{gu!FES8|;&lKH6a!Xf@0s7F91IUZ zR~byMrk-dU4eeSj{jvG3fp1t z>;B=Q!TRt;=&jOSNyyY{0D?Bi&&ax3ZpFvLR-oT75%FGjlH6ciJlXiCDF#X+y}>4* z=V~oGZcspR8e%9nue{Ea1(Uq05*7#Eu>(V!1jgvg*-b0c4cLgEzEJojAj-pIz#zY` zb(itZ(2+qt)s!!#GG6mih05#a5!cg9Qt5! z!`hiluBi%T5f;5Bt`z=narDlu$vb82WTor8c=eik*}7uaZH zuIS-f^1OI|pQFH~kt$O?MUn>k-ioV0lgqOWi||<7b9^`4fEW<~t4o}7Nj>XCdZcA+qbHwL;{ znj04z7)04VAKtG2u$T9kR3CDX7Aw+$MxC!U;4n}5OQb3~^j!52m2l*=ky?^>$XfR2 z$3B?v%9P(eWF-&}Z@FjrdjRN*TB^X}DM}RF59PPY<6h5WHzupyOv%9FBAxu^#SCPR zL*UDb|HHW71HrUbhorUxe1VCo`M}wDquygLx$mqKmN=NVb(-N>#tKV>k7d`ZCHz|b zSQqZU^QroWEGh!pn@saq(h{*FSnqt0d3FfV1>*XHVZR1uXo?WxyaW~3BhUu5tyS}+d{GHW3ARb-1oo>>E z#f0iVuJ*tj{QhROpomHOP=kEevS{e&H+JR+JY&r>YYqKA)=A3J+;G488m3u$OEFOE zyYCPuiDbB}H6oM!owcQwsk4OtX<{OIHbwtO>6M4BqNKA;M5}33E&Rcj5Amm?L=2lC zT5+%U%?@*&zJhETabe!UM6K-O!O~-ESnb1QR1|k|!S#4M?)uOm;S)x%cIwqXue zaBxTT3vj=&vn0*+F3r8I^5O0`&9;qQvN;Up_dR-}xUv|!ewfqEn`z&~vUsX&t3ru~ z;W&<%i>f#ZOcGaL+DN*#&Iu`l`Yff-QZxnJtw&7|%)b5YjogGLp&n5xk2gzq25aVb z?e{d4uQNP)6E;Z}A7yB6W3d!h0%)$MLtGJ)h2Iib%y#VcFz&Pb?ld&%)B?7i8J7qp zoQuT1&iq4>#&z=@Vx^Ck1;vfD7v?jL;aQm#xG)vrfe3M1)^k z1zaqr|0EY}u6FabTg_JS60YIH>1f>=6JG!5sZJ?@XVONWc*vI#MBn!iZ*k#4padr# z=oO~peIR@iGk>2l1qbtv~+iugwi3kq;$75EVXn&1d1PJHJ?3u4*Pe`#liR|F)?C#pFQJi zQf^_<1RXM4TD@ZX{&VQ+4=AhvKSPnCsTjgaWsk@9?%ms9 z9!&$5{1{(tw<#ObSPa7a=6;#KRMN?(8dAX5>RwN#Z>=#2~nuV;_$ zObiwJoNf(62+rsQ&pJiAJlxhg_B^__JrJ@S`JtElFaDH%vaww?tRNA$8K3$~&Z~@v zU!{_66LPp_4Nrn3DnCCr9Iqh3S+nNB2N(zcQ9Ji66g$Jl0A0R*_(YlNk${YP9rIq! zcItDd9*qH&&HV41Oo}#6xhckLmN8DX+uPKRM z2{loWlRvSb<#UYgJL7Q~&kVUU&;XZsIl5F&9>JOk8S-4-FAfJ3tw#cac;SRqz9s4D zS9{ZbYufE2H5I${oMU}OZgm)yhO~nkmi(Z*@L_(hN>Pj?d21mgE7$MvNlW|Csc)Af z6&ujsn|#djDVNs4;)m1S{5N$Te;;BrxnI(Boa8KTBJb0bQ-4Wa)&$f)L;FjiL7~@T zB`^0^_ly>#>poy7m(FQ$OjjW$z7^L>)^Jyj@7-0fFd;k6JTLpvo{&aeNF8zRS^kk} zU`}XbV6MoqO&J84(I=|Sxec5vb!ZA#dJO{0=~%s56}-@~64YqHVyGU^l?*^*%PcH| zVyqzuS}kcF)7Hp6Z^6Q&7kJsN@%Ld9`~3!(Hd&k$NuHxYpFA*c*Y^~^o|_+4dEPNo zG2^sfLo~jHHQA2d;EkQ#4Tdbb~>Uukz*Mjw%@YVM<6%rI!N-(`ShAoTm5~t>@q#?8kssp3748q z=(r13ctv0@jZJRvz5+*DS;_+gS-7n6AN8R;LtkgMlFl%W(+KnkG(1|ZH%}(Cvps!Y zKkj$>eqM55YUSfbsYWtC*{EWK zE()g%5%+_8XG9{zueX#V|0NZ{!;l<4 zi|wG=(}CWQb4oGR`4y16T~&R0PQ!%;^k|}Ow4wX1atF1ppL!WpDcy3ZaxN?Mn3?=u zNue{-b2=P!5fa^BP_Pv-$h~v%GV=qGTk!{isRdpLBUi_H5d!&|^Jcpi(VJd~jjj$t z$#_6Acx{&buDXc#mo+VlWG|V}6#T8504>pipq(Ku1#JkcWJ~LnW3z_0Q*67&CL-X@ z8Vj{VN3XvT;GH$+?>0u@`0$NUVWG29miW1Q;GKJ=xKj&G5PeQKoyPcnx%SsL&KHG4 zgM$euPr64Rk`%`?-{|-wMJfm@M1FdE&xKAku0}*@p=nS1h9m6PjTAtrMPHUwyD-Cc z;yU1KUl*%wu^2%-I8i}Pr|BT&1%d(k)Y5+?^k<|Siwenn%A$s29y1G?1p-d)W4UlRQCalL&S1*Klr={ zWfTwu%UjXUnSbQx8UE9e6+NcY@$DI@frM_(D@bidkT_Q@ZD?EtyY~I+`XZP7E_B4m z1bELHQbNu9da9K_8-rKt*cn`YYJ9@fT=Dy10zLizss*$T&ei1!h2;S%EhX0{PpknH zf9LwPgz7{`NADN$Ah(VbCW#7s@$-bnK#vuFqSm*e(IqcG=15d=C6H$SjxPNQL0t|c z!m>+Kn2=C7*+*}W+Z>=qtDII_#92qSe>Y0d+wrW2@I0pi6f)nL^^&uqRcoRUtzXTg z{hB34wDi-BXzf^heSV1qNJC~LGwNc=^Ca^HxjOE9P_Xv%p6fhKrKVR7$O`d30S=R{ zBdZj6pZdXECUBvQMdKjP&|IGHQ@n$5R!V;FXae|tZ#2?2z(L2D_l&Xg*_1S1O#;O4 z&4cKZ5iIeW3ye7RHFr2UB? z(x4n72Clqx>WJg=mR`pJt3^un3erz6;-ODE-5gh!-p>Lo^pm8c zs;&S2)8LbcuJxT^)(VIjqD=FPmwI$OUbMO}K{-GwP})K=6$!NcGRfIfM3~6MJi2Rd z-Tt6qLxONbMJoEGC2(o20R+C8BH`24s=$MYet3$+r-(@44`Sl+*_m61)<}c zoL1+CP7P|S$JJ>^7~TteN-)-IpLV_NVO-<;l)>(;nANhE87QP7c4kU#XNN1kyG{6%q{k3>}J8pG9@A2H9=2%RTc_Y#^*&aK_vW<&GIa zc%okRj}6}kah>$O6xx}7d4}$yed?lIg&ZhfeEeq%>fxH1n1Whzi2wDq-N9kBBZQUL zakc6;=~BAgAO|G(l@H3bgSQmJQ2_bn!^;P58=jqb{2&xnLc5pH`!bj$Y7mFj9l?xY zMbu>cQ<5h!O!)~X*1s42QY1n=)}Agc7OjZz-g{Cbbv@Lj3po4zh|En0^U-_c+ zPa|8(uZ_y?E<+(k9_`*4>95^;3(ef!ifkG0iy+`by>r7H(CW2e4s2GT(!7zcMCvjf zEAGzPQhv$k=M>V()5w(GxFDIiREQ|`h2oH1`_t6;OvyREb(c$>*4okqG}noILJA1M zD&hJwV0YH#VfpZMr%l_Dkgzxz`D0SYm}PU9h;2KPOF>7eS>p_zK(sGg7=Ir!&&h8c z*!ZF@dS}khgd`La{ZYD%767%qtvdZu1T4%v27^;`ygJ4#Aq+MHiLClM&WJ)!0cf}pXLrlMocfr5@O*i0JLSqqp*2dx-N9L$y6 z3*NKi4!hgmXvtkn@;_a=?G?{VX?R>^j%T}&zJtDRmpokjhjjtRQNPBhZM*{`VBU&| zqEy11ANa^?JOO6)U=;^3$gxd?Fwe2Wmi%-Ug~br#D3xn57o4%isUnRS4fY*r3=$Ay z29*29Zuw)33takD2;xJ=Ls?Igj;K)Ay^~m1QU_$I_;UP3R%H~e%mL83M?)jlcy4LTi51}|?N@Of6$f(QN zu{(7!p#lJ!VQE$PdSnYkjJWI-NEY9a^ASf0Qz|3)a%y|DEe@gzA6Di+)DdY)RaSS& z^Z&`K2tQFj(91CGjO+n`B?NoPz4qHmW>;B(Gr%-e7Nl-dmS;ttaI6J}y!? z^-_k-(2ZbJOCb05rZT|GWnUqDw~zCJOcvQsqpmx)($uJF>=rfB=%_o{IbLZaoptYhtjTYZV&zN4~ocrO#8Azly691dU@jwPFgq$s)P= zdN^wkXSanU48=a`Huzllb^QfVAKv~9?l*Sh;}=&ZUw%r$mB}Ahee%ATma(eR zzh`r9p8It&Hs!d5Q;zpT?sv^pd*t>YeORenU!@BcE;_I%NCEUsUUEc7)mnfrzoT?2 zyaFaaY*LYfSs%X={lb=R!gh1*n|?_)-4GJM_)|T+c!#-J_9RpIuIElhYchNwD}kLL z_dFx7CPVJzgCK1^Uftmmz)3CW*KfR?*1d$^1Fu4o zT;Xg~_AAFON&-h?(Pi4Jxk{t_4`0--^KS-T<~O)FsyGcR{8eGPhWPPkSWZ;eQyG<$ zEAOZ&rp8<8Os2@H>=o-g=~$!+3Q<;e>zaLy)uy3t&M#2{dnN?Y{4m{34~1@2b=~|8 zrmec!{1f4UOtraIijzLiP$udQzNFa?a(s!^tsjITwGLK; z^!ga+CW``aO3de2E4%p&PU0z034nsCWcGfL%$o7$a ze+vu--UeI;hpEc;Oh$=rC#GR3UzK65+g4~tZCG_b=aM}Cig@;8JW`*)zjL!~sHYua zSlW7t7Z>N3iI>`i@v41HU&&Xrryn?B0kDz-QjcfF}bQVkGY#%ym!Lv-WPc_4_Q(+6c8y}zWbI`m>;xsp9 zdJcL{!WThD?~r#?VIk78&FWg`e+!=4BXBprFM`GtM%S;gP>VQaSdK-m>5T*Tdvl*p zN&WD_zan35mZVT;P)DJu+Aw9RvLFhQ5(c4bu5PQ#_kSh;%O-obZHP_X?C*ZpzONqV{40W=jB*?oBr=sl)?1pTyPB|zB6YFQ&t;I$ zPp^sVX^LAI*fXR1KJ3-H)lnV&+1NQ`I}GB&3m_smnV+EiBXy$7!QT2rdqy~|6)i`U zx-FwLss80z*Yf~0>8q%V{I|9Mu;{J~$hW?yY%fs>7eu2y^J&i#-UO>VBqq_6cU??+ zAb^SthABPwOICFS8D$bI_7_Abxv;S92VQ;J#7+?Vt#*DHDQWkfcW>E~*#h;hE$98+ zc-QX+Gt>XTlnIBxPcrhPd9v;a1AF`3aPp|##_7*acUCz;*3sQIQ+6LCheQE9U zsO*=keF%M_12UekmOX2mEoD}T$BkS_jEj5UL>s@FisASi)OZ}v`l5QDbr>GQPRTw+ z1aJ#5>$O;3u*CY}$xEBbSMwYlnTc$2%0pEDb{lSQ3!}89zj!9R52*@vIp_$!T(s2l ziHnG&Y@o=3_V#~pqUF=b#RRd|Jy>I!yGy%vvJUl8St(p8KQSFV4v98@nXf_%m=q@z zu4+2|1Yeo)ndHwU`wCQ(SSPUXQ4#=EP5+oYU+q zdVf{4htZHOrVF$71x4*Y=w7@ZOyKy=UPs>id7Ww2vL4C6r+v|qkrF@4H7Ts5< zBi`7pdx#E4|B`f46Z})V=p^;+yeGeFr?@CSkU-jDT~6_v9DKb7Hq)^ZrJ@be z8_wHz+uZZ-NLRR2cdLeZJiee-aWvu^mW?&4a1{3~{jN2Bf3+>|I5q!c*i=y+jSpaU z*%I64i(8Sq2G&KIuJ(~L4Cg+!!dVj(Joz!??@ZCO)3+PN^hiob%jfYhNDch! zg*d+OpEVWIzMd6Wr&*Y?_Uuhx;Z=Ke8YhyI7v_@hVyccHsM~YTBl>CY>_ST@Kq`BCK*Pi)4G(~<7 z=vgzR$qU>IBj~wzD~oLzF)jhzOx@%@=f-GTOxM^ecYyxD0X?rYuY+WGP)urPOCSk| zj@FF*q6WJ1>5O0dJG*H$mM*Ysu6nw;=%)bXj2~Ro^mQVWeOYui6v@M|ZTDTaa#GYW zwP?${-|S?Zh9&;SNRmA65E#!aVz*fi6+xslOTG-S z3}g#_T3eRM*n>hL^Yf8FT37?89uB{9DcAfPfyiuwhdMKmtB}Uq}J~v zg=*9>=TL?#Id91z;`hI^7g>px?jAV#_^n8@P3EiHrJBvMYfTpeGnjjB9J|+xAg$tXb>q}uNP!?GhP@hz#N`*` z888`3Q>ngXxbEg{Ea!Hh(-!Qzn)>4lpUL5a{6C$W1Lb{q-)Ht`&O(aomf^W{k?MEo z#d@R0uJ^=e@RY05jSrt^h^00lD#L2VlX-^T{C~`N*%8S;&Sk_-sT=2}X! ze6G%=f^7xoaq0Ph#7v>`2@lk2(YHzWi}E}(Il}Sq6=93X1bR{%0TYp)pqe@N{lFgD z?U5{xdBHTM70}PU@{ET6-7Yf}TD=lOM+CBJk-O4$Bq6}*sVw;%vQm*G14^$RM()&w z{c%LY(F5A!{U>6UiR;y>cgPxZnk?aTM3lG6DTMnjo})du(h2?3_Qm-WijUV;dA{Df z0YahDX(kyDjCT}Kh@&A#Krhw1NW(Y0G1xh1K4=jkX@`FzLKvco`bG&CR0=a_Z~XC+ zfOvIjF4fdaoW=6~jr&o#O&kGg85uC40LzK?#(pCo)t}kZorC+p4r?2Y9dH10yPgZU zxW`MHlJTp@N;C9K<3#hu6`XeC$OpK3`5SGoZHO}0hrVl|qmTMMQZ=!J#AlT9(_47u-`T6$6x6v%+ zM@Gk%gn(rirgtA=SOcbCFJfneoa?pjwekQh?bljV7QD%(^DaGpeaYZZUM(8IS_s9a zGJ3<5qqLE|*2n8+(?9iss`p2Sv*y2gSkX+Ziq9WlW%)t-;aY|v?eYNRn`-0VIF#EF zf*t{^OXtnl%>_UFmF6RfhW`BA$Nrgi9L_d#De$HMQJWfLjvBSu0@MS&+V{MLiZ3Ot z4nEbOao+=H6qt74M{to&{hrurG-sELs~bsUDnkq+9<47m=dG6CVBS@APJTrr#S0BM z-YIcyrjAUHcANmw-SG%w+pS;G><%q^mk7(gsp~GOj@pPMqPas~ZwfG5##zBt>|wrP zF#kzYIAu%s9f4(xAP^I4ZzisQ8zR&e+VBbmW&X1rTRa zpf9}gU9P@|a^zYF_w*uQxY^dR_cEoMGL6oi4u83Q0A$O2#i9e#IAA9+Ein;rsdZ_c z4E`xZ!*GwHFz<{pGqqPB-4<$x#cs1BM7toW3O&`{8*O+AZz(S?S2>%Z%i?FSOtHfs z&t;I~euonk`0JjPK{Rr1LclC@S0J*M%=gbT{V7PNM&}>`u;X<{(NT~CW%r&8N_mqk zxWSz-d<4(d)eN$4Bkxn89dXbS3fg~Z)xDG7S!zkt@5rU*f3QtvRo=WWUw6Uv`#3O5 zUv+Zd53Pm*h!W7V)I^Er8voIa+O>|sqf6noZTz^$#8>%BDPPk!skNIp!g_>ClMPPY zE~=UFf~Z#WAL*TYj|qEZtP?!b@Pdvs8Rc}P0jZ$;ip$*S$on`M*p-@85*U{QBtzS9 z`@ODkL^N%1;J7rN;ZX|wn>usHoc2KZcwW<$puBmT%h|jrx@X46g5bgx*nu4~T|#B+ zF;b#?0V;qy43FhPSMLwglrM^&P=VxJ!@8rg1HNK^=PxjcX|wlY6tkK(%A-=B_;t;> z*3AVUDUQ1@0)(r5GWV+YuEY@g?M^fKa1D-s?-0Do+7TfZJi394nTkok9*@(oJ|FF# zlF_sDzI39Vbfn(Iwp$~$FNv&TVW(Z|=a;GJ+KL!G4n z50pYX!Yqp0;233tTK(se=!Elw$}oQ2dbHhjlTO^*n3q|P8#?tr{{_M>`(rfXXzY$y zXp=iAcZruk?u+_#sifx=FBW2-{U=F->domj7hi|cif7p+31!pl4!jV4?EZF+>*`=! zQ>vpY%olT`ZQ|!{=b%_>06N^3*`AiCUeK0k&0IpnIGcfhw!fkBf0m^~E=efREd^P~ zXG`vyLe(VB*M9F1!5qRBp+mvVAJ=is4H}~D(9BYQ0OI|;yLDlE13%SST z%d{4IU7t{^m3OZ8>`M;$Nz^BK#X%@C)bNDjMe+Of)xaySZacek{oVei3{7S#1d5cbob1VVv*2;hS!?IOsWj z$y1!Q>L7S;kyuk-s!Jlw=v{6o)MSR_JLClIG*VXtXsp}taofc9*Q;tJ)YMHathChX zL?T{Dv1k(+e>Jn*nm(rup&sK;l4?CCmV2$~iEP=+b)Aah02Gu~u(f9eIYs}>@<*uC zFS5dpS^$X7M~N<1RKgNe3w_79l$l(5R9^+25Wwagd{rj3_GfZ)vLNRC;z4REvPUUu z1jf7Q`SFZ1NjSH1jA)6PxmPR9u^$v!?k#c(o)wA4vvynig$OxQ4p&+>W;x95M04}A zeXj7i{fA`EATC8GCwOHH7nP=$@9UfzFh#}mxM}WUKxH_sE@-ggf!1=IR9eF@V+Pi& zm$tW>A<|lEae7S9qBbVpU7N<^2)kvhkp< zMrn#$KAU~*18~GXP3I-`wlzVCRDO|CUgwmIs-i*#W%LnJ^Ohgdo z#YvaJXAMf!n*_R?@4EUe6&)~A;@=PMlTSq ztj=X4U;T2oS-afqt+y+2-Vwu@R<*O&uQtN<{LSEOi&vKFePoCHqg0P&EyzrSS7%r|%#BA}HUmcRs`0*sD zkOG(uK3WLtX6h2~UNT;EAUgx1Qe6D2b5+^kB&@J|&Kk76!M~|oiSwTvzDncnZc>5Nt1Ij!(Pit7 zCS#egg>n&VLu@D;v$zO4K=P%({Si{%nCmiB-QMqNrn>Rx`~B1=~14VjQmYShPi1$7a!}cy-vcubx?BvR7K*fi6!6 z^OP1hht_AcAT}|6U1;E0X)-@{D>Kk~|91HKROPoS$mtUMD5am&3ZzT47ARhmS+pbd z5F^!2jNUe8g>Y*bB;r}!q1s(gbYl+VM+S$P`=7$#_JQk(;&ow;3M7~)KpmSwY~jPx z^0;H}YP?YGF;AS3b(5oin{fwZ2sEbgCnnO3yPMVNk5Gpw8b$Au_lz@`S{AG=~ zP$Tgsbg@o{;dw4jbQ?ZQzT@F9^|$TpBXu=FHD)UGKdHS(pUNI*@|)sSn5BQZUhYI= zuiw>d4bA<4&ZlrZ1YuJ#)Y5SKxp#*}>|=wj)XwKX;*D2Ga@CKs<+`bw-}$}B{UW8@ zKxdX{^-=yHRb8C#F4&)n9P2-W#%HG3b>j|p1H))64nre;PIxN`dCNGDfVBL!sY-)h z9L5*`%XazT($lYcN5=X|RG9#t4%kFQQi4KPEpptXL-(94T(P^3e&c=fjd_ZL)(7P6 zT%2+%^~3Np+Kq9oQ%Jb%HDq@(+##k+9rnu9UZ*qC)ILp(kQN(1jV;1~aPk!`02l>T zm;6^nye*N&n+g2G7xDz14Q@NDJFhRRlJS$f)BbFJ^eX_|V7E%sY8KLjWc*sC6BER1 zT3$k71Y^c4zdoH05PcJYYxUZr_iw5c9uw`ydasIP;!o!PM z#dif0gLbcZhl}f|w;`b~8YbGkY$k)QmL?Y?z#ymIN=+bcpP1)H}mJQFv5uMIJrfmVrB)6H+2t?2dVgE1qq1up`M?Ne3!a*TTS z;O@JFQZ$H&-;PY8_kTS&{9ASy0yH0nLf!656VxuN?>yyjv(nN0EJ6N#YaR zs~vx0N;uL<5Th(mtJ>YNQtm7nK|`2a>jYDTHF89pKrf^Ywy^BMbSU_k8!0ytqEUW> z+ox|Y71OhqOP3iJ6c(q_$-n-n1_jUw+2R*??k@VEqKvH2cQtSPzDezcn0%i;elSS2 zJ@=~O26m-@Tjk)cee|!N91abJ!JJYIxr&|(x03ajC$>CP1(cx8X{Y>#gFZ-ooC7Z4 z;=4UAAd-5AAo=)HzoXwT{;D+FhXU!plyg=6QtqgiceymovR+G;vtj>8H=7auqP%-J zTWhuH0d)=_hhCs=Xw6qfyw<_XZ9e@BbvI;Sfpj$*#U^B(dR(3Is@qfW>5AzO3NaeB zpUA_;;yzDi@_Zn|yX%~Je#;KZptf+SsuSF~s-PDIe9W~D=3g8@*k3G6m`l{jX?4EC zDS$7s1^^H@{Mq!P@cx1FWHr-mz74NohBxy%sq&4~AH2*=^gqy5BuTMNOXAs$;0Wmz z`w+j)XcKgqA2MoDMm8qfLVC?-VBDX^>|cH~dGvgbRpf9D?YwcIuoT4&$6;vvf#{=!mx zbG8p(+}swVZ($n0t3g>hF#Ho*oy}-&$S5zO%ys!lkqra$-UlPN_R(sI+?r7&i-*wP ztCFYItbk;)1`gZ9*DbByBJdEfl$2sBdm!ie*9!wwukJ|cQa3N|!6dir2pKQvZn2hf zM~~qy!omN*N+6c0^}+ZZ`Y9;T!Far`t@)_yr#8uhx65_{6a0}e8H}4I?8ON^`G|y& zO2E0y zHwfj=UWyYIQY*M`$KLhLL7k(G^QS{{&ir>b@Xn%6PSaD=8lrNmYO}=PvL~(}%+TVy z(e{$Nd8nn#;#()OBJyT+cq4w*ff5Z{3Ac4J*o-&Yk_&bN{5Q!(?ul3JUxSiEo|ADp z*Q}4*t95P$ZH}6XB2k6tZJoz7N|{fLbe5=z$qi@_*Y74jM_y{*0ggw>79bl)b_Kd1 ze83urieP8RR3+#L6LNVrBvYXbzVrKYS@@5qn0Ewg3_^{TT)=t+`|#cy95eiBykvf? zxR3%On(Xd8YLW@cJce;y=N*sJHw-Yeo)b8g0_Lwu%z0fc!=irx4*cA&bx%1%`xVNUt(@r@B(pv^bL! zezXEM593f8moMHT+Ej~dzd3VC!b92v+OtTdptSzc5>yGJbeN1i)sxD}2;*~vm)9mn zz&A*FULC z5Mt?M$rTS1X#IZWbU(RZ?>{UHu?M(+zc$OTeD1czjxEQAUpsF%deXdShElMZ=WD2z zXcXw^WoKMX=Y_Pq$OhthnV(ARJbl^eg!v89nX_n>6@0r|wqxmg_1nePn#kApYZwj ziyk@_I>|o7h@jYs7NPOyprsmFj8G=6Ke*J)n>R5VqvUYU^%I(O` z*Rw>VS?k-P@;!jN(=79f<_8OStue;X34Qy_Z2JpeQa@mCo=1D@zJ#~==up7W8S_Ve zuh}~+$w*6@)wafdLrPT}g$H`D0YI7(l>LnSK!ej#e(znVfWZTpE(f7Lp z&yX6F!)CZ!Xj9`Ue*hDS=mO}?+qc; z;q$NPN4f+#)}{k^^@KCJ zu3(J*Ij?>RHD=IGzAs+Um-u{S*SkCFBkh+1kCeaXTK7V1gvIIB>|u)4c94ea>;pQ-C=YL') - .appendTo(document.body) - - this.$backdrop.click( - this.options.backdrop == 'static' ? - $.proxy(this.$element[0].focus, this.$element[0]) - : $.proxy(this.hide, this) - ) - - if (doAnimate) this.$backdrop[0].offsetWidth // force reflow - - this.$backdrop.addClass('in') - - if (!callback) return - - doAnimate ? - this.$backdrop.one($.support.transition.end, callback) : - callback() - - } else if (!this.isShown && this.$backdrop) { - this.$backdrop.removeClass('in') - - $.support.transition && this.$element.hasClass('fade')? - this.$backdrop.one($.support.transition.end, callback) : - callback() - - } else if (callback) { - callback() - } - } - } - - - /* MODAL PLUGIN DEFINITION - * ======================= */ - - var old = $.fn.modal - - $.fn.modal = function (option) { - return this.each(function () { - var $this = $(this) - , data = $this.data('modal') - , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) - if (!data) $this.data('modal', (data = new Modal(this, options))) - if (typeof option == 'string') data[option]() - else if (options.show) data.show() - }) - } - - $.fn.modal.defaults = { - backdrop: true - , keyboard: true - , show: true - } - - $.fn.modal.Constructor = Modal - - - /* MODAL NO CONFLICT - * ================= */ - - $.fn.modal.noConflict = function () { - $.fn.modal = old - return this - } - - - /* MODAL DATA-API - * ============== */ - - $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { - var $this = $(this) - , href = $this.attr('href') - , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 - , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) - - e.preventDefault() - - $target - .modal(option) - .one('hide', function () { - $this.focus() - }) - }) - -}(window.jQuery); - -/* ============================================================ - * bootstrap-dropdown.js v2.3.2 - * http://twitter.github.com/bootstrap/javascript.html#dropdowns - * ============================================================ - * Copyright 2012 Twitter, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================ */ - - -!function ($) { - - "use strict"; // jshint ;_; - - - /* DROPDOWN CLASS DEFINITION - * ========================= */ - - var toggle = '[data-toggle=dropdown]' - , Dropdown = function (element) { - var $el = $(element).on('click.dropdown.data-api', this.toggle) - $('html').on('click.dropdown.data-api', function () { - $el.parent().removeClass('open') - }) - } - - Dropdown.prototype = { - - constructor: Dropdown - - , toggle: function (e) { - var $this = $(this) - , $parent - , isActive - - if ($this.is('.disabled, :disabled')) return - - $parent = getParent($this) - - isActive = $parent.hasClass('open') - - clearMenus() - - if (!isActive) { - if ('ontouchstart' in document.documentElement) { - // if mobile we we use a backdrop because click events don't delegate - $('